fork-background-history.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. import { homedir } from "node:os";
  2. import { writeFile } from "node:fs/promises";
  3. import { join } from "node:path";
  4. import { DatabaseSync } from "node:sqlite";
  5. import { chromium } from "playwright-core";
  6. import { BufferReader, BufferWriter, deserialize, serialize, VSBuffer } from "@zcode/rpc";
  7. import { TID_TASK_ITEM, testId } from "@zcode/shared/test-ids";
  8. import { openMobilePairingPage, seedMobileFixtureLogin } from "#e2e/helpers/mobile-pairing";
  9. import { obtainUnreadPairingUrl } from "#e2e/helpers/web-remote-unread";
  10. import { restartIntoWorkspacePreservingProfile } from "#e2e/helpers/model-provider-restart";
  11. import {
  12. clickFirstV4Fork,
  13. getV4PaneSnapshot,
  14. selectV4TaskById,
  15. startNewV4Draft,
  16. waitForV4Fork,
  17. waitForV4Pane,
  18. waitForV4TimelineContaining,
  19. } from "#e2e/helpers/v4-conversation";
  20. interface ForkFault {
  21. request?: number[];
  22. calls: number;
  23. reply(response: number[]): void;
  24. restore(): void;
  25. }
  26. declare global {
  27. interface Window {
  28. __forkHistoryFault?: ForkFault;
  29. }
  30. }
  31. /** BG04 / FX14:真实轮内通知必须跨连续 fork、进程重启与手机保持原轮。 */
  32. export async function assertForkAfterBackgroundNotification(finalText: string) {
  33. const parentId = (await getV4PaneSnapshot()).sessionId!;
  34. expect(parentId).not.toBe("draft");
  35. const before = readHistory(parentId);
  36. await writeFile(
  37. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "fork-background-source.json"),
  38. JSON.stringify(before, null, 2),
  39. );
  40. // live anchor 的 productTurnId 由首次 fork resolver 惰性补齐;不能要求首 fork 前已存在。
  41. assertInTurnNotification(before, false);
  42. const childId = await forkCurrent(parentId, finalText);
  43. assertInTurnNotification(readHistory(childId));
  44. const stableParent = readHistory(parentId);
  45. assertInTurnNotification(stableParent);
  46. expect(stableParent.map((entry) => entry.id)).toEqual(before.map((entry) => entry.id));
  47. const grandchildId = await forkCurrent(childId, finalText);
  48. assertInTurnNotification(readHistory(grandchildId));
  49. expect(readHistory(parentId)).toEqual(stableParent);
  50. await startNewV4Draft();
  51. await restartIntoWorkspacePreservingProfile();
  52. await selectV4TaskById(childId);
  53. await waitForV4TimelineContaining(finalText);
  54. await forkCurrent(childId, finalText);
  55. // 只在测试 RPC 边界注入失败;真实 CLI/数据库不接受这些请求,也不会生成 child。
  56. await assertVisibleForkFailure("ack");
  57. await assertVisibleForkFailure("transport");
  58. await assertMobileFork(childId, finalText);
  59. expect(readHistory(parentId)).toEqual(stableParent);
  60. }
  61. async function forkCurrent(parentId: string, finalText: string) {
  62. await waitForV4Fork();
  63. expect(await clickFirstV4Fork()).toBe(true);
  64. const child = await waitForV4Pane(
  65. (pane) => Boolean(pane.sessionId && pane.sessionId !== "draft" && pane.sessionId !== parentId),
  66. "FX14 点击 fork 后没有切到 child",
  67. 30_000,
  68. );
  69. await waitForV4TimelineContaining(finalText);
  70. return child.sessionId!;
  71. }
  72. type StoredMessage = {
  73. id: string;
  74. data: {
  75. role: string;
  76. metadata?: { inputPresentation?: string };
  77. anchor?: { productTurnId?: string; orderedMessageIds?: string[]; boundaryMessageId?: string };
  78. };
  79. };
  80. function readHistory(sessionId: string): StoredMessage[] {
  81. // Node 内置 SQLite 只有同步 API;隔离测试库仅作短只读查询,立即关闭句柄。
  82. const db = new DatabaseSync(join(homedir(), ".zcode", "cli", "db", "db.sqlite"), {
  83. readOnly: true,
  84. });
  85. try {
  86. const rows = db
  87. .prepare("SELECT id, data FROM message WHERE session_id=? ORDER BY time_created, id")
  88. .all(sessionId) as Array<{ id: string; data: string }>;
  89. return rows.map((row) => ({ id: row.id, data: JSON.parse(row.data) }));
  90. } finally {
  91. db.close();
  92. }
  93. }
  94. function assertInTurnNotification(messages: StoredMessage[], requireProductTurnId = true) {
  95. const notification = messages.find(
  96. (entry) => entry.data.metadata?.inputPresentation === "task_notification_steer",
  97. );
  98. expect(notification).toBeDefined();
  99. const boundary = messages.find(
  100. (entry) =>
  101. entry.data.role === "assistant" &&
  102. entry.data.anchor?.orderedMessageIds?.includes(notification!.id),
  103. );
  104. expect(boundary).toBeDefined();
  105. expect(boundary!.data.anchor!.productTurnId).not.toBe(notification!.id);
  106. if (requireProductTurnId) {
  107. expect(messages.some((entry) => entry.id === boundary!.data.anchor!.productTurnId)).toBe(true);
  108. }
  109. }
  110. async function assertVisibleForkFailure(kind: "ack" | "transport") {
  111. const parentId = (await getV4PaneSnapshot()).sessionId;
  112. // 等上一条提示自然关闭,防止第二种故障误用第一条提示通过断言。
  113. await browser.waitUntil(async () => !(await hasForkFailureToast()), { timeout: 10_000 });
  114. await browser.execute(() => {
  115. const original = MessagePort.prototype.postMessage;
  116. const fault: ForkFault = {
  117. calls: 0,
  118. reply() {
  119. throw new Error("FX14 fork 请求尚未捕获");
  120. },
  121. restore() {
  122. MessagePort.prototype.postMessage = original;
  123. delete window.__forkHistoryFault;
  124. },
  125. };
  126. MessagePort.prototype.postMessage = function (message: unknown, options?: unknown) {
  127. if (message instanceof Uint8Array) {
  128. const text = new TextDecoder().decode(message);
  129. if (text.includes("sendConversationCommandV4") && text.includes("forkAssistant")) {
  130. fault.calls += 1;
  131. fault.reply = (response) => {
  132. this.dispatchEvent(new MessageEvent("message", { data: Uint8Array.from(response) }));
  133. };
  134. fault.request = Array.from(message);
  135. return;
  136. }
  137. }
  138. Reflect.apply(original, this, options === undefined ? [message] : [message, options]);
  139. };
  140. window.__forkHistoryFault = fault;
  141. });
  142. try {
  143. await waitForV4Fork();
  144. expect(await clickFirstV4Fork()).toBe(true);
  145. await browser.waitUntil(
  146. () => browser.execute(() => Boolean(window.__forkHistoryFault?.request)),
  147. { timeout: 10_000 },
  148. );
  149. const raw = await browser.execute(() => window.__forkHistoryFault!.request!);
  150. const reader = new BufferReader(VSBuffer.wrap(Uint8Array.from(raw)));
  151. const header = deserialize(reader) as [number, number, string, string];
  152. const args = deserialize(reader) as [{ envelope: { commandId: string; baseRevision: number } }];
  153. expect(header[3]).toBe("sendConversationCommandV4");
  154. const writer = new BufferWriter();
  155. serialize(writer, [kind === "ack" ? 201 : 202, header[1]]);
  156. serialize(
  157. writer,
  158. kind === "ack"
  159. ? {
  160. commandId: args[0].envelope.commandId,
  161. status: "failed",
  162. reasonCode: "guard.forkTargetAmbiguous",
  163. revisionAtDecision: args[0].envelope.baseRevision,
  164. }
  165. : { name: "Error", message: "E2E_FORK_TRANSPORT_FAILURE" },
  166. );
  167. await browser.execute(
  168. (response) => window.__forkHistoryFault!.reply(response),
  169. Array.from(writer.buffer.buffer),
  170. );
  171. await browser.waitUntil(hasForkFailureToast, {
  172. timeout: 10_000,
  173. timeoutMsg: `FX14 ${kind} 失败没有可见提示`,
  174. });
  175. expect((await getV4PaneSnapshot()).sessionId).toBe(parentId);
  176. expect(await browser.execute(() => window.__forkHistoryFault!.calls)).toBe(1);
  177. await browser.saveScreenshot(
  178. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, `fork-failure-${kind}.png`),
  179. );
  180. } finally {
  181. await browser.execute(() => window.__forkHistoryFault?.restore());
  182. }
  183. }
  184. function hasForkFailureToast() {
  185. return browser.execute(() =>
  186. /分叉会话失败|Could not fork session/u.test(document.body.innerText),
  187. );
  188. }
  189. async function assertMobileFork(parentId: string, finalText: string) {
  190. const pairingUrl = await obtainUnreadPairingUrl(
  191. new URL(process.env.ZCODE_WEB_REMOTE_CONTROL_URL!).origin,
  192. );
  193. const webBrowser = await chromium.launch({
  194. executablePath: process.env.ZCODE_E2E_MOBILE_BROWSER_EXECUTABLE,
  195. headless: true,
  196. args: ["--no-sandbox"],
  197. });
  198. try {
  199. const context = await webBrowser.newContext({
  200. viewport: { width: 390, height: 844 },
  201. isMobile: true,
  202. hasTouch: true,
  203. locale: "zh-CN",
  204. });
  205. await seedMobileFixtureLogin(context);
  206. const page = await context.newPage();
  207. await openMobilePairingPage(page, pairingUrl, {
  208. artifactDir: process.env.ZCODE_E2E_ARTIFACT_DIR!,
  209. caseMarker: "FX14",
  210. phase: "fork",
  211. readySelector: '[data-testid="virtual-project-toggle"]',
  212. });
  213. for (const toggle of await page.getByTestId("virtual-project-toggle").all()) {
  214. if ((await toggle.getAttribute("aria-expanded")) !== "true") await toggle.tap();
  215. }
  216. await page.getByTestId(testId(TID_TASK_ITEM, parentId)).first().tap();
  217. await page.locator(`[data-session-id="${parentId}"]`).waitFor();
  218. await page.locator('[data-testid^="v4-fork-"]').first().tap();
  219. await page.waitForFunction((parentId) => {
  220. const id = document.querySelector("[data-session-id]")?.getAttribute("data-session-id");
  221. return id && id !== "draft" && id !== parentId;
  222. }, parentId);
  223. const childId = (await page.locator("[data-session-id]").getAttribute("data-session-id"))!;
  224. await page.getByText(finalText, { exact: true }).first().waitFor();
  225. assertInTurnNotification(readHistory(childId));
  226. await page.screenshot({
  227. path: join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "fork-background-mobile.png"),
  228. fullPage: true,
  229. });
  230. } finally {
  231. await webBrowser.close();
  232. }
  233. }