conversation-session-r3-docker-transport.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. import { selectTaskOrganizeMode } from "#e2e/helpers/workspace-agent-warmup";
  2. import {
  3. openRemoteProjectSelection,
  4. waitForRemoteTab,
  5. waitForSSHDirectoryStep,
  6. selectSSHRemoteDirectory,
  7. } from "#e2e/helpers/ssh-remote-p0";
  8. import {
  9. disconnectRemoteSource,
  10. reconnectRemoteProject,
  11. } from "#e2e/helpers/remote-project-actions";
  12. import { execFile } from "node:child_process";
  13. import { mkdir, writeFile } from "node:fs/promises";
  14. import { resolve } from "node:path";
  15. import { promisify } from "node:util";
  16. import { parseRemoteWorkspaceIdentity } from "@zcode/shared";
  17. import { TID_DOCKER_CONTAINER_INPUT, TID_REMOTE_KIND_DOCKER } from "@zcode/shared/test-ids";
  18. import { clearAppData, clickTestIdByDom } from "#e2e/helpers/desktop-app";
  19. import {
  20. selectUpstreamProviderModelById,
  21. selectUpstreamThoughtLevelValue,
  22. } from "#e2e/helpers/upstream-provider";
  23. import {
  24. getUpstreamRequestRecordCount,
  25. countUpstreamRequests,
  26. waitForUpstreamRequest,
  27. } from "#e2e/helpers/conversation-session-network";
  28. import {
  29. createSSHLifecycleProvider,
  30. SSH_LIFECYCLE_MODEL_ID,
  31. SSH_LIFECYCLE_THOUGHT_LEVEL,
  32. type SSHLifecycleProvider,
  33. } from "#e2e/helpers/ssh-remote-lifecycle";
  34. import {
  35. clickLastEnabledSSHDialogButton,
  36. readHostProcesses,
  37. readSSHRuntimeConfig,
  38. readRemoteTabSnapshot,
  39. } from "#e2e/helpers/ssh-remote-p0";
  40. import {
  41. getV4Messages,
  42. prepareV4ConversationE2E,
  43. sendV4PromptAndWaitAccepted,
  44. waitForV4ConversationState,
  45. } from "#e2e/helpers/v4-conversation";
  46. const CASE_MARKER = "E2E_R3_DOCKER_TRANSPORT";
  47. const artifactDir = resolve(
  48. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/r3-docker-transport",
  49. );
  50. const run = promisify(execFile);
  51. async function dockerSh(container: string, command: string): Promise<string> {
  52. try {
  53. return (await run("docker", ["exec", container, "sh", "-lc", command], { maxBuffer: 1 << 22 }))
  54. .stdout;
  55. } catch (error) {
  56. return `ERR:${(error as { stderr?: string }).stderr ?? String(error)}`;
  57. }
  58. }
  59. async function connectDockerTargetUntilReady(
  60. container: string,
  61. workspacePath = process.env.ZCODE_E2E_SSH_WORKSPACE_PATH,
  62. ): Promise<{ identity: string; remoteSessionId: string; kind: string | null }> {
  63. // Composer 的旧远程入口已退役;与 SSH 一样从项目创建进入 transport 选择。
  64. await openRemoteProjectSelection();
  65. await clickTestIdByDom(TID_REMOTE_KIND_DOCKER, {
  66. timeout: 30_000,
  67. timeoutMsg: `${CASE_MARKER}: 无法选择 Docker transport`,
  68. });
  69. const input = $(`[data-testid="${TID_DOCKER_CONTAINER_INPUT}"]`);
  70. await input.waitForDisplayed({ timeout: 30_000 });
  71. await input.setValue(container);
  72. await clickLastEnabledSSHDialogButton(CASE_MARKER);
  73. await waitForSSHDirectoryStep(CASE_MARKER);
  74. if (!workspacePath) throw new Error(`${CASE_MARKER}: 缺少 Docker 项目目录`);
  75. await selectSSHRemoteDirectory(workspacePath, CASE_MARKER);
  76. const tab = await waitForRemoteTab({ caseMarker: CASE_MARKER, expectedPath: workspacePath });
  77. return {
  78. identity: tab.workspaceIdentity!,
  79. remoteSessionId: tab.remoteSessionId!,
  80. kind: tab.remoteKind,
  81. };
  82. }
  83. describe(`${CASE_MARKER}: Desktop Docker transport 首装、首发与关闭重连`, () => {
  84. const facts: Record<string, unknown> = {};
  85. let provider: SSHLifecycleProvider | undefined;
  86. after(async () => {
  87. await mkdir(artifactDir, { recursive: true });
  88. await writeFile(resolve(artifactDir, "docker-transport.json"), JSON.stringify(facts, null, 2));
  89. await provider?.tunnel.close();
  90. await browser.electron.restoreAllMocks();
  91. await clearAppData();
  92. });
  93. it("R3A-TRN-01-UID 数字 UID 无 passwd 条目仍可首装并打开 Docker 项目", async function () {
  94. this.timeout(15 * 60_000);
  95. const container = `zcode-e2e-numeric-uid-${process.pid}`;
  96. const fixtureHome = "/tmp/zcode-uid-home";
  97. const workspacePath = `${fixtureHome}/project`;
  98. try {
  99. await run("docker", [
  100. "run",
  101. "--detach",
  102. "--name",
  103. container,
  104. "--user",
  105. "10001:10001",
  106. "--env",
  107. `HOME=${fixtureHome}`,
  108. "--workdir",
  109. "/tmp",
  110. "node:22.16.0-bookworm-slim",
  111. "sh",
  112. "-c",
  113. `mkdir -p ${workspacePath} && exec sleep infinity`,
  114. ]);
  115. const readIdentity = async () =>
  116. JSON.parse(
  117. (
  118. await run("docker", [
  119. "exec",
  120. container,
  121. "node",
  122. "-e",
  123. `const { readFile } = require("node:fs/promises");
  124. readFile("/etc/passwd", "utf8").then(passwd => console.log(JSON.stringify({
  125. uid: process.geteuid(),
  126. hasPasswd: passwd.split("\\n").some(line => line.split(":")[2] === String(process.geteuid()))
  127. }))).catch(error => { console.error(error); process.exitCode = 1; });`,
  128. ])
  129. ).stdout,
  130. ) as { uid: number; hasPasswd: boolean };
  131. expect(await readIdentity()).toEqual({ uid: 10001, hasPasswd: false });
  132. await prepareV4ConversationE2E({ skipProvider: true });
  133. const ready = await connectDockerTargetUntilReady(container, workspacePath);
  134. expect(ready.kind).toBe("docker");
  135. const identity = parseRemoteWorkspaceIdentity(ready.identity);
  136. expect(identity?.kind).toBe("server");
  137. const result = await run("docker", [
  138. "exec",
  139. container,
  140. "node",
  141. "-e",
  142. `const { readFile } = require("node:fs/promises");
  143. async function main() {
  144. const root = process.env.HOME + "/.zcode/server/run/";
  145. const status = JSON.parse(await readFile(root + "status.json", "utf8"));
  146. const token = (await readFile(root + "ingress-token", "utf8")).trim();
  147. const response = await fetch("http://127.0.0.1:" + status.port + "/api/server-info", {
  148. headers: { authorization: "Bearer " + token }
  149. });
  150. const info = await response.json();
  151. console.log(JSON.stringify({ state: status.state, serverId: info.serverId, identity: info.identity }));
  152. }
  153. main().catch(error => { console.error(error); process.exitCode = 1; });`,
  154. ]);
  155. const serverInfo = JSON.parse(result.stdout) as {
  156. state: string;
  157. serverId: string;
  158. identity: { osUser: string };
  159. };
  160. expect(serverInfo.state).toBe("ready");
  161. expect(serverInfo.identity.osUser).toBe("uid:10001");
  162. expect(serverInfo.serverId).toBe(identity?.sourceServerId);
  163. expect(await readIdentity()).toEqual({ uid: 10001, hasPasswd: false });
  164. facts.numericUid = { ready, serverInfo };
  165. await mkdir(artifactDir, { recursive: true });
  166. await browser.saveScreenshot(resolve(artifactDir, "numeric-uid-project.png"));
  167. } finally {
  168. try {
  169. await clearAppData();
  170. } finally {
  171. await run("docker", ["rm", "--force", container]).catch(() => undefined);
  172. }
  173. }
  174. });
  175. it("R3A-TRN-01 独立 Docker 容器:Docker 入口安装、Provisioning、真实首发、断开后重连", async function () {
  176. this.timeout(30 * 60_000);
  177. // 本机 runner 已把同一 SSH / Docker 目标写入 ZCODE_E2E_SSH_CONTAINER;旧用例只读服务器队列
  178. // 的别名,尚未执行产品操作就报缺变量。保留显式目标优先,否则复用 runner 创建的隔离容器。
  179. const container =
  180. process.env.R3_DOCKER_TARGET?.trim() || process.env.ZCODE_E2E_SSH_CONTAINER?.trim();
  181. if (!container) throw new Error(`${CASE_MARKER}: 需设置 R3_DOCKER_TARGET`);
  182. facts.container = container;
  183. facts.containerUser = (
  184. await dockerSh(
  185. container,
  186. "id -un; test -e ~/.zcode/server/current.json && echo installed || echo fresh",
  187. )
  188. ).trim();
  189. await prepareV4ConversationE2E({ skipProvider: true });
  190. const initialHosts = await readHostProcesses();
  191. // 旧用例误把容器不可达宿主回放当成必须使用个人账号;专用隧道只转发模型 HTTP,产品控制面仍走 Docker。
  192. provider = await createSSHLifecycleProvider(readSSHRuntimeConfig(CASE_MARKER), CASE_MARKER, {
  193. tunnelUsername: "tunnel",
  194. });
  195. const ready = await connectDockerTargetUntilReady(container);
  196. facts.ready = ready;
  197. expect(ready.kind).toBe("docker");
  198. const parsed = parseRemoteWorkspaceIdentity(ready.identity);
  199. expect(parsed?.kind).toBe("server");
  200. // 0911 修复:远端 provider_config.json 已迁移新 schema(providerRules[].providerName),
  201. // 旧字段 "label" 不存在 → grep 无匹配 exit 1 且 stderr 为空 → dockerSh 返回裸 "ERR:",
  202. // 掩盖了前两段(archiveSha256/state:ready)的真实输出。改为 grep providerName,
  203. // 且每段 grep 兜底 || true,保证命令 exit 0 时 stdout 不被丢弃。
  204. const installState = await dockerSh(
  205. container,
  206. 'grep -o \'"archiveSha256": *"[0-9a-f]*"\' ~/.zcode/server/current.json || true; cat ~/.zcode/server/run/status.json | tr -d "\\n "; echo; grep -o "\\"providerName\\": *\\"[^\\"]*\\"" ~/.zcode/v2/provider_config.json || true',
  207. );
  208. facts.remoteAfterConnect = installState.split("\n").filter(Boolean).slice(0, 8);
  209. expect(installState).toContain("archiveSha256");
  210. expect(installState).toContain('"state":"ready"');
  211. expect(installState).toContain(provider.name);
  212. expect(await readHostProcesses()).toEqual(initialHosts);
  213. // 容器内真实 Agent 经 Provider HTTP 隧道首发,响应由本例 fixture 提供。
  214. await selectUpstreamProviderModelById(SSH_LIFECYCLE_MODEL_ID, {
  215. includePlainModelFallback: false,
  216. providerId: provider.id,
  217. providerName: provider.name,
  218. });
  219. await selectUpstreamThoughtLevelValue(SSH_LIFECYCLE_THOUGHT_LEVEL);
  220. // 复用 Docker 项目草稿,保留当前机器与模型归属。
  221. const replayBefore = await getUpstreamRequestRecordCount();
  222. await sendV4PromptAndWaitAccepted(
  223. `${CASE_MARKER}_FIRST 请只回复 DOCKER1`,
  224. `${CASE_MARKER}_FIRST`,
  225. `${CASE_MARKER}: 首发未被接受`,
  226. );
  227. const running = await waitForV4ConversationState(
  228. (s) => Boolean(s.taskId && s.taskId !== "draft"),
  229. `${CASE_MARKER}: 首发没有产生 task`,
  230. 60_000,
  231. );
  232. await waitForV4ConversationState(
  233. (s) => s.taskId === running.taskId && s.state === "idle" && s.queueCount === 0,
  234. `${CASE_MARKER}: 真实首发没有收口`,
  235. 180_000,
  236. );
  237. // 用户 prompt 本身含 DOCKER1,不能用整个页面文本作为真实回复证据。
  238. await browser.waitUntil(
  239. async () =>
  240. (await getV4Messages("assistant")).some((message) =>
  241. /DOCKER\s*1/u.test(message.text ?? ""),
  242. ),
  243. { timeout: 30_000, timeoutMsg: `${CASE_MARKER}: assistant 未返回 DOCKER1` },
  244. );
  245. const text = (await getV4Messages("assistant")).map((message) => message.text ?? "").join("\n");
  246. expect(text).toMatch(/DOCKER\s*1/u);
  247. const requestMatch = {
  248. lastUserMessageIncludes: [`${CASE_MARKER}_FIRST`],
  249. excludes: ["Generate a concise title"],
  250. };
  251. await waitForUpstreamRequest(requestMatch, `${CASE_MARKER}: 容器首发未到达回放服务`, 30_000, {
  252. afterIndex: replayBefore - 1,
  253. });
  254. expect(await countUpstreamRequests(requestMatch, { afterIndex: replayBefore - 1 })).toBe(1);
  255. const remoteRequests = await dockerSh(
  256. container,
  257. 'F=$(ls -t ~/.zcode/cli/log/*.jsonl | head -n1); grep -c "model.network.completed" "$F" || true; grep -o "\\"baseURL\\":\\"[^\\"]*\\"" "$F" | sort | uniq -c',
  258. );
  259. facts.remoteModelNetwork = remoteRequests.trim().split("\n");
  260. expect(remoteRequests).toContain(provider.tunnel.baseURL);
  261. // 关闭重连:设备断开 → 重连 → 新 remoteSessionId、Host 不变、容器内 daemon 仍在。
  262. const sourceId = parsed?.sourceServerId;
  263. await selectTaskOrganizeMode(["项目", "Project"]);
  264. await disconnectRemoteSource(sourceId!, CASE_MARKER, { workspaceIdentities: [ready.identity] });
  265. const daemonAfterDisconnect = await dockerSh(
  266. container,
  267. 'cat ~/.zcode/server/run/status.json | tr -d "\\n " | cut -c1-120',
  268. );
  269. expect(daemonAfterDisconnect).toContain('"state":"ready"');
  270. await reconnectRemoteProject(ready.identity, CASE_MARKER);
  271. let reconnected: string | null = null;
  272. await browser.waitUntil(
  273. async () => {
  274. const snapshot = await readRemoteTabSnapshot(ready.identity).catch(() => null);
  275. if (snapshot?.remoteSessionId && snapshot.remoteSessionId !== ready.remoteSessionId) {
  276. reconnected = snapshot.remoteSessionId;
  277. return true;
  278. }
  279. return false;
  280. },
  281. { timeout: 180_000, interval: 1000, timeoutMsg: `${CASE_MARKER}: Docker 目标重连没有换代` },
  282. );
  283. facts.reconnected = { before: ready.remoteSessionId, after: reconnected };
  284. expect(await readHostProcesses()).toEqual(initialHosts);
  285. });
  286. });