conversation-session-r3-transport-loss.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. import { execFile } from "node:child_process";
  2. import { mkdir, writeFile } from "node:fs/promises";
  3. import { waitForPermissionInteractionId } from "#e2e/helpers/permission-interaction-id";
  4. import { readRemoteToolExecutionEvents } from "#e2e/helpers/remote-tool-execution-evidence";
  5. import { resolve } from "node:path";
  6. import { promisify } from "node:util";
  7. import { clearAppData } from "#e2e/helpers/desktop-app";
  8. import {
  9. getUpstreamRequestRecordCount,
  10. waitForUpstreamRequest,
  11. } from "#e2e/helpers/conversation-session-network";
  12. import {
  13. connectSSHWorkspaceAndSendFirstTurn,
  14. prepareSSHLifecycle,
  15. readRemoteCoreIdentity,
  16. readTaskRowInProject,
  17. sendSSHFollowTurn,
  18. type SSHLifecycleProvider,
  19. type SSHLifecycleTask,
  20. } from "#e2e/helpers/ssh-remote-lifecycle";
  21. import {
  22. readHostProcesses,
  23. readRemoteTabSnapshot,
  24. runSSHCommand,
  25. waitForRemoteTab,
  26. type SSHConnectionConfig,
  27. } from "#e2e/helpers/ssh-remote-p0";
  28. import {
  29. approveV4Permission,
  30. getV4PaneSnapshot,
  31. hasV4PermissionDialog,
  32. selectV4TaskById,
  33. sendV4Prompt,
  34. waitForV4ConversationState,
  35. waitForV4Pane,
  36. waitForV4PermissionDialogInComposerDock,
  37. waitForV4TimelineContaining,
  38. } from "#e2e/helpers/v4-conversation";
  39. const CASE_MARKER = "E2E_R3_TRANSPORT_LOSS";
  40. const artifactDir = resolve(
  41. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/r3-transport-loss",
  42. );
  43. const REMOTE_PERMISSION_DIR = "/home/dev/r3-workspace-a/.zcode-e2e/r3-transport-loss";
  44. const REMOTE_PERMISSION_FILE = `${REMOTE_PERMISSION_DIR}/permission-output.txt`;
  45. const PERMISSION_EXECUTION = { toolCallId: "toolu_r3_task_permission", toolName: "Write" };
  46. const run = promisify(execFile);
  47. /**
  48. * 只切断 Desktop(用户 dev)的 SSH 会话:模型回放反向隧道由独立用户 tunnel 承载,必须保留,
  49. * 否则远端 Agent 的模型请求会随之失败,无法区分"传输中断"与"模型不可达"。
  50. */
  51. async function severDesktopSshSessions(container: string): Promise<string> {
  52. const script = [
  53. "target_uid=$(id -u dev); killed=''",
  54. 'for d in /proc/[0-9]*; do p=${d#/proc/}; [ "$p" = 1 ] && continue',
  55. "c=$(tr '\\0' ' ' < \"$d/cmdline\" 2>/dev/null) || continue; case \"$c\" in *sshd*) ;; *) continue;; esac",
  56. 'uid=$(awk \'/^Uid:/ {print $2}\' "$d/status"); [ "$uid" = "$target_uid" ] || continue',
  57. 'parent=$(awk \'{print $4}\' "$d/stat"); kill -9 "$p" 2>/dev/null && killed="$killed $p"',
  58. '[ "$parent" != 1 ] && kill -9 "$parent" 2>/dev/null && killed="$killed $parent"; done',
  59. "echo $killed",
  60. ].join("; ");
  61. const result = await run("docker", ["exec", container, "sh", "-c", script]);
  62. return result.stdout.trim().split(/\s+/u).filter(Boolean).join(",");
  63. }
  64. async function waitForSessionRegeneration(
  65. identity: string,
  66. previous: string,
  67. label: string,
  68. ): Promise<string> {
  69. let latest: string | null = null;
  70. await browser.waitUntil(
  71. async () => {
  72. const snapshot = await readRemoteTabSnapshot(identity).catch(() => null);
  73. if (snapshot?.remoteSessionId && snapshot.remoteSessionId !== previous) {
  74. latest = snapshot.remoteSessionId;
  75. return true;
  76. }
  77. return false;
  78. },
  79. {
  80. interval: 1000,
  81. timeout: 120_000,
  82. timeoutMsg: `${CASE_MARKER}: workspace ${label} 传输中断后没有自动换代恢复`,
  83. },
  84. );
  85. return latest!;
  86. }
  87. async function remoteAgentAlive(config: SSHConnectionConfig, workspacePath: string) {
  88. // 模板字符串里不能直接写 ${d#/proc/};用 basename 取 PID。
  89. const script = [
  90. "r=none",
  91. 'for d in /proc/[0-9]*; do c=$(tr "\\0" " " < "$d/cmdline" 2>/dev/null) || continue',
  92. // agent spawnArgs 恒为 "app-server --stdio"(3.12+ release 优先 glm 原生二进制,
  93. // 旧 dev 态才是 node zcode.cjs);按 args 匹配与实现形态无关。
  94. `case "$c" in *"app-server --stdi"[o]*) [ "$(readlink $d/cwd)" = "${workspacePath}" ] && r=$(basename "$d");; esac; done`,
  95. "echo $r",
  96. ].join("; ");
  97. const result = await runSSHCommand(config, script);
  98. return result.stdout.trim();
  99. }
  100. describe(`${CASE_MARKER}: 产品 SSH 连接中断期间远端任务继续,恢复后同组换代且阻塞权限保留`, () => {
  101. let provider: SSHLifecycleProvider | null = null;
  102. const facts: Record<string, unknown> = {};
  103. after(async () => {
  104. await mkdir(artifactDir, { recursive: true });
  105. await writeFile(resolve(artifactDir, "transport-loss.json"), JSON.stringify(facts, null, 2));
  106. await provider?.tunnel.close().catch(() => undefined);
  107. provider = null;
  108. await browser.electron.restoreAllMocks();
  109. await clearAppData();
  110. });
  111. it("R3A-REC-01/03/09 running 中断连→daemon 与任务继续、A/B 自动换代;permission 阻塞跨断连恢复同 ID 并只响应一次", async function () {
  112. this.timeout(35 * 60_000);
  113. const container = process.env.ZCODE_E2E_SSH_CONTAINER?.trim();
  114. if (!container) throw new Error(`${CASE_MARKER}: 缺少 ZCODE_E2E_SSH_CONTAINER`);
  115. const prepared = await prepareSSHLifecycle(CASE_MARKER, {
  116. apiType: "anthropic-messages",
  117. tunnelUsername: "tunnel",
  118. });
  119. provider = prepared.provider;
  120. const [workspaceA, workspaceB] = prepared.config.workspacePaths;
  121. await runSSHCommand(prepared.config, `rm -rf "${REMOTE_PERMISSION_DIR}"`);
  122. const taskA = await connectSSHWorkspaceAndSendFirstTurn({
  123. caseMarker: CASE_MARKER,
  124. config: prepared.config,
  125. label: "A",
  126. provider,
  127. workspacePath: workspaceA,
  128. });
  129. const taskB = await connectSSHWorkspaceAndSendFirstTurn({
  130. caseMarker: CASE_MARKER,
  131. config: prepared.config,
  132. label: "B",
  133. provider,
  134. workspacePath: workspaceB,
  135. });
  136. const hosts = await readHostProcesses();
  137. const core0 = await readRemoteCoreIdentity(prepared.config, CASE_MARKER);
  138. const agentB0 = await remoteAgentAlive(prepared.config, workspaceB);
  139. // REC-01:切回 A(当前 active 是后连接的 B),A 进入 45s controlled-stream running,随后切断 Desktop 的 SSH 会话。
  140. await selectV4TaskById(taskA.taskId, 30_000);
  141. await waitForRemoteTab({
  142. caseMarker: CASE_MARKER,
  143. expectedIdentity: taskA.identity,
  144. expectedPath: workspaceA,
  145. expectedRemoteSessionId: taskA.remoteSessionId,
  146. });
  147. await sendV4Prompt(`${CASE_MARKER}_SLOW 慢慢回答`);
  148. await waitForV4TimelineContaining("R3_TLOSS_STREAMING", 60_000);
  149. await waitForV4Pane(
  150. (s) => s.canStop && s.sessionId === taskA.taskId,
  151. "A 没有进入 running",
  152. 45_000,
  153. );
  154. const agentA0 = await remoteAgentAlive(prepared.config, workspaceA);
  155. facts.severedSessions = await severDesktopSshSessions(container);
  156. const regeneratedA = await waitForSessionRegeneration(
  157. taskA.identity,
  158. taskA.remoteSessionId,
  159. "A",
  160. );
  161. const regeneratedB = await waitForSessionRegeneration(
  162. taskB.identity,
  163. taskB.remoteSessionId,
  164. "B",
  165. );
  166. facts.regenerated = { A: regeneratedA, B: regeneratedB };
  167. // daemon/Agent 不受传输中断影响:Core 与两个 Agent 身份不变;任务未被判 failed,流在恢复后收口。
  168. const core1 = await readRemoteCoreIdentity(prepared.config, CASE_MARKER);
  169. expect(core1.pid).toBe(core0.pid);
  170. expect(core1.startTicks).toBe(core0.startTicks);
  171. expect(await remoteAgentAlive(prepared.config, workspaceA)).toBe(agentA0);
  172. expect(await remoteAgentAlive(prepared.config, workspaceB)).toBe(agentB0);
  173. expect(await readHostProcesses()).toEqual(hosts);
  174. await waitForV4ConversationState(
  175. (s) => s.taskId === taskA.taskId && s.state === "idle",
  176. `${CASE_MARKER}: 断连恢复后 A 的 running turn 没有正常收口`,
  177. 120_000,
  178. );
  179. const messages = await browser.execute(() => document.body?.innerText ?? "");
  180. expect(messages).not.toMatch(/任务失败|task failed/iu);
  181. facts.aTurnCompletedAfterReconnect = true;
  182. // B 在恢复后续发:历史保留、不含 A 的内容。
  183. const resumedB: SSHLifecycleTask = { ...taskB, remoteSessionId: regeneratedB };
  184. await readTaskRowInProject(resumedB, CASE_MARKER);
  185. await sendSSHFollowTurn(resumedB, CASE_MARKER, taskA.firstPrompt);
  186. // REC-09(Desktop 自动恢复路径):A 的 permission 阻塞在断连期间保留;恢复后同一请求只被响应一次。
  187. const resumedA: SSHLifecycleTask = { ...taskA, remoteSessionId: regeneratedA };
  188. await readTaskRowInProject(resumedA, CASE_MARKER);
  189. await selectV4TaskById(taskA.taskId, 30_000);
  190. await waitForRemoteTab({
  191. caseMarker: CASE_MARKER,
  192. expectedIdentity: taskA.identity,
  193. expectedPath: workspaceA,
  194. expectedRemoteSessionId: regeneratedA,
  195. });
  196. const permissionStart = await getUpstreamRequestRecordCount();
  197. await sendV4Prompt(`${CASE_MARKER}_PERMISSION 请写入文件 ${REMOTE_PERMISSION_FILE}`);
  198. await waitForUpstreamRequest(
  199. { lastUserMessageIncludes: [`${CASE_MARKER}_PERMISSION`] },
  200. `${CASE_MARKER}: 权限 turn 没有到达回放`,
  201. 60_000,
  202. { afterIndex: permissionStart - 1 },
  203. );
  204. const dock = await waitForV4PermissionDialogInComposerDock(60_000);
  205. expect(dock.inDock).toBe(true);
  206. const pendingId = await waitForPermissionInteractionId(CASE_MARKER);
  207. facts.permissionDialogIdBeforeSever = pendingId;
  208. facts.severedSessionsSecond = await severDesktopSshSessions(container);
  209. const regeneratedA2 = await waitForSessionRegeneration(
  210. taskA.identity,
  211. regeneratedA,
  212. "A(second)",
  213. );
  214. facts.regeneratedA2 = regeneratedA2;
  215. await browser.waitUntil(() => hasV4PermissionDialog(), {
  216. timeout: 60_000,
  217. timeoutMsg: `${CASE_MARKER}: 恢复后权限对话框没有重新出现`,
  218. });
  219. const restoredId = await waitForPermissionInteractionId(CASE_MARKER);
  220. facts.permissionDialogIdAfterRecover = restoredId;
  221. expect(restoredId).toBe(pendingId);
  222. expect(
  223. (
  224. await runSSHCommand(
  225. prepared.config,
  226. `test -f "${REMOTE_PERMISSION_FILE}" && echo exists || echo absent`,
  227. )
  228. ).stdout.trim(),
  229. ).toBe("absent");
  230. const executionQuery = { sessionId: taskA.taskId, toolName: PERMISSION_EXECUTION.toolName };
  231. expect(await readRemoteToolExecutionEvents(prepared.config, executionQuery)).toEqual([]);
  232. expect(await approveV4Permission()).toBe(true);
  233. await waitForV4TimelineContaining("R3_TLOSS_PERMISSION_DONE", 90_000);
  234. const written = await runSSHCommand(
  235. prepared.config,
  236. `cat "${REMOTE_PERMISSION_FILE}"; echo; grep -c R3_TLOSS_PERMISSION_RESULT "${REMOTE_PERMISSION_FILE}"`,
  237. );
  238. expect(written.stdout).toContain("R3_TLOSS_PERMISSION_RESULT");
  239. expect(written.stdout.trim().endsWith("1")).toBe(true);
  240. await browser.pause(2000);
  241. expect(await hasV4PermissionDialog()).toBe(false);
  242. facts.permissionResolvedOnce = written.stdout.trim();
  243. await waitForV4ConversationState(
  244. (s) => s.taskId === taskA.taskId && s.state === "idle",
  245. `${CASE_MARKER}: 权限 turn 没有回到 idle`,
  246. 60_000,
  247. );
  248. let executions = await readRemoteToolExecutionEvents(prepared.config, executionQuery);
  249. await browser.waitUntil(
  250. async () => {
  251. executions = await readRemoteToolExecutionEvents(prepared.config, executionQuery);
  252. facts.remoteToolExecutions = executions;
  253. return executions.some((event) => event.event === "tool.call.completed");
  254. },
  255. { timeout: 15_000, timeoutMsg: `${CASE_MARKER}: 远端 Write 缺少完成事件` },
  256. );
  257. expect(executions.filter((event) => event.event === "tool.call.started")).toHaveLength(1);
  258. expect(executions.filter((event) => event.event === "tool.call.completed")).toHaveLength(1);
  259. expect(executions.every((event) => event.toolCallId === PERMISSION_EXECUTION.toolCallId)).toBe(
  260. true,
  261. );
  262. expect((await getV4PaneSnapshot()).canStop).toBe(false);
  263. expect(await readHostProcesses()).toEqual(hosts);
  264. });
  265. });