conversation-session-id-compatibility.test.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. import { projectSectionSelector } from "#e2e/helpers/project-sidebar";
  2. import { randomUUID } from "node:crypto";
  3. import type { CommandEnvelope } from "@zcode/shared/zcode-protocol-v4";
  4. import { admitCreateBeforeExit } from "#e2e/helpers/session-creation-resend";
  5. import { startE2ENetworkCaptureProxy } from "#e2e/helpers/network-capture-proxy";
  6. import { verifySessionCreationRetries } from "#e2e/helpers/session-creation-retries";
  7. import { mkdir, writeFile } from "node:fs/promises";
  8. import { join, resolve } from "node:path";
  9. import { DatabaseSync, type SQLInputValue } from "node:sqlite";
  10. import {
  11. TID_TASK_ITEM,
  12. TID_PROMPT_SUGGESTION_OPTION,
  13. TID_V4_COMPOSER_INPUT,
  14. TID_V4_COMPOSER_SEND,
  15. testId,
  16. } from "@zcode/shared/test-ids";
  17. import { chromium } from "playwright-core";
  18. import { openMobilePairingPage, seedMobileFixtureLogin } from "#e2e/helpers/mobile-pairing";
  19. import { obtainUnreadPairingUrl, showMobileTaskHome } from "#e2e/helpers/web-remote-unread";
  20. import {
  21. clearAppData,
  22. DEFAULT_WORKSPACE,
  23. getE2EAppDataPaths,
  24. setInputValueByTestIdDom,
  25. } from "#e2e/helpers/desktop-app";
  26. import { startConversationModelProviderReplayServer } from "#e2e/helpers/model-provider-replay";
  27. import { restartIntoWorkspacePreservingProfile } from "#e2e/helpers/model-provider-restart-runtime";
  28. import { seedReplayProvider } from "#e2e/helpers/model-provider-restart";
  29. import { openWorkspaceDraftFromSidebar } from "#e2e/helpers/workspace-agent-warmup";
  30. import {
  31. UPSTREAM_MODEL,
  32. UPSTREAM_PROVIDER_ID,
  33. UPSTREAM_PROVIDER_NAME,
  34. selectRegistryProviderModelById,
  35. } from "#e2e/helpers/upstream-provider";
  36. import {
  37. clickV4SlashOption,
  38. getV4ComposerText,
  39. prepareV4ConversationE2E,
  40. selectV4TaskById,
  41. sendV4Prompt,
  42. waitForV4MentionOptionPrefix,
  43. waitForV4Pane,
  44. waitForV4TimelineContaining,
  45. waitForV4AssistantMessageContaining,
  46. } from "#e2e/helpers/v4-conversation";
  47. import { waitForUpstreamRequest } from "#e2e/helpers/conversation-session-network";
  48. const CASE_NAME = "conversation-session-id-compatibility";
  49. const LEGACY_IDS = [
  50. "session_0123456789abcdef0123456789abcdef",
  51. "session_12345678-1234-4234-8234-123456789abc",
  52. ];
  53. const paths = getE2EAppDataPaths();
  54. const artifactDir = resolve(process.env.ZCODE_E2E_ARTIFACT_DIR ?? `.e2e-artifacts/${CASE_NAME}`);
  55. let replay: Awaited<ReturnType<typeof startConversationModelProviderReplayServer>>;
  56. const facts: Record<string, unknown> = {};
  57. describe("SID01–SID05: 会话 ID 创建、历史引用和完整重启恢复", () => {
  58. before(async () => {
  59. replay = await startConversationModelProviderReplayServer(CASE_NAME);
  60. });
  61. after(async () => {
  62. await mkdir(artifactDir, { recursive: true });
  63. await writeFile(join(artifactDir, "session-id-facts.json"), JSON.stringify(facts, null, 2));
  64. await browser.electron.restoreAllMocks();
  65. await clearAppData();
  66. await replay?.stop();
  67. });
  68. it("新建 sess_,两种旧 ID 重启后保持身份、可引用读取和继续发送", async function () {
  69. this.timeout(480000);
  70. await mkdir(artifactDir, { recursive: true });
  71. await prepareV4ConversationE2E({ skipProvider: true });
  72. await seedReplayProvider({
  73. id: UPSTREAM_PROVIDER_ID,
  74. name: UPSTREAM_PROVIDER_NAME,
  75. apiFormat: "anthropic-messages",
  76. models: [UPSTREAM_MODEL],
  77. });
  78. await restartIntoWorkspacePreservingProfile(DEFAULT_WORKSPACE);
  79. await prepareV4ConversationE2E({ skipProvider: true });
  80. await selectRegistryProviderModelById(UPSTREAM_MODEL, {
  81. providerId: UPSTREAM_PROVIDER_ID,
  82. providerName: UPSTREAM_PROVIDER_NAME,
  83. includePlainModelFallback: false,
  84. });
  85. await sendV4Prompt("E2E_SID_NEW: Reply E2E_SID_NEW_OK.");
  86. await waitForV4AssistantMessageContaining("E2E_SID_NEW_OK", 60000);
  87. const created = await waitForV4Pane(
  88. (s) => Boolean(s.sessionId && s.sessionId !== "draft") && !s.canStop,
  89. "新会话未完成",
  90. 60000,
  91. );
  92. const newId = created.sessionId!;
  93. facts.newId = newId;
  94. expect(newId).toMatch(
  95. /^sess_[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,
  96. );
  97. // 旧格式仅播种到隔离夹具,必须等旧 Host/Agent 全部退出;产品代码不迁移任何主键。
  98. await restartIntoWorkspacePreservingProfile(DEFAULT_WORKSPACE, {
  99. afterElectronProcessExit: () => seedLegacySessions(newId),
  100. });
  101. facts.afterFirstRestart = readIdentityFacts(newId);
  102. for (const [index, id] of LEGACY_IDS.entries()) {
  103. await selectV4TaskById(id, 30000);
  104. await waitForV4TimelineContaining(`E2E_SID_HISTORY_${index}`, 30000);
  105. const restored = await waitForV4Pane(
  106. (s) => s.sessionId === id && !s.canStop,
  107. "旧 ID 未恢复",
  108. 30000,
  109. );
  110. expect(restored.sessionId).toBe(id);
  111. await sendV4Prompt(`E2E_SID_FOLLOW_${index}: Reply E2E_SID_FOLLOW_OK_${index}.`);
  112. await waitForV4AssistantMessageContaining(`E2E_SID_FOLLOW_OK_${index}`, 60000);
  113. await waitForV4Pane((s) => s.sessionId === id && !s.canStop, "旧会话继续发送未结束", 60000);
  114. }
  115. await restartIntoWorkspacePreservingProfile(DEFAULT_WORKSPACE);
  116. for (const [index, id] of LEGACY_IDS.entries()) {
  117. await selectV4TaskById(id, 30000);
  118. await waitForV4TimelineContaining(`E2E_SID_HISTORY_${index}`, 30000);
  119. await waitForV4TimelineContaining(`E2E_SID_FOLLOW_OK_${index}`, 30000);
  120. }
  121. facts.afterSecondRestart = readIdentityFacts(newId);
  122. for (const [index, id] of LEGACY_IDS.entries()) {
  123. await openWorkspaceDraftFromSidebar(DEFAULT_WORKSPACE);
  124. await setInputValueByTestIdDom(TID_V4_COMPOSER_INPUT, "#");
  125. const option = await waitForV4MentionOptionPrefix(`session:${id}`);
  126. expect(option).toBe(`session:${id}`);
  127. expect(await clickV4SlashOption(option)).toBe(true);
  128. const mention = (await getV4ComposerText())!;
  129. expect(mention).toContain(`#${id}`);
  130. await sendV4Prompt(
  131. `E2E_SID_REFERENCE_${index}: ${mention} Read its original decision with ReadSession.`,
  132. );
  133. await waitForUpstreamRequest(
  134. {
  135. includes: [
  136. `E2E_SID_REFERENCE_${index}`,
  137. "The user referenced prior ZCode session(s)",
  138. id,
  139. ],
  140. excludes: ["Generate a concise title"],
  141. },
  142. "旧 ID 未进入模型引用提示",
  143. 60000,
  144. );
  145. await waitForV4TimelineContaining(`E2E_SID_REFERENCE_OK_${index}`, 60000);
  146. await waitForUpstreamRequest(
  147. {
  148. includes: [`E2E_SID_REFERENCE_${index}`, `E2E_SID_HISTORY_${index}`, id],
  149. excludes: ["Generate a concise title"],
  150. },
  151. "旧 ID 的工具结果未进入后续模型请求",
  152. 60000,
  153. );
  154. const sessionChip = await browser.execute(
  155. (label) =>
  156. Array.from(document.querySelectorAll("span")).some(
  157. (element) =>
  158. element.textContent?.trim() === label &&
  159. element.querySelector("svg.lucide-messages-square") !== null,
  160. ),
  161. `E2E SID legacy ${index}`,
  162. );
  163. expect(sessionChip).toBe(true);
  164. facts[`reference${index}`] = { id, mention, sessionChip };
  165. await browser.saveScreenshot(join(artifactDir, `legacy-reference-${index}.png`));
  166. }
  167. facts.final = readIdentityFacts(newId);
  168. });
  169. it("手机 shared-host 恢复两种旧 ID,引用发送后刷新仍保留原身份", async function () {
  170. this.timeout(180000);
  171. const endpoint = process.env.ZCODE_WEB_REMOTE_CONTROL_URL;
  172. if (!endpoint) throw new Error("SID 手机验收需要隔离 Web/relay fixture");
  173. const pairingUrl = await obtainUnreadPairingUrl(new URL(endpoint).origin);
  174. const executablePath = process.env.ZCODE_E2E_MOBILE_BROWSER_EXECUTABLE;
  175. const chrome = await chromium.launch({
  176. ...(executablePath ? { executablePath } : { channel: "chrome" }),
  177. headless: true,
  178. });
  179. try {
  180. const context = await chrome.newContext({
  181. viewport: { width: 390, height: 844 },
  182. isMobile: true,
  183. hasTouch: true,
  184. locale: "zh-CN",
  185. });
  186. await seedMobileFixtureLogin(context);
  187. const page = await context.newPage();
  188. await openMobilePairingPage(page, pairingUrl, {
  189. artifactDir,
  190. caseMarker: "SID04",
  191. phase: "pairing",
  192. readySelector: '[data-testid="sidebar"], [data-mobile-page="chat"]',
  193. });
  194. for (const [index, id] of LEGACY_IDS.entries()) {
  195. await showMobileTaskHome(page);
  196. const toggles = page.getByTestId("virtual-project-toggle");
  197. for (let i = 0; i < (await toggles.count()); i++) {
  198. const toggle = toggles.nth(i);
  199. if ((await toggle.getAttribute("aria-expanded")) !== "true") await toggle.click();
  200. }
  201. await page.getByTestId(testId(TID_TASK_ITEM, id)).first().click();
  202. const pane = page.locator(`[data-session-id="${id}"]`);
  203. await pane.getByText(`E2E_SID_FOLLOW_OK_${index}`, { exact: false }).first().waitFor();
  204. const composer = page.getByTestId(TID_V4_COMPOSER_INPUT);
  205. await composer.fill("#");
  206. await page.getByTestId(testId(TID_PROMPT_SUGGESTION_OPTION, `session:${id}`)).click();
  207. await composer.press("End");
  208. await composer.pressSequentially(` E2E_SID_MOBILE_${index}: acknowledge this reference.`);
  209. await page.getByTestId(TID_V4_COMPOSER_SEND).click();
  210. await pane
  211. .getByText(`E2E_SID_MOBILE_OK_${index}`, { exact: false })
  212. .first()
  213. .waitFor({ timeout: 60000 });
  214. await waitForUpstreamRequest(
  215. {
  216. includes: [`E2E_SID_MOBILE_${index}`, "The user referenced prior ZCode session(s)", id],
  217. excludes: ["Generate a concise title"],
  218. },
  219. "手机未透传原 ID 的引用提醒",
  220. 30000,
  221. );
  222. await page.reload();
  223. await page
  224. .locator(`[data-session-id="${id}"]`)
  225. .getByText(`E2E_SID_MOBILE_OK_${index}`, { exact: false })
  226. .first()
  227. .waitFor({ timeout: 30000 });
  228. const chip = page
  229. .locator("span")
  230. .filter({ has: page.locator("svg.lucide-messages-square") })
  231. .filter({ hasText: `E2E SID legacy ${index}` });
  232. expect(await chip.count()).toBeGreaterThan(0);
  233. await page.screenshot({
  234. path: join(artifactDir, `mobile-legacy-${index}.png`),
  235. fullPage: true,
  236. });
  237. facts[`mobile${index}`] = { id, restoredAfterReload: true, sessionChip: true };
  238. }
  239. } finally {
  240. await chrome.close();
  241. }
  242. });
  243. it("SID05: 旧客户端重复、并发和 Host/CLI 重启重放", async function () {
  244. this.timeout(240000);
  245. await withRetryProxy(async () => {
  246. facts.retries = await verifySessionCreationRetries();
  247. });
  248. });
  249. for (const surface of ["desktop", "mobile"] as const) {
  250. it(`SID05: 已接纳首条输入在执行前退出,用户确认重发分配新 ID (${surface})`, async function () {
  251. this.timeout(240000);
  252. await prepareV4ConversationE2E({ skipProvider: true });
  253. await seedReplayProvider({
  254. id: UPSTREAM_PROVIDER_ID,
  255. name: UPSTREAM_PROVIDER_NAME,
  256. apiFormat: "anthropic-messages",
  257. models: [UPSTREAM_MODEL],
  258. });
  259. const oldId = `sess_${randomUUID()}`;
  260. const command: CommandEnvelope = {
  261. commandId: randomUUID(),
  262. clientId: `e2e-confirm-resend-${surface}`,
  263. sessionId: null,
  264. type: "createSession",
  265. issuedAt: Date.now(),
  266. payload: {
  267. workspaceId: DEFAULT_WORKSPACE,
  268. sessionId: oldId,
  269. firstInput: {
  270. text: `E2E_SID_RETRY_RESEND_${surface}`,
  271. modelSelection: {
  272. providerId: UPSTREAM_PROVIDER_ID,
  273. modelId: UPSTREAM_MODEL,
  274. // seedReplayProvider 的合成模型只声明 disabled;与真实 Composer 默认请求一致。
  275. options: { reasoningLevel: "disabled" },
  276. },
  277. },
  278. },
  279. };
  280. // 模拟 ACK 丢失窗口已有的 renderer ledger;首发 admission 由真实 Host/CLI 完成。
  281. if (surface === "desktop")
  282. await browser.execute((entry) => {
  283. localStorage.setItem("zcode-v4-pending-commands:v1", JSON.stringify([entry]));
  284. }, pendingCreateEntry(command));
  285. await withRetryProxy(async () => {
  286. await restartIntoWorkspacePreservingProfile(DEFAULT_WORKSPACE, {
  287. afterElectronProcessExit: async () => {
  288. facts[`resendAdmission-${surface}`] = await admitCreateBeforeExit(
  289. command,
  290. DEFAULT_WORKSPACE,
  291. );
  292. },
  293. });
  294. });
  295. let newId: string;
  296. if (surface === "mobile") {
  297. newId = await resendOnMobile(command);
  298. } else {
  299. await openWorkspaceDraftFromSidebar(DEFAULT_WORKSPACE);
  300. await browser.waitUntil(
  301. async () =>
  302. browser.execute(() => {
  303. const entries = JSON.parse(
  304. localStorage.getItem("zcode-v4-pending-commands:v1") ?? "[]",
  305. );
  306. return entries.some((entry: { recovery?: string }) => entry.recovery === "discarded");
  307. }),
  308. { timeout: 60000, timeoutMsg: "CLI 重启后没有确认 firstInput 被丢弃" },
  309. );
  310. const resend = await $(
  311. '//div[@role="status"]//button[normalize-space()="Send again" or normalize-space()="重新发送"]',
  312. );
  313. await resend.waitForDisplayed({ timeout: 30000 });
  314. await browser.saveScreenshot(join(artifactDir, "resend-discarded-banner.png"));
  315. await resend.click();
  316. await browser.waitUntil(
  317. async () =>
  318. browser.execute(() =>
  319. Boolean(
  320. (
  321. window as unknown as { __zcodeV4CommandAcksE2E?: Array<{ type: string }> }
  322. ).__zcodeV4CommandAcksE2E?.some((ack) => ack.type === "createSession"),
  323. ),
  324. ),
  325. { timeout: 30000, timeoutMsg: "重发没有收到 createSession ACK" },
  326. );
  327. const acks = await browser.execute(
  328. () =>
  329. (
  330. window as unknown as {
  331. __zcodeV4CommandAcksE2E: Array<{
  332. type: string;
  333. status: string;
  334. reasonCode?: string;
  335. }>;
  336. }
  337. ).__zcodeV4CommandAcksE2E,
  338. );
  339. facts[`resendAcks-${surface}`] = acks;
  340. expect(acks.filter((ack) => ack.type === "createSession").at(-1)?.status).toBe("accepted");
  341. await waitForV4AssistantMessageContaining("E2E_SID_RETRY_OK", 60000);
  342. const current = await waitForV4Pane(
  343. (s) => Boolean(s.sessionId && s.sessionId !== "draft") && !s.canStop,
  344. "重发会话未完成",
  345. 60000,
  346. );
  347. newId = current.sessionId!;
  348. }
  349. expect(newId).not.toBe(oldId);
  350. expect(newId).toMatch(
  351. /^sess_[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,
  352. );
  353. const db = new DatabaseSync(join(paths.storageRoot, "cli/db/db.sqlite"), { readOnly: true });
  354. try {
  355. const inputs = db
  356. .prepare(
  357. "SELECT id,session_id,status,status_reason,payload FROM session_input WHERE session_id IN (?,?) ORDER BY session_id",
  358. )
  359. .all(oldId, newId);
  360. expect(inputs).toHaveLength(2);
  361. expect(inputs.find((row) => row.session_id === oldId)).toMatchObject({
  362. status: "discarded",
  363. status_reason: "session_resumed",
  364. });
  365. const promoted = inputs.find((row) => row.session_id === newId)!;
  366. expect(promoted.status).toBe("promoted");
  367. expect(promoted.id).not.toBe(`queue_${command.commandId}`);
  368. // runtime 的 model-only 提醒也用 user role;必须按真实用户语义计数,避免把工具清单当成第二次输入。
  369. expect(
  370. db
  371. .prepare(
  372. "SELECT count(*) AS n FROM message WHERE session_id IN (?,?) AND json_extract(data,'$.semantics.origin')='real_user'",
  373. )
  374. .get(oldId, newId)?.n,
  375. ).toBe(1);
  376. facts[`confirmedResend-${surface}`] = {
  377. oldId,
  378. newId,
  379. inputs,
  380. accepted: true,
  381. userMessages: 1,
  382. };
  383. } finally {
  384. db.close();
  385. }
  386. });
  387. }
  388. });
  389. function readIdentityFacts(newId: string) {
  390. const cli = new DatabaseSync(join(paths.storageRoot, "cli", "db", "db.sqlite"), {
  391. readOnly: true,
  392. });
  393. const host = new DatabaseSync(join(paths.appDataDir, "tasks-index.sqlite"), { readOnly: true });
  394. try {
  395. return [newId, ...LEGACY_IDS].map((id) => {
  396. const session = cli.prepare("select id,parent_id from session where id=?").get(id);
  397. const task = host.prepare("select task_id,cli_created_at from tasks where task_id=?").get(id);
  398. expect(session?.id).toBe(id);
  399. expect(task?.task_id).toBe(id);
  400. expect(session?.parent_id).toBeNull();
  401. if (id.startsWith("session_"))
  402. expect(
  403. cli.prepare("select id from session where id=?").get(id.replace(/^session_/, "sess_")),
  404. ).toBeUndefined();
  405. const messages = cli.prepare("select count(*) as n from message where session_id=?").get(id);
  406. expect(Number(messages?.n)).toBeGreaterThanOrEqual(2);
  407. return { session, task, messages };
  408. });
  409. } finally {
  410. cli.close();
  411. host.close();
  412. }
  413. }
  414. function insertRow(db: DatabaseSync, table: string, row: Record<string, SQLInputValue>) {
  415. const columns = Object.keys(row);
  416. db.prepare(
  417. `insert into ${table} (${columns.join(",")}) values (${columns.map(() => "?").join(",")})`,
  418. ).run(...Object.values(row));
  419. }
  420. function seedLegacySessions(sourceId: string) {
  421. const cli = new DatabaseSync(join(paths.storageRoot, "cli", "db", "db.sqlite"));
  422. const host = new DatabaseSync(join(paths.appDataDir, "tasks-index.sqlite"));
  423. try {
  424. const source = cli.prepare("select * from session where id=?").get(sourceId)!;
  425. const sourceTask = host.prepare("select * from tasks where task_id=?").get(sourceId)!;
  426. const modelEntry = cli
  427. .prepare("select * from session_entry where session_id=? and type='runtime/model_selection'")
  428. .get(sourceId)!;
  429. expect(source).toBeDefined();
  430. expect(sourceTask).toBeDefined();
  431. expect(modelEntry).toBeDefined();
  432. for (const [index, id] of LEGACY_IDS.entries()) {
  433. const now = Date.now() - 10000 + index;
  434. const title = `E2E SID legacy ${index}`;
  435. insertRow(cli, "session", {
  436. ...source,
  437. id,
  438. title,
  439. title_source: "custom",
  440. title_message_id: null,
  441. trace_id: `trace_e2e_sid_${index}`,
  442. slug: `e2e-sid-${index}`,
  443. time_created: now,
  444. time_updated: now,
  445. });
  446. insertRow(host, "tasks", {
  447. ...sourceTask,
  448. task_id: id,
  449. title,
  450. cli_title: title,
  451. cli_title_source: "custom",
  452. cli_created_at: now,
  453. cli_updated_at: now,
  454. meta_json: JSON.stringify({
  455. ...JSON.parse(String(sourceTask.meta_json)),
  456. taskId: id,
  457. title,
  458. }),
  459. });
  460. insertRow(cli, "session_entry", {
  461. ...modelEntry,
  462. id: `entry_e2e_sid_${index}`,
  463. session_id: id,
  464. });
  465. const userId = `msg_e2e_sid_${index}_user`;
  466. const assistantId = `msg_e2e_sid_${index}_assistant`;
  467. const user = {
  468. role: "user",
  469. time: { created: now },
  470. agent: "zcode-agent",
  471. model: { providerID: UPSTREAM_PROVIDER_ID, modelID: UPSTREAM_MODEL },
  472. };
  473. const assistant = {
  474. role: "assistant",
  475. parentID: userId,
  476. time: { created: now + 1, completed: now + 1 },
  477. modelID: UPSTREAM_MODEL,
  478. providerID: UPSTREAM_PROVIDER_ID,
  479. mode: "build",
  480. agent: "zcode-agent",
  481. path: { cwd: DEFAULT_WORKSPACE, root: DEFAULT_WORKSPACE },
  482. cost: 0,
  483. tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
  484. finish: "stop",
  485. };
  486. for (const [messageId, data] of [
  487. [userId, user],
  488. [assistantId, assistant],
  489. ] as const) {
  490. insertRow(cli, "message", {
  491. id: messageId,
  492. session_id: id,
  493. time_created: now,
  494. time_updated: now,
  495. data: JSON.stringify(data),
  496. });
  497. insertRow(cli, "part", {
  498. id: `part_${messageId}`,
  499. message_id: messageId,
  500. session_id: id,
  501. time_created: now,
  502. time_updated: now,
  503. data: JSON.stringify({
  504. type: "text",
  505. text: `E2E_SID_HISTORY_${index}: keep the original session identity.`,
  506. time: { start: now, end: now },
  507. }),
  508. });
  509. }
  510. }
  511. } finally {
  512. cli.close();
  513. host.close();
  514. }
  515. }
  516. async function withRetryProxy<T>(run: () => Promise<T>): Promise<T> {
  517. // 独立 Host 使用内建 HTTPS provider;仅在本用例安装隔离代理,不访问真实上游。
  518. const proxy = await startE2ENetworkCaptureProxy({
  519. artifactPath: join(artifactDir, "session-retry-network.json"),
  520. caDir: join(paths.homeDir, "session-retry-ca"),
  521. requestRedirects: [
  522. {
  523. host: "open.bigmodel.cn",
  524. path: "/api/anthropic/v1/messages",
  525. targetUrl: `${replay.baseUrl}/messages`,
  526. },
  527. ],
  528. responseMocks: [
  529. {
  530. host: "open.bigmodel.cn",
  531. method: "POST",
  532. path: "/api/paas/c1f3a7e2/v2/client",
  533. body: JSON.stringify({ code: 500, msg: "E2E handshake unavailable" }),
  534. },
  535. ],
  536. });
  537. const previous = Object.fromEntries(Object.keys(proxy.env).map((key) => [key, process.env[key]]));
  538. Object.assign(process.env, proxy.env);
  539. try {
  540. return await run();
  541. } finally {
  542. for (const [key, value] of Object.entries(previous)) {
  543. if (value === undefined) delete process.env[key];
  544. else process.env[key] = value;
  545. }
  546. await proxy.stop();
  547. }
  548. }
  549. function pendingCreateEntry(command: CommandEnvelope) {
  550. return {
  551. commandId: command.commandId,
  552. clientId: command.clientId,
  553. sessionId: null,
  554. issuedAt: command.issuedAt,
  555. expiresAt: Date.now() + 3600000,
  556. replay: { kind: "input", type: "createSession", payload: command.payload },
  557. clientContext: { workspace: { workspacePath: DEFAULT_WORKSPACE }, projectId: null },
  558. };
  559. }
  560. async function resendOnMobile(command: CommandEnvelope): Promise<string> {
  561. const endpoint = process.env.ZCODE_WEB_REMOTE_CONTROL_URL;
  562. if (!endpoint) throw new Error("SID 手机重发需要隔离 Web/relay fixture");
  563. const pairingUrl = await obtainUnreadPairingUrl(new URL(endpoint).origin);
  564. const executablePath = process.env.ZCODE_E2E_MOBILE_BROWSER_EXECUTABLE;
  565. const chrome = await chromium.launch({
  566. ...(executablePath ? { executablePath } : { channel: "chrome" }),
  567. headless: true,
  568. });
  569. try {
  570. const context = await chrome.newContext({
  571. viewport: { width: 390, height: 844 },
  572. isMobile: true,
  573. hasTouch: true,
  574. locale: "zh-CN",
  575. });
  576. await seedMobileFixtureLogin(context);
  577. const page = await context.newPage();
  578. await openMobilePairingPage(page, pairingUrl, {
  579. artifactDir,
  580. caseMarker: "SID05",
  581. phase: "resend",
  582. readySelector: '[data-testid="sidebar"], [data-mobile-page="chat"]',
  583. });
  584. await page.evaluate(
  585. (entry) => localStorage.setItem("zcode-v4-pending-commands:v1", JSON.stringify([entry])),
  586. pendingCreateEntry(command),
  587. );
  588. await page.reload();
  589. await showMobileTaskHome(page);
  590. await page
  591. .locator(projectSectionSelector(DEFAULT_WORKSPACE))
  592. .getByTestId("virtual-project-create-task")
  593. .tap();
  594. const resend = page
  595. .getByRole("status")
  596. .getByRole("button", { name: /^(Send again|重新发送)$/ });
  597. await resend.waitFor({ timeout: 60000 });
  598. await page.screenshot({
  599. path: join(artifactDir, "mobile-resend-discarded-banner.png"),
  600. fullPage: true,
  601. });
  602. await resend.tap();
  603. await page.waitForFunction(() =>
  604. (
  605. window as unknown as { __zcodeV4CommandAcksE2E?: Array<{ type: string }> }
  606. ).__zcodeV4CommandAcksE2E?.some((ack) => ack.type === "createSession"),
  607. );
  608. const acks = await page.evaluate(
  609. () =>
  610. (
  611. window as unknown as {
  612. __zcodeV4CommandAcksE2E: Array<{ type: string; status: string; reasonCode?: string }>;
  613. }
  614. ).__zcodeV4CommandAcksE2E,
  615. );
  616. facts["resendAcks-mobile"] = acks;
  617. expect(acks.filter((ack) => ack.type === "createSession").at(-1)?.status).toBe("accepted");
  618. const answer = page.getByText("E2E_SID_RETRY_OK", { exact: true }).first();
  619. await answer.waitFor({ timeout: 60000 });
  620. const pane = page.locator('[data-session-id^="sess_"]').filter({ has: answer }).first();
  621. const newId = await pane.getAttribute("data-session-id");
  622. if (!newId) throw new Error("手机重发后没有新 sessionId");
  623. await page.reload();
  624. await page
  625. .locator(`[data-session-id="${newId}"]`)
  626. .getByText("E2E_SID_RETRY_OK", { exact: true })
  627. .first()
  628. .waitFor({ timeout: 30000 });
  629. return newId;
  630. } finally {
  631. await chrome.close();
  632. }
  633. }