conversation-session-fork-cold-start-membership.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. import { homedir } from "node:os";
  2. import { join } from "node:path";
  3. import { DatabaseSync } from "node:sqlite";
  4. import { chromium } from "playwright-core";
  5. import { openMobilePairingPage, seedMobileFixtureLogin } from "#e2e/helpers/mobile-pairing";
  6. import { obtainUnreadPairingUrl, showMobileTaskHome } from "#e2e/helpers/web-remote-unread";
  7. import { writeFile } from "node:fs/promises";
  8. import { ServiceChannels } from "@zcode/shared";
  9. import type { VirtualProject } from "@zcode/services";
  10. import { callHandoffHost, installHandoffRpcProbe } from "#e2e/helpers/remote-project-handoff-probe";
  11. import { TID_TASK_ITEM, TID_V4_COMPOSER_INPUT, testId } from "@zcode/shared/test-ids";
  12. import {
  13. DEFAULT_WORKSPACE,
  14. clearAppData,
  15. setInputValueByTestIdDom,
  16. } from "#e2e/helpers/desktop-app";
  17. import { restartIntoWorkspacePreservingProfile } from "#e2e/helpers/model-provider-restart";
  18. import {
  19. clickFirstV4Fork,
  20. prepareV4ConversationE2E,
  21. selectV4TaskById,
  22. sendV4Prompt,
  23. startNewV4Draft,
  24. waitForV4Fork,
  25. waitForV4MentionOptionPrefix,
  26. waitForV4Pane,
  27. waitForV4TimelineContaining,
  28. } from "#e2e/helpers/v4-conversation";
  29. const CASE_TIMEOUT_MS = 300_000;
  30. const PARENT_MARKER = "E2E_FORK_COLD_START_PROJECT_ROW";
  31. const PARENT_REPLY = "FORK_COLD_START_PROJECT_ROW_OK";
  32. describe("TSL19/TSL28/TSL41:fork child Project row 与冷启动 membership", () => {
  33. after(async () => {
  34. await browser.electron.restoreAllMocks();
  35. await clearAppData();
  36. });
  37. it("fork 后无需重启即显示可点击 Project row,重启后仍能从会话目录找到 child", async function () {
  38. this.timeout(CASE_TIMEOUT_MS);
  39. await prepareV4ConversationE2E();
  40. await sendV4Prompt(`${PARENT_MARKER}: Reply with exactly "${PARENT_REPLY}" and no other text.`);
  41. await waitForV4TimelineContaining(PARENT_REPLY, 60_000);
  42. const parent = await waitForV4Pane(
  43. (snapshot) =>
  44. !snapshot.canStop && Boolean(snapshot.sessionId && snapshot.sessionId !== "draft"),
  45. "TSL19 parent 没有完成并绑定 session",
  46. 60_000,
  47. );
  48. const parentId = requireSessionId(parent.sessionId, "parent");
  49. await waitForPersistedProjectTask(parentId);
  50. await installHandoffRpcProbe();
  51. const parentProject = await callHandoffHost<VirtualProject>(
  52. ServiceChannels.Project,
  53. "saveProject",
  54. [{ name: "Fork parent A", roots: [DEFAULT_WORKSPACE], primaryRoot: DEFAULT_WORKSPACE }],
  55. );
  56. const parentProjectId = parentProject.id;
  57. await callHandoffHost(ServiceChannels.Project, "moveTask", [
  58. { task: { workspacePath: DEFAULT_WORKSPACE, taskId: parentId }, projectId: parentProjectId },
  59. ]);
  60. expect(readTaskOwnership(parentId)?.project_id).toBe(parentProjectId);
  61. const otherProject = await callHandoffHost<VirtualProject>(
  62. ServiceChannels.Project,
  63. "saveProject",
  64. [
  65. {
  66. name: "Fork shared root B",
  67. roots: [DEFAULT_WORKSPACE],
  68. primaryRoot: DEFAULT_WORKSPACE,
  69. },
  70. ],
  71. );
  72. expect(otherProject.id).not.toBe(parentProjectId);
  73. await waitForV4Fork();
  74. expect(await clickFirstV4Fork()).toBe(true);
  75. const child = await waitForV4Pane(
  76. (snapshot) =>
  77. Boolean(
  78. snapshot.sessionId && snapshot.sessionId !== "draft" && snapshot.sessionId !== parentId,
  79. ),
  80. "TSL19 fork 后没有切换到 child",
  81. 60_000,
  82. );
  83. const childId = requireSessionId(child.sessionId, "child");
  84. expect(readCliSession(childId)).toEqual({
  85. parentId,
  86. taskType: "fork",
  87. });
  88. // Bug 根因:fork child 的 conversation hydration 会把 pane 恢复出来,但旧 gateway
  89. // 没有把 hydration 后的非 draft summary 发布给 sessions-index。于是当前 pane 正常,
  90. // task-index syncer 却永远收不到 child,Project 只能在重启回源后补出 task row。
  91. // 这里必须在不重启、不续发的窗口先证明持久行和唯一 DOM row 都已出现。
  92. await waitForPersistedProjectTask(childId);
  93. // 原断言仅检查 workspace 中有行,且在全页面找 DOM,会把未归类误当成父项目。
  94. await assertProjectOwnership(childId, parentProjectId, otherProject.id, "after-fork");
  95. await waitForSingleProjectRow(
  96. childId,
  97. "TSL28 fork child hydration 后 tasks-index 已落库,但 Project 没有唯一 child row",
  98. );
  99. // 先离开 active child,再从 Project row 点回来,排除 active pane/optimistic overlay
  100. // 临时保留同一行造成的假绿。
  101. await selectV4TaskById(parentId);
  102. await assertProjectOwnership(childId, parentProjectId, otherProject.id, "after-leave");
  103. await waitForSingleProjectRow(
  104. childId,
  105. "TSL28 离开 active child 后 Project child row 消失或重复",
  106. );
  107. await selectV4TaskById(childId);
  108. await waitForV4TimelineContaining(PARENT_REPLY, 30_000);
  109. // Bug 根因:旧冷启动查询用 parent_id is null 代替 task type membership。
  110. // 先切回未发送 draft,避免 App 重启自动 resume 当前 child 后把缺失的冷种子掩盖掉。
  111. await startNewV4Draft();
  112. await waitForV4Pane(
  113. (snapshot) => snapshot.sessionId === "draft",
  114. "TSL19 重启前没有切回 draft",
  115. 30_000,
  116. );
  117. await restartIntoWorkspacePreservingProfile();
  118. await waitForV4Pane(
  119. (snapshot) => snapshot.sessionId === "draft",
  120. "TSL19 冷启动错误恢复了 fork child",
  121. 60_000,
  122. );
  123. // mention 目录直接读取 sessions-index;在点击 child 前先看到精确 session id,
  124. // 证明 parented fork 来自冷启动 membership,而不是 select 后按需 resume 才补进内存。
  125. await setInputValueByTestIdDom(TID_V4_COMPOSER_INPUT, "#", {
  126. timeout: 15_000,
  127. timeoutMsg: "TSL19 冷启动后 composer 不可输入",
  128. });
  129. expect(await waitForV4MentionOptionPrefix(`session:${childId}`, 30_000)).toBe(
  130. `session:${childId}`,
  131. );
  132. await setInputValueByTestIdDom(TID_V4_COMPOSER_INPUT, "");
  133. await assertProjectOwnership(childId, parentProjectId, otherProject.id, "after-restart");
  134. // 首次继承之后用户移动拥有最终决定权,重复恢复不能拉回父项目。
  135. await installHandoffRpcProbe();
  136. await callHandoffHost(ServiceChannels.Project, "moveTask", [
  137. {
  138. task: { workspacePath: DEFAULT_WORKSPACE, taskId: childId },
  139. projectId: otherProject.id,
  140. },
  141. ]);
  142. await selectV4TaskById(childId);
  143. await waitForV4TimelineContaining(PARENT_REPLY, 30_000);
  144. await assertProjectOwnership(childId, otherProject.id, parentProjectId, "after-move-resume");
  145. await verifyMobileFork(parentId, parentProjectId, otherProject.id);
  146. });
  147. });
  148. function readTaskOwnership(taskId: string) {
  149. const database = new DatabaseSync(join(homedir(), ".zcode", "v2", "tasks-index.sqlite"), {
  150. readOnly: true,
  151. });
  152. try {
  153. return database
  154. .prepare(
  155. "SELECT project_id,host_id,workspace_key,forked_from_task_id FROM tasks WHERE workspace_key=? AND task_id=?",
  156. )
  157. .get(DEFAULT_WORKSPACE, taskId) as
  158. | {
  159. project_id: string | null;
  160. host_id: string;
  161. workspace_key: string;
  162. forked_from_task_id: string | null;
  163. }
  164. | undefined;
  165. } finally {
  166. database.close();
  167. }
  168. }
  169. async function assertProjectOwnership(
  170. taskId: string,
  171. expectedProjectId: string,
  172. otherProjectId: string,
  173. stage: string,
  174. ) {
  175. const ownership = readTaskOwnership(taskId);
  176. await writeFile(
  177. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, `fork-ownership-${stage}.json`),
  178. JSON.stringify({ taskId, expectedProjectId, otherProjectId, ownership }, null, 2),
  179. );
  180. expect(ownership?.project_id).toBe(expectedProjectId);
  181. for (const projectId of [expectedProjectId, otherProjectId]) {
  182. const toggle = $(`[data-project-id="${projectId}"] [data-testid="virtual-project-toggle"]`);
  183. await toggle.waitForExist({ timeout: 30_000 });
  184. if ((await toggle.getAttribute("aria-expanded")) !== "true") await toggle.click();
  185. }
  186. await browser.waitUntil(
  187. () =>
  188. browser.execute(
  189. (taskTestId, expected, other) => {
  190. const selector = `[data-testid="${taskTestId}"]`;
  191. return (
  192. document.querySelectorAll(`[data-project-id="${expected}"] ${selector}`).length === 1 &&
  193. document.querySelectorAll(`[data-project-id="${other}"] ${selector}`).length === 0 &&
  194. document.querySelectorAll(`[data-testid="conversation-section"] ${selector}`).length ===
  195. 0
  196. );
  197. },
  198. testId(TID_TASK_ITEM, taskId),
  199. expectedProjectId,
  200. otherProjectId,
  201. ),
  202. { timeout: 30_000, timeoutMsg: `TSL41 ${stage}: fork 行不在指定项目内或重复出现在其他区域` },
  203. );
  204. await browser.saveScreenshot(
  205. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, `fork-ownership-${stage}.png`),
  206. );
  207. }
  208. async function waitForPersistedProjectTask(taskId: string): Promise<void> {
  209. await browser.waitUntil(
  210. () => readWorkspaceTaskIds().filter((candidate) => candidate === taskId).length === 1,
  211. {
  212. timeout: 30_000,
  213. timeoutMsg: `TSL28 fork child 没有写入唯一 tasks-index row: ${taskId}`,
  214. },
  215. );
  216. }
  217. async function waitForSingleProjectRow(taskId: string, timeoutMsg: string): Promise<void> {
  218. await browser.waitUntil(
  219. () =>
  220. browser.execute(
  221. (taskItemTestId) =>
  222. document.querySelectorAll(`[data-testid="${taskItemTestId}"]`).length === 1,
  223. testId(TID_TASK_ITEM, taskId),
  224. ),
  225. {
  226. timeout: 30_000,
  227. timeoutMsg,
  228. },
  229. );
  230. }
  231. function readWorkspaceTaskIds(): string[] {
  232. // Node 当前内置 SQLite 只提供 DatabaseSync;E2E 轮询每次都立即关闭只读句柄。
  233. const database = new DatabaseSync(join(homedir(), ".zcode", "v2", "tasks-index.sqlite"), {
  234. readOnly: true,
  235. });
  236. try {
  237. const rows = database
  238. .prepare("select task_id from tasks where workspace_key = ? and deleted = 0 order by task_id")
  239. .all(DEFAULT_WORKSPACE) as Array<{ task_id: string }>;
  240. return rows.map((row) => row.task_id);
  241. } finally {
  242. database.close();
  243. }
  244. }
  245. function requireSessionId(value: string | null, label: string): string {
  246. if (!value || value === "draft") {
  247. throw new Error(`TSL19 缺少 ${label} sessionId: ${String(value)}`);
  248. }
  249. return value;
  250. }
  251. function readCliSession(sessionId: string): {
  252. parentId: string | null;
  253. taskType: string | null;
  254. } | null {
  255. // Node 当前内置 SQLite 只提供 DatabaseSync;E2E 只读一次并立即关闭句柄。
  256. const database = new DatabaseSync(join(homedir(), ".zcode", "cli", "db", "db.sqlite"), {
  257. readOnly: true,
  258. });
  259. try {
  260. const row = database
  261. .prepare("select parent_id, task_type from session where id = ?")
  262. .get(sessionId) as { parent_id: string | null; task_type: string | null } | undefined;
  263. return row ? { parentId: row.parent_id, taskType: row.task_type } : null;
  264. } finally {
  265. database.close();
  266. }
  267. }
  268. async function verifyMobileFork(parentId: string, projectId: string, otherProjectId: string) {
  269. const pairingUrl = await obtainUnreadPairingUrl(
  270. new URL(process.env.ZCODE_WEB_REMOTE_CONTROL_URL!).origin,
  271. );
  272. const webBrowser = await chromium.launch({
  273. executablePath: process.env.ZCODE_E2E_MOBILE_BROWSER_EXECUTABLE,
  274. headless: true,
  275. args: ["--no-sandbox"],
  276. });
  277. try {
  278. const context = await webBrowser.newContext({
  279. viewport: { width: 390, height: 844 },
  280. isMobile: true,
  281. hasTouch: true,
  282. locale: "zh-CN",
  283. });
  284. await seedMobileFixtureLogin(context);
  285. const page = await context.newPage();
  286. const projectSelector = `[data-project-id="${projectId}"]`;
  287. await openMobilePairingPage(page, pairingUrl, {
  288. artifactDir: process.env.ZCODE_E2E_ARTIFACT_DIR!,
  289. caseMarker: "TSL41",
  290. phase: "fork",
  291. readySelector: projectSelector,
  292. });
  293. const toggle = page.locator(projectSelector).getByTestId("virtual-project-toggle");
  294. if ((await toggle.getAttribute("aria-expanded")) !== "true") await toggle.tap();
  295. await page.locator(projectSelector).getByTestId(testId(TID_TASK_ITEM, parentId)).tap();
  296. await page.locator(`[data-session-id="${parentId}"]`).waitFor();
  297. await page.locator('[data-testid^="v4-fork-"]').first().tap();
  298. await page.waitForFunction((parentId) => {
  299. const id = document.querySelector("[data-session-id]")?.getAttribute("data-session-id");
  300. return id && id !== "draft" && id !== parentId;
  301. }, parentId);
  302. const childId = (await page.locator("[data-session-id]").getAttribute("data-session-id"))!;
  303. expect(readCliSession(childId)?.parentId).toBe(parentId);
  304. await waitForPersistedProjectTask(childId);
  305. expect(readTaskOwnership(childId)?.project_id).toBe(projectId);
  306. await showMobileTaskHome(page);
  307. if ((await toggle.getAttribute("aria-expanded")) !== "true") await toggle.tap();
  308. await page.locator(projectSelector).getByTestId(testId(TID_TASK_ITEM, childId)).waitFor();
  309. expect(
  310. await page
  311. .locator(`[data-project-id="${otherProjectId}"]`)
  312. .getByTestId(testId(TID_TASK_ITEM, childId))
  313. .count(),
  314. ).toBe(0);
  315. expect(
  316. await page
  317. .locator('[data-testid="conversation-section"]')
  318. .getByTestId(testId(TID_TASK_ITEM, childId))
  319. .count(),
  320. ).toBe(0);
  321. await page.screenshot({
  322. path: join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "fork-ownership-mobile.png"),
  323. fullPage: true,
  324. });
  325. await writeFile(
  326. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "fork-ownership-mobile.json"),
  327. JSON.stringify(
  328. { parentId, childId, projectId, ownership: readTaskOwnership(childId) },
  329. null,
  330. 2,
  331. ),
  332. );
  333. } finally {
  334. await webBrowser.close();
  335. }
  336. }