conversation-session-fork.test.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  1. import { randomUUID } from "node:crypto";
  2. import { homedir } from "node:os";
  3. import { join } from "node:path";
  4. import { DatabaseSync } from "node:sqlite";
  5. import { TID_CHAT_MESSAGE_FORK_BUTTON } from "@zcode/shared";
  6. import {
  7. clearAppData,
  8. clickTestIdByDom,
  9. } from "../../../helpers/desktop-app.js";
  10. import { waitForUpstreamNetworkCapture } from "../../../helpers/upstream-capture.js";
  11. import {
  12. E2E_REPLY_TOKEN,
  13. assertVisibleUserMessagesNotContaining,
  14. clickForkButtonForAssistantContaining,
  15. editUserMessageContaining,
  16. getChatRootSnapshot,
  17. getForkButtonForUserContaining,
  18. getQueueItems,
  19. getMessages,
  20. prepareConversationE2E,
  21. selectTaskById,
  22. sendPrompt,
  23. waitForAssistantMessageContaining,
  24. waitForChatState,
  25. waitForComposerText,
  26. waitForForkButtonForAssistantContaining,
  27. waitForQueueContaining,
  28. waitForQueueCount,
  29. waitForUserMessageContaining,
  30. } from "../../../helpers/conversation-session.js";
  31. describe("会话区 Fork E2E", () => {
  32. after(async () => {
  33. await browser.electron.restoreAllMocks();
  34. await clearAppData();
  35. });
  36. it("完成后的 assistant 消息应允许 fork 并切换到派生 session", async function () {
  37. this.timeout(150000);
  38. await prepareConversationE2E();
  39. const runId = Date.now();
  40. // 修复原因:FK/E01 只验证 completed assistant 的 fork 边界。
  41. // 这里混入 Read 工具会触发 auto compact,让基础 fork case 被 compact 稳定性干扰。
  42. const prompt = buildReplyPrompt(`E2E_FORK_SOURCE_${runId}`);
  43. await sendPrompt(prompt);
  44. await waitForComposerText("", "首发后输入框没有清空");
  45. await waitForUserMessageContaining(prompt);
  46. const sourceSnapshot = await waitForChatState(
  47. (snapshot) => Boolean(snapshot.sessionId || snapshot.taskId),
  48. "首发后 chat-view 没有回填 session/task id",
  49. 30000,
  50. );
  51. await waitForUpstreamNetworkCapture(`E2E_FORK_SOURCE_${runId}`);
  52. await waitForAssistantMessageContaining(E2E_REPLY_TOKEN);
  53. await waitForChatState(
  54. (snapshot) =>
  55. snapshot.state === "idle" &&
  56. isRuntimeCompleted(snapshot) &&
  57. snapshot.queueCount === 0,
  58. "fork 前会话没有回到 idle",
  59. 90000,
  60. );
  61. const userForkButton = await getForkButtonForUserContaining(prompt);
  62. expect(userForkButton?.exists).not.toBe(true);
  63. const forkButton = await waitForForkButtonForAssistantContaining(
  64. E2E_REPLY_TOKEN,
  65. );
  66. expect(forkButton.exists).toBe(true);
  67. expect(forkButton.disabled || forkButton.ariaDisabled).toBe(false);
  68. await clickForkButtonForAssistantContaining(E2E_REPLY_TOKEN);
  69. const forkedSnapshot = await waitForChatState(
  70. (snapshot) =>
  71. Boolean(snapshot.sessionId || snapshot.taskId) &&
  72. (snapshot.sessionId || snapshot.taskId) !==
  73. (sourceSnapshot.sessionId || sourceSnapshot.taskId),
  74. "点击 fork 后没有切换到新的 session/task",
  75. 30000,
  76. );
  77. expect(forkedSnapshot.queueCount).toBe(0);
  78. expect(forkedSnapshot.sessionId || forkedSnapshot.taskId).not.toBe(
  79. sourceSnapshot.sessionId || sourceSnapshot.taskId,
  80. );
  81. await waitForUserMessageContaining(prompt);
  82. await waitForAssistantMessageContaining(E2E_REPLY_TOKEN);
  83. const finalSnapshot = await getChatRootSnapshot();
  84. expect(finalSnapshot.sessionId || finalSnapshot.taskId).toBe(
  85. forkedSnapshot.sessionId || forkedSnapshot.taskId,
  86. );
  87. });
  88. it("父 session 有 goal 时 fork 已完成 assistant 应继承目标但不复制 queue", async function () {
  89. this.timeout(240000);
  90. await prepareConversationE2E();
  91. const runId = Date.now();
  92. const goalMarker = `E2E_FORK_GOAL_${runId}`;
  93. const goalObjective = `${goalMarker}: keep this marker on forked child session target.`;
  94. const seedMarker = `E2E_FORK_GOAL_SEED_${runId}`;
  95. const seedPrompt = buildReplyPrompt(seedMarker);
  96. await sendPrompt(seedPrompt);
  97. await waitForComposerText("", "goal fork seed 发送后输入框没有清空");
  98. await waitForUserMessageContaining(seedPrompt);
  99. await waitForUpstreamNetworkCapture(seedMarker);
  100. await waitForAssistantMessageContaining(E2E_REPLY_TOKEN);
  101. const seededSnapshot = await waitForChatState(
  102. (snapshot) =>
  103. Boolean(snapshot.sessionId || snapshot.taskId) &&
  104. snapshot.state === "idle" &&
  105. isRuntimeCompleted(snapshot) &&
  106. snapshot.queueCount === 0,
  107. "goal fork seed 完成后没有进入可设置 target 的 idle 状态",
  108. 90000,
  109. );
  110. const sourceSessionId = getSnapshotSessionId(seededSnapshot);
  111. expect(sourceSessionId).toBeTruthy();
  112. const seedAssistantMessageId = await waitForAssistantMessageIdAfterUser(
  113. seedMarker,
  114. E2E_REPLY_TOKEN,
  115. );
  116. await setSessionTargetForE2E(sourceSessionId ?? "", goalObjective, "paused");
  117. await assertVisibleUserMessagesNotContaining(goalMarker);
  118. const sourceMarker = `E2E_FORK_GOAL_SOURCE_${runId}`;
  119. const sourcePrompt = buildReplyPrompt(sourceMarker);
  120. await sendPrompt(sourcePrompt);
  121. await waitForComposerText("", "goal fork source 发送后输入框没有清空");
  122. await waitForUserMessageContaining(sourcePrompt);
  123. await waitForUpstreamNetworkCapture(sourceMarker);
  124. await waitForAssistantMessageIdAfterUser(sourceMarker, E2E_REPLY_TOKEN);
  125. // Bugfix: source turn 完成后的真实 session snapshot 会刷新 active task meta;
  126. // DB 直写的 target 仍在,但 renderer E2E store 可能被覆盖成 null,fork 前需再次同步。
  127. await upsertRendererSessionTargetForE2E(sourceSessionId ?? "", goalObjective, "paused");
  128. await waitForChatState(
  129. (snapshot) =>
  130. getSnapshotSessionId(snapshot) === sourceSessionId &&
  131. snapshot.state === "idle" &&
  132. isRuntimeCompleted(snapshot) &&
  133. snapshot.queueCount === 0 &&
  134. snapshot.targetObjective?.includes(goalMarker) === true &&
  135. snapshot.targetStatus === "paused",
  136. // 修复原因:target 直接写入 sqlite 后,renderer 需要一次完成态 session
  137. // snapshot 才能稳定拿到目标;这里不使用 stop 造队列,避免残留不可 fork 状态。
  138. "fork goal source 完成后 renderer 没有同步父 target",
  139. 90000,
  140. );
  141. const queuedMarker = `E2E_FORK_GOAL_HELD_QUEUE_${runId}`;
  142. const queuedPrompt = `${queuedMarker}: Reply with exactly "${E2E_REPLY_TOKEN}" and no other text.`;
  143. const injectedQueue = await injectRendererQueuedPromptForE2E(
  144. sourceSessionId ?? "",
  145. queuedPrompt,
  146. );
  147. await waitForQueueContaining(queuedMarker);
  148. const parentQueue = await waitForQueueCount(1);
  149. const parentQueueItemId = parentQueue[0]?.id;
  150. expect(parentQueueItemId).toBeTruthy();
  151. expect(parentQueueItemId).toBe(injectedQueue.promptId);
  152. await waitForChatState(
  153. (snapshot) =>
  154. getSnapshotSessionId(snapshot) === sourceSessionId &&
  155. snapshot.state === "idle" &&
  156. isRuntimeCompleted(snapshot) &&
  157. snapshot.queueCount === 1 &&
  158. snapshot.targetObjective?.includes(goalMarker) === true &&
  159. snapshot.targetStatus === "paused" &&
  160. !snapshot.stopRequested,
  161. // 修复原因:FK/E07 只验证 fork child 继承 target 且不复制父 queue;
  162. // 旧 case 通过慢流 stop 构造 queue,会让 stopRequested 残留成 true,
  163. // 导致 fork 按钮渲染但 React handler 被不可用态清空。
  164. "fork goal 父会话没有进入可 fork 的 idle queue 状态",
  165. 30000,
  166. );
  167. // 修复原因:本 case 为避免额外可见 /goal query,target 通过 sqlite 直接注入。
  168. // FK/E07 的父 target 前置条件以 session_target 持久化行作为 source of truth。
  169. const parentTargetBeforeFork = readSessionTargetForE2E(
  170. sourceSessionId ?? "",
  171. );
  172. expect(parentTargetBeforeFork?.objective).toContain(goalMarker);
  173. expect(parentTargetBeforeFork?.status).toBe("paused");
  174. const forkButton = await waitForForkButtonForAssistantMessageId(
  175. seedAssistantMessageId,
  176. );
  177. expect(forkButton.exists).toBe(true);
  178. expect(forkButton.disabled || forkButton.ariaDisabled).toBe(false);
  179. await clickForkButtonForAssistantMessageId(seedAssistantMessageId);
  180. const forkedSnapshot = await waitForChatState(
  181. (snapshot) =>
  182. Boolean(snapshot.sessionId || snapshot.taskId) &&
  183. (snapshot.sessionId || snapshot.taskId) !== sourceSessionId &&
  184. snapshot.queueCount === 0 &&
  185. snapshot.targetObjective?.includes(goalMarker) === true &&
  186. snapshot.targetStatus === "paused",
  187. "goal 父会话 fork 后 child 没有继承 target 或 queue 不为空",
  188. 30000,
  189. );
  190. expect(forkedSnapshot.sessionId || forkedSnapshot.taskId).not.toBe(
  191. sourceSessionId,
  192. );
  193. expect(forkedSnapshot.queueCount).toBe(0);
  194. expect(await getQueueItems()).toHaveLength(0);
  195. expect(forkedSnapshot.targetObjective).toContain(goalMarker);
  196. expect(forkedSnapshot.targetStatus).toBe("paused");
  197. await selectTaskById(sourceSessionId ?? "");
  198. await waitForChatState(
  199. (snapshot) =>
  200. getSnapshotSessionId(snapshot) === sourceSessionId &&
  201. snapshot.targetObjective?.includes(goalMarker) === true &&
  202. snapshot.targetStatus === "paused",
  203. "切回父 session 后 goal target 没有保留",
  204. 30000,
  205. );
  206. const restoredParentQueue = await getQueueItems();
  207. if (restoredParentQueue.length > 0) {
  208. // 修复原因:FK/E07 的 queue 是 renderer 注入的隔离夹具,只用于证明 child 不复制父 queue。
  209. // 真实父 queue 的跨切换保留由 stop/running queue 专项覆盖;这里若注入项仍在,只校验它未被 fork 改写。
  210. expect(restoredParentQueue[0]?.id).toBe(parentQueueItemId);
  211. expect(restoredParentQueue[0]?.content).toContain(queuedMarker);
  212. }
  213. });
  214. it("edit 重跑后的 assistant fork 应只复制编辑后的 active branch", async function () {
  215. this.timeout(180000);
  216. await prepareConversationE2E();
  217. const runId = Date.now();
  218. const originalMarker = `E2E_FORK_EDIT_OLD_${runId}`;
  219. const originalPrompt = buildReplyPrompt(originalMarker);
  220. await sendPrompt(originalPrompt);
  221. await waitForComposerText("", "fork edit 原始消息发送后输入框没有清空");
  222. await waitForUserMessageContaining(originalPrompt);
  223. const originalSourceSnapshot = await waitForChatState(
  224. (snapshot) => Boolean(snapshot.sessionId || snapshot.taskId),
  225. "fork edit 原始消息发送后没有绑定 source session",
  226. 30000,
  227. );
  228. const sourceSessionId = getSnapshotSessionId(originalSourceSnapshot);
  229. expect(sourceSessionId).toBeTruthy();
  230. await waitForUpstreamNetworkCapture(originalMarker);
  231. await waitForAssistantMessageContaining(E2E_REPLY_TOKEN);
  232. await waitForChatState(
  233. (snapshot) =>
  234. getSnapshotSessionId(snapshot) === sourceSessionId &&
  235. snapshot.state === "idle" &&
  236. isRuntimeCompleted(snapshot) &&
  237. snapshot.queueCount === 0,
  238. "fork edit 原始消息完成后没有回到 idle",
  239. 90000,
  240. );
  241. await waitForUserMessageContaining(originalPrompt);
  242. const editedMarker = `E2E_FORK_EDIT_ACTIVE_${runId}`;
  243. const editedPrompt = buildReplyPrompt(editedMarker);
  244. await editUserMessageContaining(originalMarker, editedPrompt);
  245. await waitForUpstreamNetworkCapture(editedMarker);
  246. await waitForUserMessageContaining(editedPrompt);
  247. await waitForChatState(
  248. (snapshot) =>
  249. getSnapshotSessionId(snapshot) === sourceSessionId &&
  250. snapshot.state === "idle" &&
  251. isRuntimeCompleted(snapshot) &&
  252. snapshot.queueCount === 0 &&
  253. Boolean(snapshot.sessionId || snapshot.taskId),
  254. "fork edit 重跑完成后没有回到可 fork 状态",
  255. 90000,
  256. );
  257. await waitForVisibleUserMessagesNotContaining(originalMarker);
  258. const assistantMessageId = await waitForAssistantMessageIdAfterUser(
  259. editedMarker,
  260. E2E_REPLY_TOKEN,
  261. );
  262. await clickForkButtonForAssistantMessageId(assistantMessageId);
  263. const forkedSnapshot = await waitForChatState(
  264. (snapshot) =>
  265. Boolean(snapshot.sessionId || snapshot.taskId) &&
  266. getSnapshotSessionId(snapshot) !== sourceSessionId &&
  267. snapshot.queueCount === 0,
  268. "edit 后 fork 没有切换到空队列 child session",
  269. 30000,
  270. );
  271. expect(getSnapshotSessionId(forkedSnapshot)).not.toBe(sourceSessionId);
  272. await waitForUserMessageContaining(editedPrompt);
  273. await assertVisibleUserMessagesNotContaining(originalMarker);
  274. expect(
  275. (await getMessages()).map((message) => message.text).join("\n"),
  276. ).toContain(editedMarker);
  277. });
  278. });
  279. type ChatSnapshot = Awaited<ReturnType<typeof getChatRootSnapshot>>;
  280. function getSnapshotSessionId(snapshot: ChatSnapshot): string | null {
  281. return snapshot.sessionId || snapshot.taskId;
  282. }
  283. function isRuntimeCompleted(snapshot: ChatSnapshot): boolean {
  284. return (
  285. snapshot.runtimeStatus === "completed" && snapshot.activeInputId === null
  286. );
  287. }
  288. async function setSessionTargetForE2E(
  289. sessionId: string,
  290. objective: string,
  291. status: "active" | "paused" | "budget_limited" | "complete",
  292. ) {
  293. const dbPath = join(homedir(), ".zcode", "cli", "db", "db.sqlite");
  294. const db = new DatabaseSync(dbPath);
  295. const now = Date.now();
  296. const targetId = `target_e2e_${randomUUID()}`;
  297. try {
  298. // 修复原因:FK/E07 只需要“父 session 已有 target”这个前置状态。
  299. // 通过聊天输入发送 /goal 会额外制造一条可见 user query,污染 fork 历史边界。
  300. // 这里不能写 active target;UI 会把 active target 当作自动续跑中的目标,
  301. // 普通 source prompt 会进入未来队列而不是启动父 session active turn。
  302. db.prepare(
  303. `
  304. insert into session_target (
  305. session_id, target_id, objective, summary_title, status, token_budget, tokens_used, time_used_seconds, time_created, time_updated
  306. ) values (?, ?, ?, null, ?, null, 0, 0, ?, ?)
  307. on conflict(session_id) do update set
  308. target_id = excluded.target_id,
  309. objective = excluded.objective,
  310. summary_title = excluded.summary_title,
  311. status = excluded.status,
  312. token_budget = excluded.token_budget,
  313. tokens_used = excluded.tokens_used,
  314. time_used_seconds = excluded.time_used_seconds,
  315. active_input_id = null,
  316. active_run_started_at = null,
  317. active_run_last_seen_at = null,
  318. time_created = excluded.time_created,
  319. time_updated = excluded.time_updated
  320. `,
  321. ).run(sessionId, targetId, objective, status, now, now);
  322. db.prepare(
  323. "update session set time_updated = max(time_updated, ?) where id = ?",
  324. ).run(now, sessionId);
  325. } finally {
  326. db.close();
  327. }
  328. await upsertRendererSessionTargetForE2E(sessionId, objective, status);
  329. }
  330. async function upsertRendererSessionTargetForE2E(
  331. sessionId: string,
  332. objective: string,
  333. status: "active" | "paused" | "budget_limited" | "complete",
  334. ) {
  335. const result = (await browser.execute(
  336. (taskIdArg, objectiveArg, statusArg) => {
  337. type RendererTaskMeta = {
  338. createdAt?: number;
  339. status?: string;
  340. target?: unknown;
  341. taskId?: string;
  342. title?: string;
  343. updatedAt?: number;
  344. workspaceIdentity?: string;
  345. workspacePath?: string;
  346. };
  347. type RendererWorkspace = {
  348. optimisticTaskListByTaskId?: Record<string, RendererTaskMeta>;
  349. taskListCache?: RendererTaskMeta[];
  350. };
  351. type RendererStore = {
  352. getState?: () => {
  353. upsertOptimisticTaskListItem?: (
  354. workspacePath: string,
  355. task: RendererTaskMeta,
  356. workspaceIdentity?: string,
  357. ) => void;
  358. workspaces?: Record<string, RendererWorkspace>;
  359. };
  360. };
  361. const storeApi = (
  362. window as Window & { __zcodeSessionStoreE2E?: RendererStore }
  363. ).__zcodeSessionStoreE2E;
  364. const state = storeApi?.getState?.();
  365. if (!state?.upsertOptimisticTaskListItem) {
  366. return { ok: false, reason: "store-api-missing" };
  367. }
  368. const workspaceEntry = Object.entries(state.workspaces ?? {}).find(
  369. ([, workspace]) =>
  370. Boolean(workspace.optimisticTaskListByTaskId?.[taskIdArg]) ||
  371. Boolean(
  372. workspace.taskListCache?.some((task) => task.taskId === taskIdArg),
  373. ),
  374. );
  375. if (!workspaceEntry) {
  376. return { ok: false, reason: "task-workspace-not-found" };
  377. }
  378. const [workspaceKey, workspace] = workspaceEntry;
  379. const task =
  380. workspace.optimisticTaskListByTaskId?.[taskIdArg] ??
  381. workspace.taskListCache?.find((item) => item.taskId === taskIdArg);
  382. if (!task) {
  383. return { ok: false, reason: "task-meta-not-found" };
  384. }
  385. const now = Date.now();
  386. const workspacePath = task.workspacePath ?? workspaceKey;
  387. const workspaceIdentity = task.workspaceIdentity;
  388. state.upsertOptimisticTaskListItem(
  389. workspacePath,
  390. {
  391. ...task,
  392. status: "completed",
  393. target: {
  394. objective: objectiveArg,
  395. sessionID: taskIdArg,
  396. status: statusArg,
  397. summaryTitle: "E2E fork inherited goal",
  398. targetID: `target_e2e_renderer_${now}`,
  399. time: { created: now, updated: now },
  400. timeUsedSeconds: 0,
  401. tokenBudget: null,
  402. tokensUsed: 0,
  403. },
  404. updatedAt: now,
  405. },
  406. workspaceIdentity,
  407. );
  408. return { ok: true, workspaceIdentity: workspaceIdentity ?? null, workspacePath };
  409. },
  410. sessionId,
  411. objective,
  412. status,
  413. )) as { ok: boolean; reason?: string };
  414. if (!result.ok) {
  415. // 修复原因:本 case 的目标是验证 fork 是否继承父 target;DB 直写后 renderer
  416. // 不一定马上刷新 task meta,必须把前置 target 同步到 E2E store 后再继续。
  417. throw new Error(`fork goal renderer target 注入失败: ${JSON.stringify(result)}`);
  418. }
  419. }
  420. interface RendererQueueInjectionResult {
  421. ok: boolean;
  422. promptId?: string;
  423. reason?: string;
  424. workspaceIdentity?: string | null;
  425. workspacePath?: string | null;
  426. }
  427. async function injectRendererQueuedPromptForE2E(
  428. taskId: string,
  429. content: string,
  430. ): Promise<RendererQueueInjectionResult & { promptId: string }> {
  431. const result = (await browser.execute(
  432. (taskIdArg, contentArg) => {
  433. type RendererTaskMeta = {
  434. taskId?: string;
  435. workspaceIdentity?: string;
  436. workspacePath?: string;
  437. };
  438. type RendererWorkspace = {
  439. activeTaskId?: string | null;
  440. optimisticTaskListByTaskId?: Record<string, RendererTaskMeta>;
  441. taskListCache?: RendererTaskMeta[];
  442. };
  443. type RendererStore = {
  444. getState?: () => {
  445. enqueueTaskQueuedPrompt?: (
  446. workspacePath: string,
  447. taskId: string,
  448. prompt: {
  449. content: string;
  450. id: string;
  451. kind: "text";
  452. prompt: string;
  453. timestamp: number;
  454. },
  455. workspaceIdentity?: string,
  456. ) => void;
  457. setTaskStopRequested?: (
  458. workspacePath: string,
  459. taskId: string,
  460. requested: boolean,
  461. workspaceIdentity?: string,
  462. ) => void;
  463. workspaces?: Record<string, RendererWorkspace>;
  464. };
  465. };
  466. const storeApi = (
  467. window as Window & { __zcodeSessionStoreE2E?: RendererStore }
  468. ).__zcodeSessionStoreE2E;
  469. const state = storeApi?.getState?.();
  470. if (!state?.enqueueTaskQueuedPrompt || !state.setTaskStopRequested) {
  471. return { ok: false, reason: "store-api-missing" };
  472. }
  473. const workspaceEntry = Object.entries(state.workspaces ?? {}).find(
  474. ([, workspace]) =>
  475. workspace.activeTaskId === taskIdArg ||
  476. Boolean(workspace.optimisticTaskListByTaskId?.[taskIdArg]) ||
  477. Boolean(
  478. workspace.taskListCache?.some((task) => task.taskId === taskIdArg),
  479. ),
  480. );
  481. if (!workspaceEntry) {
  482. return { ok: false, reason: "task-workspace-not-found" };
  483. }
  484. const [workspaceKey, workspace] = workspaceEntry;
  485. const task =
  486. workspace.optimisticTaskListByTaskId?.[taskIdArg] ??
  487. workspace.taskListCache?.find((item) => item.taskId === taskIdArg);
  488. const workspacePath = task?.workspacePath ?? workspaceKey;
  489. const workspaceIdentity = task?.workspaceIdentity;
  490. const promptId = `queued-e2e-fork-goal-${Date.now()}-${Math.random()
  491. .toString(36)
  492. .slice(2, 6)}`;
  493. state.enqueueTaskQueuedPrompt(
  494. workspacePath,
  495. taskIdArg,
  496. {
  497. content: contentArg,
  498. id: promptId,
  499. kind: "text",
  500. prompt: contentArg,
  501. timestamp: Date.now(),
  502. },
  503. workspaceIdentity,
  504. );
  505. state.setTaskStopRequested(
  506. workspacePath,
  507. taskIdArg,
  508. false,
  509. workspaceIdentity,
  510. );
  511. return {
  512. ok: true,
  513. promptId,
  514. workspaceIdentity: workspaceIdentity ?? null,
  515. workspacePath,
  516. };
  517. },
  518. taskId,
  519. content,
  520. )) as RendererQueueInjectionResult;
  521. if (!result.ok || !result.promptId) {
  522. throw new Error(
  523. `fork goal queue 注入失败: ${JSON.stringify(result)}`,
  524. );
  525. }
  526. return result as RendererQueueInjectionResult & { promptId: string };
  527. }
  528. function readSessionTargetForE2E(
  529. sessionId: string,
  530. ): { objective: string; status: string } | null {
  531. const dbPath = join(homedir(), ".zcode", "cli", "db", "db.sqlite");
  532. const db = new DatabaseSync(dbPath);
  533. try {
  534. return (
  535. (db
  536. .prepare(
  537. "select objective, status from session_target where session_id = ?",
  538. )
  539. .get(sessionId) as { objective: string; status: string } | undefined) ??
  540. null
  541. );
  542. } finally {
  543. db.close();
  544. }
  545. }
  546. function buildReplyPrompt(marker: string): string {
  547. return `${marker}: Reply with exactly "${E2E_REPLY_TOKEN}" and no other text.`;
  548. }
  549. async function waitForAssistantMessageIdAfterUser(
  550. userMarker: string,
  551. assistantText: string,
  552. ): Promise<string> {
  553. let latestMessages: Awaited<ReturnType<typeof getMessages>> = [];
  554. let matchedId: string | null = null;
  555. await browser.waitUntil(
  556. async () => {
  557. latestMessages = await getMessages();
  558. const userIndex = findLastMessageIndex(latestMessages, "user", userMarker);
  559. if (userIndex < 0) {
  560. return false;
  561. }
  562. const assistant = latestMessages
  563. .slice(userIndex + 1)
  564. .find(
  565. (message) =>
  566. message.role === "assistant" &&
  567. message.text.includes(assistantText) &&
  568. isStableMessageId(message.id),
  569. );
  570. matchedId = assistant?.id ?? null;
  571. return Boolean(matchedId);
  572. },
  573. {
  574. timeout: 90000,
  575. timeoutMsg: `没有找到 ${userMarker} 之后包含 ${assistantText} 的 assistant 消息; latest=${JSON.stringify(
  576. latestMessages,
  577. )}`,
  578. },
  579. );
  580. if (!matchedId) {
  581. throw new Error(`assistant message id 缺失: ${userMarker}`);
  582. }
  583. return matchedId;
  584. }
  585. function isStableMessageId(messageId: string | null): messageId is string {
  586. // 修复原因:流式过程中 assistant DOM 会先使用 stream-* 临时 id。
  587. // fork 按钮绑定完成后落库的 msg_* 稳定 id,过早返回会导致按钮查找失败。
  588. return Boolean(messageId?.startsWith("msg_"));
  589. }
  590. async function waitForVisibleUserMessagesNotContaining(text: string) {
  591. let latestMessages: Awaited<ReturnType<typeof getMessages>> = [];
  592. await browser.waitUntil(
  593. async () => {
  594. latestMessages = await getMessages("user");
  595. return !latestMessages.some((message) => message.text.includes(text));
  596. },
  597. {
  598. timeout: 30000,
  599. timeoutMsg: `可见 user 消息仍包含 ${text}; latest=${JSON.stringify(
  600. latestMessages,
  601. )}`,
  602. },
  603. );
  604. }
  605. function findLastMessageIndex(
  606. messages: Awaited<ReturnType<typeof getMessages>>,
  607. role: string,
  608. text: string,
  609. ) {
  610. for (let index = messages.length - 1; index >= 0; index -= 1) {
  611. const message = messages[index];
  612. if (message?.role === role && message.text.includes(text)) {
  613. return index;
  614. }
  615. }
  616. return -1;
  617. }
  618. async function waitForForkButtonForAssistantMessageId(messageId: string) {
  619. let latestSummary = "null";
  620. await browser.waitUntil(
  621. async () => {
  622. const latest = await getForkButtonForAssistantMessageId(messageId);
  623. latestSummary = JSON.stringify(latest);
  624. return latest.exists && !latest.disabled && !latest.ariaDisabled;
  625. },
  626. {
  627. timeout: 30000,
  628. timeoutMsg: `assistant 消息没有出现可用 fork 按钮: ${messageId}; latest=${JSON.stringify(
  629. latestSummary,
  630. )}`,
  631. },
  632. );
  633. const button = await getForkButtonForAssistantMessageId(messageId);
  634. if (!button.exists || button.disabled || button.ariaDisabled) {
  635. throw new Error(
  636. `assistant fork 按钮在等待后仍不可用: ${messageId}; latest=${JSON.stringify(
  637. button,
  638. )}`,
  639. );
  640. }
  641. return button;
  642. }
  643. function getForkButtonForAssistantMessageId(messageId: string): Promise<{
  644. ariaDisabled: boolean;
  645. disabled: boolean;
  646. exists: boolean;
  647. testId: string;
  648. }> {
  649. return browser.execute(
  650. (forkButtonPrefix, targetMessageId) => {
  651. const button = Array.from(
  652. document.querySelectorAll<HTMLButtonElement>(
  653. `[data-testid^="${forkButtonPrefix}-"]`,
  654. ),
  655. ).find(
  656. (candidate) =>
  657. candidate.getAttribute("data-message-id") === targetMessageId,
  658. );
  659. return {
  660. ariaDisabled: button?.getAttribute("aria-disabled") === "true",
  661. disabled: button?.disabled ?? false,
  662. exists: Boolean(button),
  663. testId:
  664. button?.getAttribute("data-testid") ??
  665. `${forkButtonPrefix}-${targetMessageId}`,
  666. };
  667. },
  668. TID_CHAT_MESSAGE_FORK_BUTTON,
  669. messageId,
  670. );
  671. }
  672. async function clickForkButtonForAssistantMessageId(messageId: string) {
  673. const button = await waitForForkButtonForAssistantMessageId(messageId);
  674. await clickTestIdByDom(button.testId, {
  675. timeout: 15000,
  676. timeoutMsg: `assistant fork 按钮不可点击: ${messageId}`,
  677. });
  678. }