app-control-session-lifecycle.test.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. import { mkdir, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { chromium, type Browser, type Page } from "playwright-core";
  4. import { ServiceChannels } from "@zcode/shared";
  5. import type { ProjectTask, ProjectTree } from "@zcode/services";
  6. import { TID_TASK_ITEM, TID_V4_SESSION_PANE, testId } from "@zcode/shared/test-ids";
  7. import { clearAppData, DEFAULT_WORKSPACE } from "#e2e/helpers/desktop-app";
  8. import {
  9. buildReadonlyToolPrompt,
  10. ensureReadonlyToolFixtureFile,
  11. } from "#e2e/helpers/conversation-session-readonly-tool";
  12. import { releaseControlledReplay, waitForControlledReplay } from "#e2e/helpers/controlled-replay";
  13. import { reloadElectronSessionSafely } from "#e2e/helpers/e2e-electron-reload";
  14. import { openMobilePairingPage } from "#e2e/helpers/mobile-pairing";
  15. import { setPluginPresentation } from "#e2e/helpers/plugin-management-lifecycle";
  16. import { startDraftFromProject } from "#e2e/helpers/project-sidebar";
  17. import {
  18. callHandoffHost,
  19. installHandoffRpcProbe,
  20. restoreHandoffProbes,
  21. } from "#e2e/helpers/remote-project-handoff-probe";
  22. import {
  23. readAppControlToolResult,
  24. type AppControlToolEvidence,
  25. } from "#e2e/helpers/app-control-evidence";
  26. import { waitForUpstreamNetworkCapture } from "#e2e/helpers/upstream-capture";
  27. import {
  28. obtainUnreadPairingUrl,
  29. showMobileTaskHome,
  30. waitMobileTaskView,
  31. } from "#e2e/helpers/web-remote-unread";
  32. import { WEB_REMOTE_CONTROL_FIXTURE_CREDENTIALS } from "#e2e/helpers/web-remote-control-session-events-fixture";
  33. import {
  34. approveV4Permission,
  35. getV4PaneSnapshot,
  36. prepareV4ConversationE2E,
  37. renameV4Session,
  38. selectV4TaskById,
  39. sendV4Prompt,
  40. waitForV4AssistantMessageContaining,
  41. waitForV4Pane,
  42. } from "#e2e/helpers/v4-conversation";
  43. const CASE = "E2E_SCT04";
  44. const CALLER_TITLE = "SCT04 调用会话";
  45. const TITLE = "SCT04 生命周期分叉";
  46. const artifacts = process.env.ZCODE_E2E_ARTIFACT_DIR!;
  47. const tools: AppControlToolEvidence = {};
  48. const assertions: Record<string, unknown> = {};
  49. const evidence = { tools, assertions };
  50. interface SessionRef {
  51. kind: "app";
  52. sourceServerId: string;
  53. workspacePath: string;
  54. sessionId: string;
  55. workspaceIdentity?: string;
  56. project?: { kind: "app"; sourceServerId: string; projectId: string };
  57. }
  58. interface Operation {
  59. session: SessionRef;
  60. commandId: string;
  61. }
  62. interface Admission {
  63. session: SessionRef;
  64. operation: Operation;
  65. admission: string;
  66. delivery: string;
  67. }
  68. interface Creation extends Omit<Admission, "admission"> {
  69. creation: string;
  70. firstInput: string;
  71. }
  72. interface History {
  73. view: "messages";
  74. session: SessionRef;
  75. messages: Array<{ id: string; role: string; text: string }>;
  76. nextCursor?: string;
  77. }
  78. interface Summary {
  79. view: "summary";
  80. summary: {
  81. session: SessionRef;
  82. status: string;
  83. executionId?: string;
  84. title: string;
  85. archived: boolean;
  86. pinned: boolean;
  87. };
  88. }
  89. interface Wait {
  90. status: string;
  91. operations: Array<{ operation: Operation; status: string; executionId?: string }>;
  92. }
  93. interface Mutation {
  94. status: string;
  95. reason?: string;
  96. }
  97. async function action<T>(key: string, intent: string, approval = false): Promise<T> {
  98. await sendV4Prompt(
  99. `${CASE}_ACTION_${key.toUpperCase()}: ${intent} Use complete identities from the earlier actual tool results. Do not navigate or invent a result. After the tool returns reply exactly SCT04_${key.toUpperCase()}_RETURNED.`,
  100. );
  101. if (approval) expect(await approveV4Permission()).toBe(true);
  102. await waitForV4AssistantMessageContaining(`SCT04_${key.toUpperCase()}_RETURNED`, 90_000);
  103. await waitForV4Pane((value) => !value.canStop, `SCT04 ${key} caller has not completed`);
  104. const request = (await waitForUpstreamNetworkCapture(`toolu_sct04_${key}`)).requestJson;
  105. return readAppControlToolResult<T>(request, `toolu_sct04_${key}`, tools);
  106. }
  107. async function mutate(key: string, intent: string) {
  108. const result = await action<Mutation>(key, intent, true);
  109. expect(result.status).toBe("applied");
  110. return result;
  111. }
  112. async function readTask(id: string): Promise<ProjectTask> {
  113. // 只读 owner 的持久组织事实;被测动作全部来自真实 Agent 工具。
  114. const tree = await callHandoffHost<ProjectTree>(ServiceChannels.Project, "readTree", [{}]);
  115. const task = tree.tasks.find((value) => value.taskId === id);
  116. if (!task) throw new Error(`SCT04 product task absent: ${id}`);
  117. return task;
  118. }
  119. function expectOperation(result: Wait, operation: Operation, status: string) {
  120. expect(
  121. result.operations.find((value) => value.operation.commandId === operation.commandId),
  122. ).toMatchObject({ operation, status });
  123. }
  124. async function selectMobile(page: Page, id: string) {
  125. await showMobileTaskHome(page);
  126. for (const toggle of await page.getByTestId("virtual-project-toggle").all()) {
  127. if ((await toggle.getAttribute("aria-expanded")) !== "true") await toggle.click();
  128. }
  129. await page.getByTestId(testId(TID_TASK_ITEM, id)).click();
  130. await page.locator(`[data-testid^="${TID_V4_SESSION_PANE}-"][data-session-id="${id}"]`).waitFor();
  131. }
  132. // SCT02/04/05/06 accepted;真实工具链候选保持 pending,不以 fixture 文本当工具证据。
  133. describe(`${CASE}: App session lifecycle through actual tools`, () => {
  134. let mobile: Browser | undefined;
  135. let page: Page | undefined;
  136. after(async () => {
  137. if (artifacts) {
  138. await mkdir(artifacts, { recursive: true });
  139. await writeFile(join(artifacts, "SCT04-lifecycle.json"), JSON.stringify(evidence, null, 2));
  140. await browser.saveScreenshot(join(artifacts, "SCT04-desktop.png"));
  141. await page?.screenshot({ path: join(artifacts, "SCT04-mobile.png") });
  142. }
  143. await mobile?.close();
  144. await restoreHandoffProbes();
  145. await clearAppData();
  146. });
  147. it("creates, queues, waits, forks stable history, organizes and guards interruption on desktop and 390px mobile", async function () {
  148. this.timeout(900_000);
  149. await ensureReadonlyToolFixtureFile();
  150. await prepareV4ConversationE2E();
  151. await startDraftFromProject(DEFAULT_WORKSPACE);
  152. await sendV4Prompt(buildReadonlyToolPrompt(`${CASE}_CALLER`));
  153. await waitForV4AssistantMessageContaining("upstream-e2e-ok", 90_000);
  154. const caller = await waitForV4Pane(
  155. (value) => !value.canStop && value.sessionId !== "draft",
  156. "SCT04 caller missing",
  157. );
  158. const callerId = caller.sessionId!;
  159. await renameV4Session(CALLER_TITLE);
  160. await installHandoffRpcProbe();
  161. await browser.waitUntil(async () => (await readTask(callerId)).title === CALLER_TITLE, {
  162. timeout: 30_000,
  163. timeoutMsg: "SCT04 caller title not durable",
  164. });
  165. const pairUrl = await obtainUnreadPairingUrl();
  166. mobile = await chromium.launch({
  167. ...(process.env.ZCODE_E2E_MOBILE_BROWSER_EXECUTABLE
  168. ? { executablePath: process.env.ZCODE_E2E_MOBILE_BROWSER_EXECUTABLE }
  169. : { channel: "chrome" }),
  170. headless: true,
  171. });
  172. const context = await mobile.newContext({
  173. viewport: { width: 390, height: 844 },
  174. isMobile: true,
  175. hasTouch: true,
  176. });
  177. await context.addInitScript((credentials) => {
  178. for (const [key, value] of Object.entries(credentials)) localStorage.setItem(key, value);
  179. }, WEB_REMOTE_CONTROL_FIXTURE_CREDENTIALS);
  180. page = await context.newPage();
  181. await openMobilePairingPage(page, pairUrl, {
  182. artifactDir: artifacts,
  183. caseMarker: CASE,
  184. phase: "lifecycle",
  185. readySelector: '[data-testid="sidebar"]',
  186. });
  187. await selectMobile(page, callerId);
  188. const assertBackground = async () => {
  189. expect((await getV4PaneSnapshot()).sessionId).toBe(callerId);
  190. await waitMobileTaskView({ workspacePath: DEFAULT_WORKSPACE, taskId: callerId });
  191. };
  192. const projects = await action<{
  193. projects: Array<{ project: NonNullable<SessionRef["project"]> }>;
  194. }>("projects", "Call ListProjects with query=ZCodeProject.");
  195. expect(projects.projects).toHaveLength(1);
  196. const created = await action<Creation>(
  197. "create",
  198. "Call CreateSession in that project with prompt E2E_SCT04_CREATE_TARGET (step marker E2E_SCT04_CREATE; do not pass requestId).",
  199. true,
  200. );
  201. expect(created).toMatchObject({
  202. creation: "created",
  203. firstInput: "accepted",
  204. delivery: "start_now",
  205. });
  206. expect(created.session.project).toEqual(projects.projects[0]!.project);
  207. expect(created.session.sessionId).not.toBe(callerId);
  208. expect(created.operation.session).toEqual(created.session);
  209. expect(created.operation.commandId).toBeTruthy();
  210. await browser.waitUntil(
  211. async () =>
  212. (await readTask(created.session.sessionId)).projectId ===
  213. created.session.project!.projectId,
  214. { timeout: 30_000 },
  215. );
  216. await assertBackground();
  217. // 接纳后仍可能在初始化 MCP;等待目标真实进入受控流,才能断言 running 而非 accepted。
  218. await waitForControlledReplay("sct04-create-target");
  219. const sent = await action<Admission>(
  220. "send",
  221. "Call SendToSession on the created session with prompt E2E_SCT04_SEND_TARGET (step marker E2E_SCT04_SEND; do not pass requestId).",
  222. true,
  223. );
  224. expect(sent).toMatchObject({
  225. admission: "accepted",
  226. delivery: "queued",
  227. session: created.session,
  228. });
  229. expect(sent.operation.session).toEqual(created.session);
  230. expect(sent.operation.commandId).not.toBe(created.operation.commandId);
  231. const pending = await action<Wait>(
  232. "pending",
  233. "Call WaitSessions for both create and send operations with mode=all and timeoutMs=0.",
  234. );
  235. expect(pending.status).toBe("timed_out");
  236. expectOperation(pending, created.operation, "running");
  237. expectOperation(pending, sent.operation, "queued");
  238. await assertBackground();
  239. assertions.createAndQueue = { created, sent, pending, desktop: callerId, mobile: callerId };
  240. await releaseControlledReplay("sct04-create-target");
  241. const completed = await action<Wait>(
  242. "completed",
  243. "Call WaitSessions for those two exact operations, mode=all, timeoutMs=30000.",
  244. );
  245. expect(completed.status).toBe("completed");
  246. expectOperation(completed, created.operation, "completed");
  247. expectOperation(completed, sent.operation, "completed");
  248. assertions.exactCompletion = completed;
  249. const first = await action<History>(
  250. "page",
  251. "Call ReadSession on the created session, view=messages, limit=1.",
  252. );
  253. expect(first.session).toEqual(created.session);
  254. expect(first.messages).toHaveLength(1);
  255. expect(first.messages[0]).toMatchObject({ role: "user", text: "E2E_SCT04_CREATE_TARGET" });
  256. expect(first.nextCursor).toBe(first.messages[0]!.id);
  257. const second = await action<History>(
  258. "page2",
  259. "Call ReadSession on the same session, view=messages, limit=200, cursor equal to the previous nextCursor.",
  260. );
  261. expect(second.session).toEqual(created.session);
  262. expect(tools.toolu_sct04_page2!.call.input!.cursor).toBe(first.nextCursor);
  263. expect(second.nextCursor).toBeUndefined();
  264. const allMessages = [...first.messages, ...second.messages];
  265. expect(new Set(allMessages.map((message) => message.id)).size).toBe(allMessages.length);
  266. for (const marker of ["E2E_SCT04_CREATE_TARGET", "E2E_SCT04_SEND_TARGET"]) {
  267. expect(
  268. allMessages.filter((message) => message.role === "user" && message.text === marker),
  269. ).toHaveLength(1);
  270. }
  271. // 真实历史包含 model-only 消息,不能假定首轮 assistant 紧随用户消息。
  272. const boundary = second.messages.find(
  273. (message) => message.role === "assistant" && message.text.includes("SCT04_CREATE_DONE"),
  274. );
  275. expect(boundary).toBeDefined();
  276. expect(second.messages.find((message) => message.role === "assistant")?.id).toBe(boundary!.id);
  277. expect(
  278. second.messages.some(
  279. (message) => message.role === "assistant" && message.text.includes("SCT04_SEND_DONE"),
  280. ),
  281. ).toBe(true);
  282. assertions.paginationAndUniqueDelivery = { first, second, boundary };
  283. const fork = await action<{ status: string; session: SessionRef }>(
  284. "fork",
  285. "Call ForkSession on the created session at the assistant message containing SCT04_CREATE_DONE from the SECOND page (step marker E2E_SCT04_FORK; do not pass requestId).",
  286. true,
  287. );
  288. expect(tools.toolu_sct04_fork!.call.input!.atMessage).toBe(boundary!.id);
  289. expect(fork.status).toBe("created");
  290. expect(fork.session.sessionId).not.toBe(created.session.sessionId);
  291. expect(fork.session.project).toEqual(created.session.project);
  292. const history = await action<History>(
  293. "fork_history",
  294. "Call ReadSession on the returned fork, view=messages, limit=20.",
  295. );
  296. expect(history.session).toEqual(fork.session);
  297. expect(history.messages).toEqual(
  298. expect.arrayContaining([
  299. expect.objectContaining({ role: "user", text: first.messages[0]!.text }),
  300. expect.objectContaining({ role: "assistant", text: boundary!.text }),
  301. ]),
  302. );
  303. expect(JSON.stringify(history.messages)).not.toContain("E2E_SCT04_SEND_TARGET");
  304. await assertBackground();
  305. assertions.stableFork = { fork, history };
  306. const run = await action<Admission>(
  307. "run",
  308. "Call SendToSession on the fork, prompt=E2E_SCT04_INTERRUPT_TARGET (step marker E2E_SCT04_RUN; do not pass requestId).",
  309. true,
  310. );
  311. expect(run).toMatchObject({
  312. session: fork.session,
  313. admission: "accepted",
  314. delivery: "start_now",
  315. });
  316. const running = await action<Summary>("running", "Call ReadSession on the fork, view=summary.");
  317. expect(running.summary.status).toBe("running");
  318. expect(running.summary.executionId).toBeTruthy();
  319. await mutate(
  320. "rename",
  321. "Call RenameSession on the fork, title=SCT04 生命周期分叉 (step marker E2E_SCT04_RENAME; do not pass requestId).",
  322. );
  323. await mutate(
  324. "pin",
  325. "Call SetSessionPinned on the fork, pinned=true (step marker E2E_SCT04_PIN; do not pass requestId).",
  326. );
  327. const rowId = testId(TID_TASK_ITEM, fork.session.sessionId);
  328. await browser.waitUntil(
  329. async () => {
  330. const task = await readTask(fork.session.sessionId);
  331. return task.title === TITLE && task.pinned && !task.archived;
  332. },
  333. { timeout: 30_000, timeoutMsg: "SCT04 rename/pin not persisted" },
  334. );
  335. await $('[data-testid="project-pinned-tasks"]')
  336. .$(`[data-testid="${rowId}"]`)
  337. .waitForDisplayed();
  338. await showMobileTaskHome(page);
  339. await page.getByTestId("project-pinned-tasks").getByTestId(rowId).waitFor();
  340. expect(await page.getByTestId(rowId).innerText()).toContain(TITLE);
  341. const pinned = await readTask(fork.session.sessionId);
  342. await mutate(
  343. "archive",
  344. "Call SetSessionArchived on the fork, archived=true (step marker E2E_SCT04_ARCHIVE; do not pass requestId).",
  345. );
  346. await browser.waitUntil(async () => (await readTask(fork.session.sessionId)).archived, {
  347. timeout: 30_000,
  348. });
  349. await $(`[data-testid="${rowId}"]`).waitForExist({ reverse: true, timeout: 30_000 });
  350. await page.getByTestId(rowId).waitFor({ state: "detached" });
  351. const archived = await action<Summary>(
  352. "archived",
  353. "Call ReadSession on the archived fork, view=summary.",
  354. );
  355. expect(archived.summary).toMatchObject({
  356. title: TITLE,
  357. archived: true,
  358. pinned: true,
  359. status: "running",
  360. executionId: running.summary.executionId,
  361. });
  362. await mutate(
  363. "unarchive",
  364. "Call SetSessionArchived on the fork, archived=false (step marker E2E_SCT04_UNARCHIVE; do not pass requestId).",
  365. );
  366. await page.getByTestId("project-pinned-tasks").getByTestId(rowId).waitFor();
  367. await mutate(
  368. "unpin",
  369. "Call SetSessionPinned on the fork, pinned=false (step marker E2E_SCT04_UNPIN; do not pass requestId).",
  370. );
  371. await browser.waitUntil(
  372. async () => {
  373. const task = await readTask(fork.session.sessionId);
  374. return !task.archived && !task.pinned && task.title === TITLE;
  375. },
  376. { timeout: 30_000 },
  377. );
  378. // 取消最后一个置顶后分组本身会消失,直接检查组合选择器而非先查询已卸载的父元素。
  379. await $(`[data-testid="project-pinned-tasks"] [data-testid="${rowId}"]`).waitForExist({
  380. reverse: true,
  381. });
  382. await $(`[data-testid="${rowId}"]`).waitForDisplayed();
  383. await page
  384. .getByTestId("project-pinned-tasks")
  385. .getByTestId(rowId)
  386. .waitFor({ state: "detached" });
  387. await page.getByTestId(rowId).waitFor();
  388. assertions.organizationBothDirections = {
  389. pinned,
  390. archived: archived.summary,
  391. restored: await readTask(fork.session.sessionId),
  392. };
  393. await selectMobile(page, callerId);
  394. await assertBackground();
  395. await mutate(
  396. "interrupt",
  397. "Call InterruptSession on the fork using the exact executionId from running (step marker E2E_SCT04_INTERRUPT; do not pass requestId).",
  398. );
  399. const interrupted = await action<Wait>(
  400. "interrupted",
  401. "Call WaitSessions for the run operation, mode=all, timeoutMs=30000.",
  402. );
  403. expect(interrupted.status).toBe("completed");
  404. expectOperation(interrupted, run.operation, "interrupted");
  405. const next = await action<Admission>(
  406. "next",
  407. "Call SendToSession on the fork, prompt=E2E_SCT04_NEXT_TARGET (step marker E2E_SCT04_NEXT; do not pass requestId).",
  408. true,
  409. );
  410. expect(next).toMatchObject({
  411. session: fork.session,
  412. admission: "accepted",
  413. delivery: "start_now",
  414. });
  415. const nextRunning = await action<Summary>(
  416. "next_running",
  417. "Call ReadSession on the fork, view=summary.",
  418. );
  419. expect(nextRunning.summary.status).toBe("running");
  420. expect(nextRunning.summary.executionId).toBeTruthy();
  421. expect(nextRunning.summary.executionId).not.toBe(running.summary.executionId);
  422. const stale = await action<Mutation>(
  423. "stale",
  424. "Call InterruptSession using the OLD executionId from running (step marker E2E_SCT04_STALE; do not pass requestId).",
  425. true,
  426. );
  427. expect(stale.status).toBe("rejected");
  428. const stillRunning = await action<Wait>(
  429. "still_running",
  430. "Call WaitSessions for the NEXT operation, mode=all, timeoutMs=0.",
  431. );
  432. expect(stillRunning.status).toBe("timed_out");
  433. expectOperation(stillRunning, next.operation, "running");
  434. expect(stillRunning.operations[0]!.executionId).toBe(nextRunning.summary.executionId);
  435. await releaseControlledReplay("sct04-next-target");
  436. const nextCompleted = await action<Wait>(
  437. "next_completed",
  438. "Call WaitSessions for the NEXT operation, mode=all, timeoutMs=30000.",
  439. );
  440. expect(nextCompleted.status).toBe("completed");
  441. expectOperation(nextCompleted, next.operation, "completed");
  442. const finalHistory = await action<History>(
  443. "final_history",
  444. "Call ReadSession on the fork, view=messages, limit=20.",
  445. );
  446. for (const marker of ["E2E_SCT04_INTERRUPT_TARGET", "E2E_SCT04_NEXT_TARGET"]) {
  447. expect(
  448. finalHistory.messages.filter(
  449. (message) => message.role === "user" && message.text === marker,
  450. ),
  451. ).toHaveLength(1);
  452. }
  453. expect(
  454. finalHistory.messages.some(
  455. (message) => message.role === "assistant" && message.text.includes("SCT04_NEXT_DONE"),
  456. ),
  457. ).toBe(true);
  458. assertions.executionGuard = { interrupted, nextRunning, stale, stillRunning, nextCompleted };
  459. await assertBackground();
  460. // 来源必须来自持久 input,不从正文猜测;显式 UI 选择只用于接收方显示验证。
  461. const sourceSelector = `[data-v4-user-input-source="session"][data-source-session-id="${callerId}"]`;
  462. const captureSource = async (
  463. theme: "zai-light" | "zai-dark",
  464. locale: "zh-CN" | "en-US",
  465. phase: string,
  466. ) => {
  467. await setPluginPresentation({ theme, locale, width: 1200, height: 900 });
  468. await showMobileTaskHome(page!);
  469. await page!.evaluate(
  470. (next) => {
  471. const actions = (
  472. window as Window & {
  473. __testActions?: { setLocale(value: string): void; setTheme(value: string): void };
  474. }
  475. ).__testActions;
  476. if (!actions) throw new Error("SCT04 mobile presentation actions unavailable");
  477. actions.setLocale(next.locale);
  478. actions.setTheme(next.theme);
  479. },
  480. { theme, locale },
  481. );
  482. await selectMobile(page!, fork.session.sessionId);
  483. const label =
  484. locale === "zh-CN" ? `来自会话 ${CALLER_TITLE}` : `From session ${CALLER_TITLE}`;
  485. await browser.waitUntil(async () => (await $$(sourceSelector).length) === 2, {
  486. timeout: 30_000,
  487. timeoutMsg: "SCT04 recipient source badges missing",
  488. });
  489. for (const badge of await $$(sourceSelector)) expect(await badge.getText()).toBe(label);
  490. await page!.locator(sourceSelector).first().waitFor();
  491. expect(await page!.locator(sourceSelector).allTextContents()).toEqual([label, label]);
  492. const desktopOverflow = await browser.execute(
  493. () => document.documentElement.scrollWidth > window.innerWidth,
  494. );
  495. const mobileLayout = await page!.evaluate(() => ({
  496. width: window.innerWidth,
  497. overflow: document.documentElement.scrollWidth > window.innerWidth,
  498. }));
  499. expect(desktopOverflow).toBe(false);
  500. expect(mobileLayout).toEqual({ width: 390, overflow: false });
  501. await browser.saveScreenshot(
  502. join(artifacts, `SCT04-source-${phase}-${theme}-${locale}-desktop.png`),
  503. );
  504. await page!.screenshot({
  505. path: join(artifacts, `SCT04-source-${phase}-${theme}-${locale}-mobile.png`),
  506. });
  507. assertions[`source-${phase}-${theme}-${locale}`] = {
  508. label,
  509. callerId,
  510. recipient: fork.session,
  511. count: 2,
  512. mobileLayout,
  513. };
  514. };
  515. await selectV4TaskById(fork.session.sessionId);
  516. await waitForV4AssistantMessageContaining("SCT04_NEXT_DONE");
  517. for (const theme of ["zai-light", "zai-dark"] as const) {
  518. for (const locale of ["zh-CN", "en-US"] as const) await captureSource(theme, locale, "live");
  519. }
  520. // 规格 0.13:持久化载荷只带 sessionId,标题由运行侧按 id 解析,所以这里断言的是**当前**标题——
  521. // 改动前它是发送那一刻的快照。点击走既有导航 owner,落到发起方会话。
  522. await setPluginPresentation({ theme: "zai-dark", locale: "zh-CN", width: 1200, height: 900 });
  523. await selectV4TaskById(fork.session.sessionId);
  524. const sourceLink = await $(`${sourceSelector} [data-source-session-navigable="true"]`);
  525. await sourceLink.waitForDisplayed({ timeout: 30_000 });
  526. expect(await sourceLink.getText()).toBe(`来自会话 ${CALLER_TITLE}`);
  527. await sourceLink.click();
  528. const navigated = await waitForV4Pane(
  529. (snapshot) => snapshot.sessionId === callerId,
  530. "SCT04 点击来源提示后没有跳到发起方会话",
  531. 30_000,
  532. );
  533. expect(navigated.sessionId).toBe(callerId);
  534. assertions.sourceNavigation = { from: fork.session.sessionId, to: callerId };
  535. await selectV4TaskById(fork.session.sessionId);
  536. await page.reload({ waitUntil: "domcontentloaded" });
  537. await page.locator(sourceSelector).first().waitFor();
  538. expect(await page.locator(sourceSelector).count()).toBe(2);
  539. assertions.mobileReplaySource = true;
  540. await reloadElectronSessionSafely(browser);
  541. await selectV4TaskById(fork.session.sessionId);
  542. await waitForV4AssistantMessageContaining("SCT04_NEXT_DONE");
  543. // 桌面重启会结束旧配对;沿真实入口重新连接后再验证持久来源,不能把离线页当作历史丢失。
  544. await openMobilePairingPage(page, await obtainUnreadPairingUrl(), {
  545. artifactDir: artifacts,
  546. caseMarker: CASE,
  547. phase: "cold-reconnect",
  548. // 已有手机页面保留 task-chat 路由;配对就绪时不保证首页侧栏可见。
  549. readySelector: '[data-testid="sidebar"], [data-testid^="v4-session-pane-"]',
  550. });
  551. await captureSource("zai-dark", "en-US", "cold");
  552. await installHandoffRpcProbe();
  553. const restored = await readTask(fork.session.sessionId);
  554. expect(restored).toMatchObject({
  555. title: TITLE,
  556. archived: false,
  557. pinned: false,
  558. projectId: fork.session.project!.projectId,
  559. });
  560. assertions.coldRestoredOrganization = restored;
  561. });
  562. });