conversation-session-fork.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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_V4_FORK } from "@zcode/shared/test-ids";
  6. import { clearAppData, DEFAULT_WORKSPACE, clickTestIdByDom } from "#e2e/helpers/desktop-app";
  7. import {
  8. waitForUpstreamNetworkCapture,
  9. waitForUpstreamNetworkRequestStarted,
  10. } from "#e2e/helpers/upstream-capture";
  11. import {
  12. E2E_REPLY_TOKEN,
  13. clickV4Stop,
  14. assertVisibleV4UserMessagesNotContaining,
  15. getV4ConversationState,
  16. getV4Messages,
  17. prepareV4ConversationE2E,
  18. selectV4TaskById,
  19. sendV4Prompt,
  20. waitForV4AssistantMessageContaining,
  21. waitForV4ConversationState,
  22. waitForV4ComposerText,
  23. waitForV4UserMessageContaining,
  24. waitForLatestV4CommandAck,
  25. } from "#e2e/helpers/v4-conversation";
  26. import { forkV4AssistantContaining as clickForkButtonForAssistantContaining } from "#e2e/helpers/v4-message-actions";
  27. import { getV4MessageAction, waitForV4MessageAction } from "#e2e/helpers/v4-message-actions";
  28. import { editV4UserMessageContaining as editUserMessageContaining } from "#e2e/helpers/v4-message-actions";
  29. import {
  30. getQueueItems,
  31. waitForQueueContaining,
  32. waitForQueueCount,
  33. } from "#e2e/helpers/conversation-session-queue";
  34. import { restartIntoWorkspacePreservingProfile } from "#e2e/helpers/model-provider-restart-runtime";
  35. describe("会话区 Fork E2E", () => {
  36. after(async () => {
  37. await browser.electron.restoreAllMocks();
  38. await clearAppData();
  39. });
  40. it("完成后的 assistant 消息应允许 fork 并切换到派生 session", async function () {
  41. this.timeout(150000);
  42. await prepareV4ConversationE2E();
  43. const runId = Date.now();
  44. // 修复原因:FK/E01 只验证 completed assistant 的 fork 边界。
  45. // 这里混入 Read 工具会触发 auto compact,让基础 fork case 被 compact 稳定性干扰。
  46. const prompt = buildReplyPrompt(`E2E_FORK_SOURCE_${runId}`);
  47. await sendV4Prompt(prompt);
  48. await waitForV4ComposerText("", "首发后输入框没有清空");
  49. await waitForV4UserMessageContaining(prompt);
  50. const sourceSnapshot = await waitForV4ConversationState(
  51. (snapshot) => Boolean(snapshot.sessionId || snapshot.taskId),
  52. "首发后 chat-view 没有回填 session/task id",
  53. 30000,
  54. );
  55. await waitForUpstreamNetworkCapture(`E2E_FORK_SOURCE_${runId}`);
  56. await waitForV4AssistantMessageContaining(E2E_REPLY_TOKEN);
  57. await waitForV4ConversationState(
  58. (snapshot) =>
  59. snapshot.state === "idle" && isRuntimeCompleted(snapshot) && snapshot.queueCount === 0,
  60. "fork 前会话没有回到 idle",
  61. 90000,
  62. );
  63. const userForkButton = await getV4MessageAction("user", "fork", prompt);
  64. expect(userForkButton?.exists).not.toBe(true);
  65. const forkButton = await waitForV4MessageAction("assistant", "fork", E2E_REPLY_TOKEN);
  66. expect(forkButton.exists).toBe(true);
  67. expect(forkButton.disabled || forkButton.ariaDisabled).toBe(false);
  68. await clickForkButtonForAssistantContaining(E2E_REPLY_TOKEN);
  69. const forkedSnapshot = await waitForV4ConversationState(
  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 waitForV4UserMessageContaining(prompt);
  82. await waitForV4AssistantMessageContaining(E2E_REPLY_TOKEN);
  83. const finalSnapshot = await getV4ConversationState();
  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 prepareV4ConversationE2E();
  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 sendV4Prompt(seedPrompt);
  97. await waitForV4ComposerText("", "goal fork seed 发送后输入框没有清空");
  98. await waitForV4UserMessageContaining(seedPrompt);
  99. await waitForUpstreamNetworkCapture(seedMarker);
  100. await waitForV4AssistantMessageContaining(E2E_REPLY_TOKEN);
  101. const seededSnapshot = await waitForV4ConversationState(
  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. // V4 由 CLI snapshot 持有 target;旧 renderer store 注入不会进入真实 fork 状态。
  113. // 在进程退出屏障后写入夹具,再冷启动读取,避免退出持久化覆盖新 target。
  114. await restartIntoWorkspacePreservingProfile(DEFAULT_WORKSPACE, {
  115. afterElectronProcessExit: () =>
  116. setSessionTargetForE2E(sourceSessionId ?? "", goalObjective, "paused"),
  117. });
  118. await selectV4TaskById(sourceSessionId ?? "");
  119. await assertVisibleV4UserMessagesNotContaining(goalMarker);
  120. const sourceMarker = `E2E_FORK_GOAL_SOURCE_${runId}`;
  121. const sourcePrompt = buildReplyPrompt(sourceMarker);
  122. await sendV4Prompt(sourcePrompt);
  123. await waitForV4ComposerText("", "goal fork source 发送后输入框没有清空");
  124. await waitForV4UserMessageContaining(sourcePrompt);
  125. await waitForUpstreamNetworkCapture(sourceMarker);
  126. const sourceAssistantMessageId = await waitForAssistantMessageIdAfterUser(
  127. sourceMarker,
  128. E2E_REPLY_TOKEN,
  129. );
  130. await waitForV4ConversationState(
  131. (snapshot) =>
  132. getSnapshotSessionId(snapshot) === sourceSessionId &&
  133. snapshot.state === "idle" &&
  134. isRuntimeCompleted(snapshot) &&
  135. snapshot.queueCount === 0 &&
  136. snapshot.targetObjective?.includes(goalMarker) === true &&
  137. snapshot.targetStatus === "paused",
  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 runningMarker = `E2E_FORK_GOAL_RUNNING_${runId}`;
  144. await sendV4Prompt(buildReplyPrompt(runningMarker));
  145. // 这里需要保持运行态来建立真实队列;等待响应结束会耗尽受控流窗口。
  146. await waitForUpstreamNetworkRequestStarted(runningMarker);
  147. await waitForV4ConversationState(
  148. // V4 的 Stop projection 与已捕获请求证明运行态;旧 store 的 activeInputId 不再同步。
  149. (snapshot) => snapshot.state === "streaming",
  150. "创建父队列前主轮没有处于实际运行中",
  151. 30000,
  152. );
  153. await sendV4Prompt(queuedPrompt);
  154. await waitForQueueContaining(queuedMarker);
  155. const parentQueue = await waitForQueueCount(1);
  156. const parentQueueItemId = parentQueue[0]?.id;
  157. expect(parentQueueItemId).toBeTruthy();
  158. await clickV4Stop();
  159. await waitForV4ConversationState(
  160. (snapshot) =>
  161. getSnapshotSessionId(snapshot) === sourceSessionId &&
  162. snapshot.state === "idle" &&
  163. snapshot.activeInputId === null &&
  164. snapshot.queueCount === 1 &&
  165. !snapshot.stopRequested &&
  166. snapshot.targetObjective?.includes(goalMarker) === true &&
  167. snapshot.targetStatus === "paused",
  168. "停止后父会话没有保留目标和 held queue",
  169. 30000,
  170. );
  171. const parentTargetBeforeFork = readSessionTargetForE2E(sourceSessionId ?? "");
  172. expect(parentTargetBeforeFork?.objective).toContain(goalMarker);
  173. expect(parentTargetBeforeFork?.status).toBe("paused");
  174. const forkButton = await waitForForkButtonForAssistantMessageId(sourceAssistantMessageId);
  175. expect(forkButton.exists).toBe(true);
  176. expect(forkButton.disabled || forkButton.ariaDisabled).toBe(false);
  177. await clickForkButtonForAssistantMessageId(sourceAssistantMessageId);
  178. const forkedSnapshot = await waitForV4ConversationState(
  179. (snapshot) =>
  180. Boolean(snapshot.sessionId || snapshot.taskId) &&
  181. (snapshot.sessionId || snapshot.taskId) !== sourceSessionId &&
  182. snapshot.queueCount === 0 &&
  183. snapshot.targetObjective?.includes(goalMarker) === true &&
  184. snapshot.targetStatus === "paused",
  185. "goal 父会话 fork 后 child 没有继承 target 或 queue 不为空",
  186. 30000,
  187. );
  188. expect(forkedSnapshot.sessionId || forkedSnapshot.taskId).not.toBe(sourceSessionId);
  189. expect(forkedSnapshot.queueCount).toBe(0);
  190. expect(await getQueueItems()).toHaveLength(0);
  191. expect(forkedSnapshot.targetObjective).toContain(goalMarker);
  192. expect(forkedSnapshot.targetStatus).toBe("paused");
  193. await selectV4TaskById(sourceSessionId ?? "");
  194. await waitForV4ConversationState(
  195. (snapshot) =>
  196. getSnapshotSessionId(snapshot) === sourceSessionId &&
  197. snapshot.targetObjective?.includes(goalMarker) === true &&
  198. snapshot.targetStatus === "paused",
  199. "切回父 session 后 goal target 没有保留",
  200. 30000,
  201. );
  202. const restoredParentQueue = await waitForQueueCount(1);
  203. expect(restoredParentQueue[0]?.id).toBe(parentQueueItemId);
  204. expect(restoredParentQueue[0]?.content).toContain(queuedMarker);
  205. });
  206. it("edit 重跑后的 assistant fork 应只复制编辑后的 active branch", async function () {
  207. this.timeout(180000);
  208. await prepareV4ConversationE2E();
  209. const runId = Date.now();
  210. const originalMarker = `E2E_FORK_EDIT_OLD_${runId}`;
  211. const originalPrompt = buildReplyPrompt(originalMarker);
  212. await sendV4Prompt(originalPrompt);
  213. await waitForV4ComposerText("", "fork edit 原始消息发送后输入框没有清空");
  214. await waitForV4UserMessageContaining(originalPrompt);
  215. const originalSourceSnapshot = await waitForV4ConversationState(
  216. (snapshot) => Boolean(snapshot.sessionId || snapshot.taskId),
  217. "fork edit 原始消息发送后没有绑定 source session",
  218. 30000,
  219. );
  220. const sourceSessionId = getSnapshotSessionId(originalSourceSnapshot);
  221. expect(sourceSessionId).toBeTruthy();
  222. await waitForUpstreamNetworkCapture(originalMarker);
  223. await waitForV4AssistantMessageContaining(E2E_REPLY_TOKEN);
  224. await waitForV4ConversationState(
  225. (snapshot) =>
  226. getSnapshotSessionId(snapshot) === sourceSessionId &&
  227. snapshot.state === "idle" &&
  228. isRuntimeCompleted(snapshot) &&
  229. snapshot.queueCount === 0,
  230. "fork edit 原始消息完成后没有回到 idle",
  231. 90000,
  232. );
  233. await waitForV4UserMessageContaining(originalPrompt);
  234. const editedMarker = `E2E_FORK_EDIT_ACTIVE_${runId}`;
  235. const editedPrompt = buildReplyPrompt(editedMarker);
  236. await editUserMessageContaining(originalMarker, editedPrompt);
  237. // 失败现场已点击提交且 RPC 返回,但没有 Provider 请求;先保留命令拒绝原因,
  238. // 避免仅等待网络后把 admission 失败误报为缺失模型响应,不重发编辑命令。
  239. const editAck = await waitForLatestV4CommandAck("editUserQuery");
  240. if (editAck.status !== "accepted") {
  241. throw new Error(`fork edit 提交未接纳: ${JSON.stringify(editAck)}`);
  242. }
  243. await waitForUpstreamNetworkCapture(editedMarker);
  244. await waitForV4UserMessageContaining(editedPrompt);
  245. await waitForV4ConversationState(
  246. (snapshot) =>
  247. getSnapshotSessionId(snapshot) === sourceSessionId &&
  248. snapshot.state === "idle" &&
  249. isRuntimeCompleted(snapshot) &&
  250. snapshot.queueCount === 0 &&
  251. Boolean(snapshot.sessionId || snapshot.taskId),
  252. "fork edit 重跑完成后没有回到可 fork 状态",
  253. 90000,
  254. );
  255. await waitForVisibleUserMessagesNotContaining(originalMarker);
  256. const assistantMessageId = await waitForAssistantMessageIdAfterUser(
  257. editedMarker,
  258. E2E_REPLY_TOKEN,
  259. );
  260. await clickForkButtonForAssistantMessageId(assistantMessageId);
  261. const forkedSnapshot = await waitForV4ConversationState(
  262. (snapshot) =>
  263. Boolean(snapshot.sessionId || snapshot.taskId) &&
  264. getSnapshotSessionId(snapshot) !== sourceSessionId &&
  265. snapshot.queueCount === 0,
  266. "edit 后 fork 没有切换到空队列 child session",
  267. 30000,
  268. );
  269. expect(getSnapshotSessionId(forkedSnapshot)).not.toBe(sourceSessionId);
  270. await waitForV4UserMessageContaining(editedPrompt);
  271. await assertVisibleV4UserMessagesNotContaining(originalMarker);
  272. expect((await getV4Messages()).map((message) => message.text).join("\n")).toContain(
  273. editedMarker,
  274. );
  275. });
  276. });
  277. type ChatSnapshot = Awaited<ReturnType<typeof getV4ConversationState>>;
  278. function getSnapshotSessionId(snapshot: ChatSnapshot): string | null {
  279. return snapshot.sessionId || snapshot.taskId;
  280. }
  281. function isRuntimeCompleted(snapshot: ChatSnapshot): boolean {
  282. return snapshot.state === "idle";
  283. }
  284. async function setSessionTargetForE2E(
  285. sessionId: string,
  286. objective: string,
  287. status: "active" | "paused" | "budget_limited" | "complete",
  288. ) {
  289. const dbPath = join(homedir(), ".zcode", "cli", "db", "db.sqlite");
  290. const db = new DatabaseSync(dbPath);
  291. const now = Date.now();
  292. const targetId = `target_e2e_${randomUUID()}`;
  293. try {
  294. // 修复原因:FK/E07 只需要“父 session 已有 target”这个前置状态。
  295. // 通过聊天输入发送 /goal 会额外制造一条可见 user query,污染 fork 历史边界。
  296. // 这里不能写 active target;UI 会把 active target 当作自动续跑中的目标,
  297. // 普通 source prompt 会进入未来队列而不是启动父 session active turn。
  298. db.prepare(
  299. `
  300. insert into session_target (
  301. session_id, target_id, objective, summary_title, status, token_budget, tokens_used, time_used_seconds, time_created, time_updated
  302. ) values (?, ?, ?, null, ?, null, 0, 0, ?, ?)
  303. on conflict(session_id) do update set
  304. target_id = excluded.target_id,
  305. objective = excluded.objective,
  306. summary_title = excluded.summary_title,
  307. status = excluded.status,
  308. token_budget = excluded.token_budget,
  309. tokens_used = excluded.tokens_used,
  310. time_used_seconds = excluded.time_used_seconds,
  311. active_input_id = null,
  312. active_run_started_at = null,
  313. active_run_last_seen_at = null,
  314. time_created = excluded.time_created,
  315. time_updated = excluded.time_updated
  316. `,
  317. ).run(sessionId, targetId, objective, status, now, now);
  318. db.prepare("update session set time_updated = max(time_updated, ?) where id = ?").run(
  319. now,
  320. sessionId,
  321. );
  322. } finally {
  323. db.close();
  324. }
  325. }
  326. function readSessionTargetForE2E(sessionId: string): { objective: string; status: string } | null {
  327. const dbPath = join(homedir(), ".zcode", "cli", "db", "db.sqlite");
  328. const db = new DatabaseSync(dbPath);
  329. try {
  330. return (
  331. (db
  332. .prepare("select objective, status from session_target where session_id = ?")
  333. .get(sessionId) as { objective: string; status: string } | undefined) ?? null
  334. );
  335. } finally {
  336. db.close();
  337. }
  338. }
  339. function buildReplyPrompt(marker: string): string {
  340. return `${marker}: Reply with exactly "${E2E_REPLY_TOKEN}" and no other text.`;
  341. }
  342. async function waitForAssistantMessageIdAfterUser(
  343. userMarker: string,
  344. assistantText: string,
  345. ): Promise<string> {
  346. let latestMessages: Awaited<ReturnType<typeof getV4Messages>> = [];
  347. let matchedId: string | null = null;
  348. await browser.waitUntil(
  349. async () => {
  350. latestMessages = await getV4Messages();
  351. const userIndex = findLastMessageIndex(latestMessages, "user", userMarker);
  352. if (userIndex < 0) {
  353. return false;
  354. }
  355. const assistant = latestMessages
  356. .slice(userIndex + 1)
  357. .find(
  358. (message) =>
  359. message.role === "assistant" &&
  360. message.text.includes(assistantText) &&
  361. Boolean(message.id),
  362. );
  363. matchedId = assistant?.id ?? null;
  364. if (!matchedId) return false;
  365. const action = await getForkButtonForAssistantMessageId(matchedId);
  366. return action.exists && !action.disabled && !action.ariaDisabled;
  367. },
  368. {
  369. timeout: 90000,
  370. timeoutMsg: `没有找到 ${userMarker} 之后包含 ${assistantText} 的 assistant 消息; latest=${JSON.stringify(
  371. latestMessages,
  372. )}`,
  373. },
  374. );
  375. if (!matchedId) {
  376. throw new Error(`assistant message id 缺失: ${userMarker}`);
  377. }
  378. return matchedId;
  379. }
  380. async function waitForVisibleUserMessagesNotContaining(text: string) {
  381. let latestMessages: Awaited<ReturnType<typeof getV4Messages>> = [];
  382. await browser.waitUntil(
  383. async () => {
  384. latestMessages = await getV4Messages("user");
  385. return !latestMessages.some((message) => message.text.includes(text));
  386. },
  387. {
  388. timeout: 30000,
  389. timeoutMsg: `可见 user 消息仍包含 ${text}; latest=${JSON.stringify(latestMessages)}`,
  390. },
  391. );
  392. }
  393. function findLastMessageIndex(
  394. messages: Awaited<ReturnType<typeof getV4Messages>>,
  395. role: string,
  396. text: string,
  397. ) {
  398. for (let index = messages.length - 1; index >= 0; index -= 1) {
  399. const message = messages[index];
  400. if (message?.role === role && message.text.includes(text)) {
  401. return index;
  402. }
  403. }
  404. return -1;
  405. }
  406. async function waitForForkButtonForAssistantMessageId(messageId: string) {
  407. let latestSummary = "null";
  408. await browser.waitUntil(
  409. async () => {
  410. const latest = await getForkButtonForAssistantMessageId(messageId);
  411. latestSummary = JSON.stringify(latest);
  412. return latest.exists && !latest.disabled && !latest.ariaDisabled;
  413. },
  414. {
  415. timeout: 30000,
  416. timeoutMsg: `assistant 消息没有出现可用 fork 按钮: ${messageId}; latest=${JSON.stringify(
  417. latestSummary,
  418. )}`,
  419. },
  420. );
  421. const button = await getForkButtonForAssistantMessageId(messageId);
  422. if (!button.exists || button.disabled || button.ariaDisabled) {
  423. throw new Error(
  424. `assistant fork 按钮在等待后仍不可用: ${messageId}; latest=${JSON.stringify(button)}`,
  425. );
  426. }
  427. return button;
  428. }
  429. function getForkButtonForAssistantMessageId(messageId: string): Promise<{
  430. ariaDisabled: boolean;
  431. disabled: boolean;
  432. exists: boolean;
  433. testId: string;
  434. }> {
  435. return browser.execute(
  436. (forkButtonPrefix, targetMessageId) => {
  437. // V4 使用 canonical rowId 与 v4-fork 按钮;旧 msg_* 和 data-message-id 会漏掉已完成消息。
  438. const button = document.querySelector<HTMLButtonElement>(
  439. `[data-testid="v4-session-pane-workspace-main"] [data-testid="${forkButtonPrefix}-${targetMessageId}"]`,
  440. );
  441. return {
  442. ariaDisabled: button?.getAttribute("aria-disabled") === "true",
  443. disabled: button?.disabled ?? false,
  444. exists: Boolean(button),
  445. testId: button?.getAttribute("data-testid") ?? `${forkButtonPrefix}-${targetMessageId}`,
  446. };
  447. },
  448. TID_V4_FORK,
  449. messageId,
  450. );
  451. }
  452. async function clickForkButtonForAssistantMessageId(messageId: string) {
  453. const button = await waitForForkButtonForAssistantMessageId(messageId);
  454. await clickTestIdByDom(button.testId, {
  455. timeout: 15000,
  456. timeoutMsg: `assistant fork 按钮不可点击: ${messageId}`,
  457. });
  458. }