app-control-long-turn-retry.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. import { mkdir, writeFile } from "node:fs/promises";
  2. import { basename, dirname, join, resolve } from "node:path";
  3. import { isE2EHomeDirName } from "#e2e/helpers/e2e-runtime-paths";
  4. import { ServiceChannels } from "@zcode/shared";
  5. import type { ProjectTask, ProjectTree, VirtualProject } from "@zcode/services";
  6. import { clearAppData, DEFAULT_WORKSPACE } from "#e2e/helpers/desktop-app";
  7. import {
  8. buildReadonlyToolPrompt,
  9. ensureReadonlyToolFixtureFile,
  10. } from "#e2e/helpers/conversation-session-readonly-tool";
  11. import { restartIntoWorkspacePreservingProfile } from "#e2e/helpers/model-provider-restart-runtime";
  12. import { seedProviderReadinessHistoryFixture } from "#e2e/helpers/provider-readiness-history-fixture";
  13. import { startDraftFromProject } from "#e2e/helpers/project-sidebar";
  14. import {
  15. callHandoffHost,
  16. installHandoffRpcProbe,
  17. restoreHandoffProbes,
  18. } from "#e2e/helpers/remote-project-handoff-probe";
  19. import {
  20. readAppControlToolResult,
  21. type AppControlToolEvidence,
  22. } from "#e2e/helpers/app-control-evidence";
  23. import { waitForUpstreamNetworkCapture } from "#e2e/helpers/upstream-capture";
  24. import {
  25. approveV4Permission,
  26. prepareV4ConversationE2E,
  27. sendV4Prompt,
  28. waitForV4AssistantMessageContaining,
  29. waitForV4Pane,
  30. } from "#e2e/helpers/v4-conversation";
  31. // 会话工具设计 0.6 / 0.7 / 0.9:SCT05 创建重试换主目录、SCT06 长轮次 wait,
  32. // 以及 SCT02 读一个从未打开过的冷会话。
  33. // 目标会话一轮 70 个工具调用,超过快照尾窗 60 行,turnHeader 只在 owner 全量投影里。
  34. const CASE = "E2E_SCT06";
  35. const LONG_TURN_TOOL_CALLS = 70;
  36. const SECOND_ROOT = join(dirname(DEFAULT_WORKSPACE), "ZCodeProjectSCT06Second");
  37. // 冷会话:只写两个库,不启动运行态;读取前它从未被打开,CLI 侧没有 record。
  38. const COLD_SESSION = "session_e2e_sct06_cold";
  39. const COLD_TITLE = "E2E_SCT06_COLD_TITLE";
  40. const COLD_USER_TEXT = "E2E_SCT06_COLD_USER";
  41. const COLD_ASSISTANT_TEXT = "E2E_SCT06_COLD_ASSISTANT";
  42. const artifacts = process.env.ZCODE_E2E_ARTIFACT_DIR!;
  43. const tools: AppControlToolEvidence = {};
  44. const assertions: Record<string, unknown> = {};
  45. const evidence = { tools, assertions };
  46. interface SessionRef {
  47. kind: "app";
  48. sourceServerId: string;
  49. workspacePath: string;
  50. sessionId: string;
  51. workspaceIdentity?: string;
  52. project?: { kind: "app"; sourceServerId: string; projectId: string };
  53. }
  54. interface Operation {
  55. session: SessionRef;
  56. commandId: string;
  57. }
  58. interface Creation {
  59. creation: string;
  60. firstInput: string;
  61. delivery: string;
  62. session: SessionRef;
  63. operation: Operation;
  64. }
  65. interface Admission {
  66. admission: string;
  67. delivery: string;
  68. session: SessionRef;
  69. operation: Operation;
  70. }
  71. interface Wait {
  72. status: string;
  73. operations: Array<{ operation: Operation; status: string; attention?: { kind: string } }>;
  74. }
  75. async function action<T>(key: string, intent: string, approval = false): Promise<T> {
  76. await sendV4Prompt(
  77. `${CASE}_ACTION_${key.toUpperCase()}: ${intent} Use complete identities from the earlier actual tool results. Do not navigate or invent a result. After the tool returns reply exactly SCT06_${key.toUpperCase()}_RETURNED.`,
  78. );
  79. if (approval) expect(await approveV4Permission()).toBe(true);
  80. await waitForV4AssistantMessageContaining(`SCT06_${key.toUpperCase()}_RETURNED`, 120_000);
  81. await waitForV4Pane((value) => !value.canStop, `SCT06 ${key} caller has not completed`);
  82. const request = (await waitForUpstreamNetworkCapture(`toolu_sct06_${key}`)).requestJson;
  83. return readAppControlToolResult<T>(request, `toolu_sct06_${key}`, tools);
  84. }
  85. function operationStatus(result: Wait, operation: Operation) {
  86. return result.operations.find((value) => value.operation.commandId === operation.commandId);
  87. }
  88. async function readTree(): Promise<ProjectTree> {
  89. // 只读 Host 持久组织事实;被测动作全部来自真实 Agent 工具。
  90. return callHandoffHost<ProjectTree>(ServiceChannels.Project, "readTree", [{}]);
  91. }
  92. describe(`${CASE}: App session tools on a long turn and a retried creation`, () => {
  93. // 冷会话必须在 Host 启动前落盘,否则 Host 的 source snapshot 不含这一行。
  94. before(async () => {
  95. const home = process.env.ZCODE_E2E_HOME_DIR ?? "";
  96. if (!isE2EHomeDirName(basename(home))) throw new Error("需要隔离 E2E HOME");
  97. await restartIntoWorkspacePreservingProfile(DEFAULT_WORKSPACE, {
  98. afterElectronProcessExit: async () => {
  99. await seedProviderReadinessHistoryFixture({
  100. cliEntryPoint: resolve("../../apps/zcode-cli/packages/cli/dist/zcode.cjs"),
  101. e2eHomeDir: home,
  102. workspacePath: DEFAULT_WORKSPACE,
  103. history: {
  104. sessionId: COLD_SESSION,
  105. title: COLD_TITLE,
  106. userText: COLD_USER_TEXT,
  107. assistantText: COLD_ASSISTANT_TEXT,
  108. modelId: "deepseek-v4-flash",
  109. runtimeProviderId: "e2e-upstream",
  110. taskProviderId: "glm",
  111. assistantInputTokens: 0,
  112. assistantOutputTokens: 0,
  113. },
  114. });
  115. },
  116. });
  117. });
  118. after(async () => {
  119. if (artifacts) {
  120. await mkdir(artifacts, { recursive: true });
  121. await writeFile(
  122. join(artifacts, "SCT06-long-turn-retry.json"),
  123. JSON.stringify(evidence, null, 2),
  124. );
  125. await browser.saveScreenshot(join(artifacts, "SCT06-desktop.png"));
  126. }
  127. await restoreHandoffProbes();
  128. await clearAppData();
  129. });
  130. it("reports long-turn outcomes past the snapshot tail and reuses the first creation on retry", async function () {
  131. this.timeout(900_000);
  132. await ensureReadonlyToolFixtureFile();
  133. await mkdir(SECOND_ROOT, { recursive: true });
  134. await prepareV4ConversationE2E();
  135. await startDraftFromProject(DEFAULT_WORKSPACE);
  136. await sendV4Prompt(buildReadonlyToolPrompt(`${CASE}_CALLER`));
  137. await waitForV4AssistantMessageContaining("upstream-e2e-ok", 90_000);
  138. await waitForV4Pane(
  139. (value) => !value.canStop && value.sessionId !== "draft",
  140. "SCT06 caller missing",
  141. );
  142. await installHandoffRpcProbe();
  143. const projects = await action<{
  144. projects: Array<{ project: NonNullable<SessionRef["project"]> }>;
  145. }>("projects", "Call ListProjects with query=ZCodeProject.");
  146. expect(projects.projects).toHaveLength(1);
  147. const project = projects.projects[0]!.project;
  148. const created = await action<Creation>(
  149. "create",
  150. "Call CreateSession in that project with prompt E2E_SCT06_LONG_TARGET (step marker E2E_SCT06_CREATE; do not pass requestId).",
  151. true,
  152. );
  153. expect(created).toMatchObject({ creation: "created", firstInput: "accepted" });
  154. expect(created.session.workspacePath).toBe(DEFAULT_WORKSPACE);
  155. // 有界等待:观察期间 header 的增量照常到达,作为对照。
  156. const live = await action<Wait>(
  157. "completed",
  158. "Call WaitSessions for the create operation, mode=all, timeoutMs=60000.",
  159. );
  160. expect(operationStatus(live, created.operation)?.status).toBe("completed");
  161. // 回合已结束且 header 已滚出尾窗:只读当前结果,必须仍为 completed,不能是 unknown。
  162. const settled = await action<Wait>(
  163. "settled",
  164. "Call WaitSessions for the same create operation, mode=all, timeoutMs=0.",
  165. );
  166. expect(settled.status).toBe("completed");
  167. expect(operationStatus(settled, created.operation)?.status).toBe("completed");
  168. assertions.longTurnCompletion = { live, settled, toolCalls: LONG_TURN_TOOL_CALLS };
  169. // 测试准备:把项目主目录换成第二个 root,再用首次回执里的 requestId(retryOf)重试创建。
  170. const before = (await readTree()).projects.find((value) => value.id === project.projectId)!;
  171. await callHandoffHost<VirtualProject>(ServiceChannels.Project, "saveProject", [
  172. { id: before.id, roots: [DEFAULT_WORKSPACE, SECOND_ROOT], primaryRoot: SECOND_ROOT },
  173. ]);
  174. const moved = (await readTree()).projects.find((value) => value.id === project.projectId)!;
  175. expect(moved.roots.find((root) => root.isPrimary)?.rootPath).toBe(SECOND_ROOT);
  176. const retried = await action<Creation>(
  177. "retry",
  178. "Call CreateSession again with exactly the same project and prompt E2E_SCT06_LONG_TARGET (step marker E2E_SCT06_CREATE), passing retryOf set to the requestId from the first CreateSession result.",
  179. true,
  180. );
  181. expect(retried.creation).toBe("created");
  182. expect(retried.session).toEqual(created.session);
  183. expect(retried.operation).toEqual(created.operation);
  184. const tree = await readTree();
  185. expect(tree.tasks.filter((task) => task.workspacePath === SECOND_ROOT)).toHaveLength(0);
  186. assertions.retryReusesFirstCreation = { created, retried, primaryRoot: SECOND_ROOT };
  187. // 长回合后等审批:有界等待必须返回 needs_attention,不能一直报 running 到超时。
  188. const asked = await action<Admission>(
  189. "send",
  190. "Call SendToSession on the created session with prompt E2E_SCT06_LONG_ASK (step marker E2E_SCT06_ASK; do not pass requestId).",
  191. true,
  192. );
  193. expect(asked.session).toEqual(created.session);
  194. const attention = await action<Wait>(
  195. "attention",
  196. "Call WaitSessions for the send operation, mode=all, timeoutMs=20000.",
  197. );
  198. expect(attention.status).toBe("completed");
  199. expect(operationStatus(attention, asked.operation)).toMatchObject({
  200. status: "needs_attention",
  201. attention: { kind: "approval" },
  202. });
  203. assertions.longTurnAttention = { asked, attention };
  204. // 规格 0.9:读一个从未打开过的冷会话。summary 一直可用;messages 原先失败于 App control failed。
  205. const coldBefore = (await readTree()).tasks.find((task) => task.taskId === COLD_SESSION);
  206. expect(coldBefore).toBeDefined();
  207. const coldSummary = await action<{ summary: { title: string; status: string } }>(
  208. "cold_summary",
  209. `Call ReadSession with sessionId=${COLD_SESSION} and view=summary.`,
  210. );
  211. expect(coldSummary.summary.title).toBe(COLD_TITLE);
  212. const coldMessages = await action<{
  213. session: SessionRef;
  214. messages: Array<{ id: string; role: string; text: string }>;
  215. }>(
  216. "cold_messages",
  217. `Call ReadSession with sessionId=${COLD_SESSION}, view=messages, limit=20.`,
  218. );
  219. expect(coldMessages.session.sessionId).toBe(COLD_SESSION);
  220. expect(coldMessages.messages.map((message) => message.role)).toEqual(["user", "assistant"]);
  221. expect(coldMessages.messages[0]!.text).toContain(COLD_USER_TEXT);
  222. expect(coldMessages.messages[1]!.text).toContain(COLD_ASSISTANT_TEXT);
  223. // 读取不恢复 runtime、不认领 owner、不标已读:Host 的组织事实必须逐字不变。
  224. const coldAfter = (await readTree()).tasks.find((task) => task.taskId === COLD_SESSION);
  225. expect(coldAfter).toEqual(coldBefore);
  226. const coldSummaryAfter = await action<{ summary: { status: string; executionId?: string } }>(
  227. "cold_idle",
  228. `Call ReadSession with sessionId=${COLD_SESSION} and view=summary.`,
  229. );
  230. expect(coldSummaryAfter.summary.executionId).toBeUndefined();
  231. assertions.coldSessionRead = {
  232. coldSummary,
  233. coldMessages,
  234. taskUnchanged: coldAfter as ProjectTask | undefined,
  235. };
  236. });
  237. });