conversation-session-r3-compact-goal.test.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. import { openStatusCapsule } from "#e2e/helpers/status-capsule";
  2. import { mkdir, writeFile } from "node:fs/promises";
  3. import { resolve } from "node:path";
  4. import { TID_V4_COMPOSER_INPUT } from "@zcode/shared/test-ids";
  5. import { clearAppData, setInputValueByTestIdDom } from "#e2e/helpers/desktop-app";
  6. import {
  7. getUpstreamRequestRecordCount,
  8. waitForUpstreamRequest,
  9. } from "#e2e/helpers/conversation-session-network";
  10. import {
  11. connectSSHWorkspaceAndSendFirstTurn,
  12. prepareSSHLifecycle,
  13. type SSHLifecycleProvider,
  14. } from "#e2e/helpers/ssh-remote-lifecycle";
  15. import { readRemoteTabSnapshot, runSSHCommand } from "#e2e/helpers/ssh-remote-p0";
  16. import {
  17. clickV4Send,
  18. getV4ConversationState,
  19. getV4GoalProjection,
  20. getV4Messages,
  21. sendV4PromptAndWaitAccepted,
  22. waitForV4AssistantMessageContaining,
  23. waitForV4CompactMarker,
  24. waitForV4ConversationState,
  25. waitForV4Pane,
  26. } from "#e2e/helpers/v4-conversation";
  27. const CASE_MARKER = "E2E_R3_COMPACT_GOAL";
  28. const artifactDir = resolve(process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/r3-compact-goal");
  29. async function clickGoalAction(action: "pause" | "resume"): Promise<boolean> {
  30. await openStatusCapsule("goal", 15000);
  31. await browser.waitUntil(
  32. () =>
  33. browser.execute(
  34. (name) =>
  35. Boolean(
  36. document.querySelector<HTMLButtonElement>(`[data-goal-action="${name}"]`)?.disabled ===
  37. false,
  38. ),
  39. action,
  40. ),
  41. { timeout: 15_000, timeoutMsg: `${CASE_MARKER}: goal ${action} 按钮不可用` },
  42. );
  43. return browser.execute((name) => {
  44. const button = document.querySelector<HTMLButtonElement>(`[data-goal-action="${name}"]`);
  45. if (!button || button.disabled) return false;
  46. button.click();
  47. return true;
  48. }, action);
  49. }
  50. describe(`${CASE_MARKER}: 远端 session 的手动 compact 与 goal 暂停/继续/结束`, () => {
  51. let provider: SSHLifecycleProvider | null = null;
  52. const facts: Record<string, unknown> = {};
  53. after(async () => {
  54. await mkdir(artifactDir, { recursive: true });
  55. await writeFile(resolve(artifactDir, "compact-goal.json"), JSON.stringify(facts, null, 2));
  56. await provider?.tunnel.close().catch(() => undefined);
  57. provider = null;
  58. await browser.electron.restoreAllMocks();
  59. await clearAppData();
  60. });
  61. it("R3A-TASK-05 /compact 在远端执行且历史被摘要替代、后续回合不丢队列;/goal 建立 → pause → resume → 结束回合,active-work 状态正确、无重复 continuation", async function () {
  62. this.timeout(30 * 60_000);
  63. const prepared = await prepareSSHLifecycle(CASE_MARKER, {
  64. apiType: "anthropic-messages",
  65. tunnelUsername: "tunnel",
  66. });
  67. provider = prepared.provider;
  68. const [workspaceA] = prepared.config.workspacePaths;
  69. const taskA = await connectSSHWorkspaceAndSendFirstTurn({
  70. caseMarker: CASE_MARKER,
  71. config: prepared.config,
  72. label: "A",
  73. provider,
  74. workspacePath: workspaceA,
  75. });
  76. // 手动 compact:/compact → 远端发起 compaction 模型请求(CRITICAL: Respond with TEXT ONLY)→ manual/success marker。
  77. const compactStart = await getUpstreamRequestRecordCount();
  78. await setInputValueByTestIdDom(TID_V4_COMPOSER_INPUT, "/compact", {
  79. timeout: 15_000,
  80. timeoutMsg: `${CASE_MARKER}: composer 输入框没有出现`,
  81. });
  82. await clickV4Send();
  83. await waitForUpstreamRequest(
  84. { includes: ["CRITICAL: Respond with TEXT ONLY", taskA.firstPrompt] },
  85. `${CASE_MARKER}: compaction 请求没有到达回放`,
  86. 90_000,
  87. { afterIndex: compactStart - 1 },
  88. );
  89. await waitForV4CompactMarker({ origin: "manual", status: "success" }, 120_000);
  90. await waitForV4ConversationState(
  91. (s) => s.taskId === taskA.taskId && s.state === "idle",
  92. `${CASE_MARKER}: compact 后没有回到 idle`,
  93. 60_000,
  94. );
  95. const compactRequests = (await getUpstreamRequestRecordCount()) - compactStart;
  96. facts.compact = { requestsDuringCompact: compactRequests };
  97. // compaction 期间允许 1~3 次模型请求(摘要 + 可能的记忆抽取/标题),但不得重复触发多次 compaction。
  98. expect(compactRequests).toBeGreaterThanOrEqual(1);
  99. expect(compactRequests).toBeLessThanOrEqual(3);
  100. // compact 后下一回合:请求体携带摘要(R3_COMPACT_SUMMARY)而不是原首发回复文本。
  101. const afterCompactStart = await getUpstreamRequestRecordCount();
  102. await sendV4PromptAndWaitAccepted(
  103. `${CASE_MARKER}_AFTER 请回复`,
  104. `${CASE_MARKER}_AFTER`,
  105. `${CASE_MARKER}: compact 后回合未被接受`,
  106. );
  107. await waitForUpstreamRequest(
  108. {
  109. lastUserMessageIncludes: [`${CASE_MARKER}_AFTER`],
  110. includes: ["R3_COMPACT_SUMMARY"],
  111. excludes: [taskA.firstReply],
  112. },
  113. `${CASE_MARKER}: compact 后请求没有携带摘要或仍含原始回复`,
  114. 90_000,
  115. { afterIndex: afterCompactStart - 1 },
  116. );
  117. await waitForV4AssistantMessageContaining("R3_COMPACT_GOAL_REPLY", 90_000);
  118. await waitForV4ConversationState(
  119. (s) => s.taskId === taskA.taskId && s.state === "idle",
  120. `${CASE_MARKER}: compact 后回合没有收口`,
  121. 90_000,
  122. );
  123. facts.afterCompactTurnUsesSummary = true;
  124. const remoteCompact = await runSSHCommand(
  125. prepared.config,
  126. 'F=$(ls -t ~/.zcode/cli/log/*.jsonl | head -n1); grep -c "compact" "$F" || true',
  127. );
  128. facts.remoteLogCompactMentions = Number.parseInt(remoteCompact.stdout.trim() || "0", 10);
  129. // goal:/goal → continuation 慢流(running)→ pause → resume → 慢流结束/verify。
  130. const goalStart = await getUpstreamRequestRecordCount();
  131. await setInputValueByTestIdDom(
  132. TID_V4_COMPOSER_INPUT,
  133. `/goal ${CASE_MARKER}_OBJECTIVE 完成远端目标`,
  134. { timeout: 15_000, timeoutMsg: `${CASE_MARKER}: composer 输入框没有出现` },
  135. );
  136. await clickV4Send();
  137. await browser.waitUntil(
  138. async () =>
  139. ((await getV4GoalProjection())?.objective ?? "").includes(`${CASE_MARKER}_OBJECTIVE`),
  140. {
  141. timeout: 60_000,
  142. timeoutMsg: `${CASE_MARKER}: goal 状态面板没有出现 objective`,
  143. },
  144. );
  145. const active = await getV4GoalProjection();
  146. facts.goalActive = active;
  147. expect(["active", "verifying"]).toContain(active?.status);
  148. await waitForUpstreamRequest(
  149. { includes: [`${CASE_MARKER}_OBJECTIVE`, "Continue working toward the active session goal"] },
  150. `${CASE_MARKER}: goal continuation 请求没有到达回放`,
  151. 90_000,
  152. { afterIndex: goalStart - 1 },
  153. );
  154. await waitForV4Pane(
  155. (s) => s.canStop,
  156. `${CASE_MARKER}: goal continuation 没有进入 running`,
  157. 60_000,
  158. );
  159. expect(await clickGoalAction("pause")).toBe(true);
  160. await browser.waitUntil(async () => (await getV4GoalProjection())?.status === "paused", {
  161. timeout: 30_000,
  162. timeoutMsg: `${CASE_MARKER}: pause 后目标没有进入 paused`,
  163. });
  164. const requestsAtPause = await getUpstreamRequestRecordCount();
  165. await browser.pause(8_000);
  166. const pausedState = await getV4ConversationState();
  167. facts.paused = {
  168. state: pausedState.state,
  169. requestsDuringPause: (await getUpstreamRequestRecordCount()) - requestsAtPause,
  170. };
  171. expect(facts.paused).toMatchObject({ requestsDuringPause: 0 });
  172. expect(await clickGoalAction("resume")).toBe(true);
  173. await browser.waitUntil(
  174. async () =>
  175. ["active", "verifying", "verified", "completed"].includes(
  176. (await getV4GoalProjection())?.status ?? "",
  177. ),
  178. { timeout: 60_000, timeoutMsg: `${CASE_MARKER}: resume 后目标没有恢复` },
  179. );
  180. facts.resumed = await getV4GoalProjection();
  181. // 慢流结束 → verify 请求 → 目标收口;期间 continuation 请求不得重复(≤2:resume 可能重新发起一次 continuation)。
  182. await waitForUpstreamRequest(
  183. { includes: [`${CASE_MARKER}_OBJECTIVE`, "Verify whether the active session goal"] },
  184. `${CASE_MARKER}: goal 恢复后没有产生验证请求`,
  185. 180_000,
  186. { afterIndex: goalStart - 1 },
  187. );
  188. // idle 也可能对应暂停或错误,必须同时证明目标确实完成。
  189. await browser.waitUntil(
  190. async () => ["verified", "completed"].includes((await getV4GoalProjection())?.status ?? ""),
  191. { timeout: 60_000, timeoutMsg: `${CASE_MARKER}: verifier 通过后目标没有完成` },
  192. );
  193. await waitForV4ConversationState(
  194. (s) => s.taskId === taskA.taskId && s.state === "idle",
  195. `${CASE_MARKER}: goal 回合没有收口`,
  196. 180_000,
  197. );
  198. const goalRequestsTotal = (await getUpstreamRequestRecordCount()) - goalStart;
  199. const finalGoal = await getV4GoalProjection();
  200. facts.goalEnd = { status: finalGoal?.status ?? null, requestsTotal: goalRequestsTotal };
  201. expect(goalRequestsTotal).toBeLessThanOrEqual(4);
  202. const messages = await getV4Messages("user");
  203. facts.userMessages = messages.map((m) => (m.text ?? "").slice(0, 50));
  204. expect((await readRemoteTabSnapshot(taskA.identity)).remoteSessionId).toBe(
  205. taskA.remoteSessionId,
  206. );
  207. });
  208. });