conversation-session-remote-data-sync-runtime-usage.test.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. import { mkdir, readFile, writeFile } from "node:fs/promises";
  2. import { join, resolve } from "node:path";
  3. import {
  4. TID_SETTINGS_BACK_BUTTON,
  5. TID_SETTINGS_PAGE,
  6. TID_SETTINGS_SECTION_NAV,
  7. TID_TASK_SETTINGS_BUTTON,
  8. TID_V4_SESSION_PANE,
  9. testId,
  10. } from "@zcode/shared/test-ids";
  11. import {
  12. clearAppData,
  13. clickTestIdByDom,
  14. getE2EAppDataPaths,
  15. waitForTestIdByDom,
  16. } from "#e2e/helpers/desktop-app";
  17. import {
  18. addMarketplaceSourceThroughAgent,
  19. createPluginLifecycleFixture,
  20. installMarketplacePluginThroughAgent,
  21. PLUGIN_LIFECYCLE_MARKETPLACE_ID,
  22. PLUGIN_LIFECYCLE_MCP_TOOL_NAME,
  23. PLUGIN_LIFECYCLE_NAME,
  24. PLUGIN_LIFECYCLE_RUNTIME_MARKER,
  25. } from "#e2e/helpers/plugin-management-lifecycle";
  26. import {
  27. execInRemoteContainer,
  28. readRemoteDockerContainer,
  29. } from "#e2e/helpers/remote-docker-target";
  30. import { startDraftFromProject } from "#e2e/helpers/project-sidebar";
  31. import {
  32. selectUpstreamProviderModelById,
  33. selectUpstreamThoughtLevelValue,
  34. } from "#e2e/helpers/upstream-provider";
  35. import {
  36. countUpstreamRequests,
  37. getLatestUpstreamToolResultByToolCallId,
  38. getUpstreamRequestEvidence,
  39. getUpstreamRequestRecordCount,
  40. getUpstreamRequestToolNames,
  41. waitForUpstreamRequest,
  42. type UpstreamToolResultSnapshot,
  43. } from "#e2e/helpers/conversation-session-network";
  44. import { hasAssistantReplyForUserTurn } from "#e2e/helpers/conversation-turn-evidence";
  45. import {
  46. connectSSHWorkspaceAndSendFirstTurn,
  47. prepareSSHLifecycle,
  48. SSH_LIFECYCLE_MODEL_ID,
  49. SSH_LIFECYCLE_THOUGHT_LEVEL,
  50. SSH_LIFECYCLE_TURN_TIMEOUT_MS,
  51. type SSHLifecycleProvider,
  52. type SSHLifecycleTask,
  53. } from "#e2e/helpers/ssh-remote-lifecycle";
  54. import {
  55. prepareSSHConnectionPage,
  56. readRemoteTabSnapshot,
  57. waitForRemoteTab,
  58. type SSHRuntimeConfig,
  59. } from "#e2e/helpers/ssh-remote-p0";
  60. import {
  61. approveV4Permission,
  62. clickV4Stop,
  63. getV4Messages,
  64. hasV4PermissionDialog,
  65. selectV4TaskById,
  66. sendV4PromptAndWaitAccepted,
  67. V4_MAIN_PANE_ID,
  68. waitForV4ConversationState,
  69. } from "#e2e/helpers/v4-conversation";
  70. // DSYNC-17:推送内容在远端会话中的可用时机(docs/remote/data-sync.md「Seam ③:桌面 E2E」)。
  71. // 模型请求经 SSH 反向隧道回到本机回放(先例 WPL-011);用回放记录的模型请求判断远端 Agent 看到了什么,
  72. // 再实际调用 MCP 工具、Skill、Agent 检查工具结果;钩子在远端 $HOME 追加标记行。
  73. // 17-01 / 17-02 断言子智能体下一轮可用:远端 Host 与本机一样每轮提供子智能体配置(docs/subagent-runtime-refresh.md「远程 workspace」)。
  74. // 17-01 另断言推送钩子会重建推送前打开的新建任务页,与本机设置页保存钩子一致(docs/remote/data-sync.md「钩子」)。
  75. // 其他分类在现有 task 与推送前打开的新建任务页的期望未定义,只记录事实;17-03 断言新建 task 全部可用。
  76. const CASE_MARKER = "E2E_DSYNC_17_RUNTIME_USAGE";
  77. const TITLE_REQUEST = "Generate a concise title";
  78. const REMOTE_HOME = "/home/dev";
  79. const SKILL_NAME = "e2e-dsync-17-skill";
  80. const SKILL_DESC = "E2E_DSYNC_17_SKILL_DESC";
  81. const SKILL_BODY = "E2E_DSYNC_17_SKILL_BODY";
  82. const AGENT_NAME = "e2e-dsync-17-agent";
  83. const AGENT_DESC = "E2E_DSYNC_17_AGENT_DESC";
  84. const AGENT_BODY = "E2E_DSYNC_17_AGENT_BODY";
  85. const AGENT_DONE = "E2E_DSYNC_17_AGENT_DONE";
  86. const COMMAND_NAME = "e2e-dsync-17-cmd";
  87. const COMMAND_BODY = "E2E_DSYNC_17_COMMAND_BODY";
  88. const MCP_SERVER = "e2e-dsync-17-mcp";
  89. const MCP_TOOL = `mcp__${MCP_SERVER}__marker`;
  90. const MCP_RESULT = "E2E_DSYNC_17_MCP_RESULT";
  91. const INLINE_PLUGIN = "e2e-dsync-17-inline";
  92. const INLINE_TOOL = `mcp__plugin_${INLINE_PLUGIN}_rt__marker`;
  93. const INLINE_RESULT = "E2E_DSYNC_17_INLINE_RESULT";
  94. const MARKET_RESULT = `${PLUGIN_LIFECYCLE_RUNTIME_MARKER}_1.0.0`;
  95. // 钩子只写文件、不写 stdout:stdout 会进入上下文,改变后续请求。
  96. const HOOK_MARK = "E2E_DSYNC_17_HOOK";
  97. const HOOK_LOG = "e2e-dsync-17-hooks.log";
  98. const HOOK_COMMAND = `echo ${HOOK_MARK} >> "$HOME/${HOOK_LOG}"`;
  99. // 远端 Core 的子智能体监听在文件稳定 1000ms 后读取、再合并 300ms 才发布快照(docs/subagent-runtime-refresh.md)。
  100. // Core 的标准输出被 supervisor 丢弃,测试拿不到发布事件,只能从推送完成起等足规格的发布窗口再发下一轮。
  101. const SUBAGENT_PUBLISH_WINDOW_MS = 3_000;
  102. const artifactDir = resolve(
  103. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/dsync-17-runtime-usage",
  104. "dsync-17",
  105. );
  106. interface LocalCliConfig {
  107. [key: string]: unknown;
  108. mcp?: { [key: string]: unknown; servers?: Record<string, unknown> };
  109. plugins?: { [key: string]: unknown; dirs?: string[]; enabledPlugins?: Record<string, boolean> };
  110. }
  111. interface StageFacts {
  112. skillListed: boolean;
  113. subagentListed: boolean;
  114. mcpTool: boolean;
  115. inlinePluginTool: boolean;
  116. marketplacePluginTool: boolean;
  117. hookFired: boolean;
  118. }
  119. /** 内联的 stdio MCP 服务器:远端容器没有系统 node,靠 Agent 把自带 node 放进 MCP 子进程的 PATH。 */
  120. function mcpServerScript(serverName: string, result: string): string {
  121. return [
  122. 'const rl = require("node:readline").createInterface({ input: process.stdin });',
  123. 'const send = (message) => process.stdout.write(JSON.stringify(message) + "\\n");',
  124. 'rl.on("line", (line) => {',
  125. " let request;",
  126. " try { request = JSON.parse(line); } catch { return; }",
  127. ` if (request.method === "initialize") return send({ jsonrpc: "2.0", id: request.id, result: { protocolVersion: "2024-11-05", capabilities: { tools: {} }, serverInfo: { name: ${JSON.stringify(serverName)}, version: "1.0.0" } } });`,
  128. ' if (request.method === "tools/list") return send({ jsonrpc: "2.0", id: request.id, result: { tools: [{ name: "marker", description: "Return the data sync runtime marker", inputSchema: { type: "object", properties: {} } }] } });',
  129. ` if (request.method === "tools/call") return send({ jsonrpc: "2.0", id: request.id, result: { content: [{ type: "text", text: ${JSON.stringify(result)} }] } });`,
  130. ' if (request.id !== undefined) send({ jsonrpc: "2.0", id: request.id, result: {} });',
  131. "});",
  132. ].join("\n");
  133. }
  134. async function writeText(path: string, content: string): Promise<void> {
  135. await mkdir(join(path, ".."), { recursive: true });
  136. await writeFile(path, content);
  137. }
  138. /** 本机准备六类内容:技能、子智能体、命令、MCP、钩子、inline 插件;config.json 读改写,保留已有字段。 */
  139. async function writeLocalContent(homeDir: string): Promise<void> {
  140. const zcode = join(homeDir, ".zcode");
  141. await writeText(
  142. join(zcode, "skills", SKILL_NAME, "SKILL.md"),
  143. `---\nname: ${SKILL_NAME}\ndescription: ${SKILL_DESC} data sync runtime skill\n---\n\n${SKILL_BODY}\n`,
  144. );
  145. await writeText(
  146. join(zcode, "agents", `${AGENT_NAME}.md`),
  147. `---\nname: ${AGENT_NAME}\ndescription: ${AGENT_DESC} data sync runtime subagent\ntools: [Read]\n---\n${AGENT_BODY} Reply exactly as the task asks.\n`,
  148. );
  149. await writeText(
  150. join(zcode, "commands", `${COMMAND_NAME}.md`),
  151. `---\ndescription: data sync runtime command\n---\n${COMMAND_BODY} $ARGUMENTS\n`,
  152. );
  153. const inlineDir = join(zcode, "plugins", INLINE_PLUGIN);
  154. await writeText(
  155. join(inlineDir, ".zcode-plugin", "plugin.json"),
  156. `${JSON.stringify(
  157. {
  158. name: INLINE_PLUGIN,
  159. version: "1.0.0",
  160. description: "data sync runtime inline plugin",
  161. mcpServers: {
  162. rt: { type: "stdio", command: "node", args: ["${ZCODE_PLUGIN_ROOT}/server.cjs"] },
  163. },
  164. },
  165. null,
  166. 2,
  167. )}\n`,
  168. );
  169. await writeText(
  170. join(inlineDir, "server.cjs"),
  171. `${mcpServerScript(INLINE_PLUGIN, INLINE_RESULT)}\n`,
  172. );
  173. const configPath = join(zcode, "cli", "config.json");
  174. const config = await readFile(configPath, "utf-8")
  175. .then((text) => JSON.parse(text) as LocalCliConfig)
  176. .catch((): LocalCliConfig => ({}));
  177. const plugins = config.plugins ?? {};
  178. await writeText(
  179. configPath,
  180. `${JSON.stringify(
  181. {
  182. ...config,
  183. mcp: {
  184. ...config.mcp,
  185. servers: {
  186. ...config.mcp?.servers,
  187. [MCP_SERVER]: {
  188. command: "node",
  189. args: ["-e", mcpServerScript(MCP_SERVER, MCP_RESULT)],
  190. },
  191. },
  192. },
  193. hooks: {
  194. enabled: true,
  195. events: { UserPromptSubmit: [{ hooks: [{ type: "command", command: HOOK_COMMAND }] }] },
  196. },
  197. plugins: {
  198. ...plugins,
  199. dirs: [...(plugins.dirs ?? []), inlineDir],
  200. enabledPlugins: { ...plugins.enabledPlugins, [`${INLINE_PLUGIN}@inline`]: true },
  201. },
  202. },
  203. null,
  204. 2,
  205. )}\n`,
  206. );
  207. }
  208. /** 从子智能体推送完成起等足远端监听的发布窗口;已经过去的时间不再等待。 */
  209. async function waitForSubagentPublishWindow(pushedAt: number): Promise<void> {
  210. const remaining = SUBAGENT_PUBLISH_WINDOW_MS - (Date.now() - pushedAt);
  211. if (remaining > 0) await browser.pause(remaining);
  212. }
  213. /** 远端钩子标记行数:文件不存在时为 0。 */
  214. async function countRemoteHookLines(container: string): Promise<number> {
  215. const { stdout } = await execInRemoteContainer(container, [
  216. "sh",
  217. "-c",
  218. 'grep -c "$1" "$2" 2>/dev/null || true',
  219. "sh",
  220. HOOK_MARK,
  221. `${REMOTE_HOME}/${HOOK_LOG}`,
  222. ]);
  223. return Number.parseInt(stdout.trim() || "0", 10);
  224. }
  225. /** 本轮首个模型请求(排除标题请求):请求体文本与工具名。 */
  226. async function readTurnRequest(lastUserMarker: string, afterIndex: number) {
  227. const query = { lastUserMessageIncludes: [lastUserMarker], excludes: [TITLE_REQUEST] };
  228. const [request] = await getUpstreamRequestEvidence(query, { afterIndex });
  229. if (!request) throw new Error(`${CASE_MARKER}: 没有找到 ${lastUserMarker} 的模型请求`);
  230. return {
  231. body: JSON.stringify(request.requestJson),
  232. tools: await getUpstreamRequestToolNames(query),
  233. };
  234. }
  235. function factsFromRequest(
  236. request: { body: string; tools: string[] },
  237. hookFired: boolean,
  238. ): StageFacts {
  239. return {
  240. skillListed: request.body.includes(SKILL_DESC),
  241. subagentListed: request.body.includes(AGENT_DESC),
  242. mcpTool: request.tools.includes(MCP_TOOL),
  243. inlinePluginTool: request.tools.includes(INLINE_TOOL),
  244. marketplacePluginTool: request.tools.includes(PLUGIN_LIFECYCLE_MCP_TOOL_NAME),
  245. hookFired,
  246. };
  247. }
  248. async function waitForTurnReply(userMarker: string, reply: string): Promise<string> {
  249. await browser.waitUntil(
  250. async () => hasAssistantReplyForUserTurn(await getV4Messages(), userMarker, reply),
  251. {
  252. timeout: SSH_LIFECYCLE_TURN_TIMEOUT_MS,
  253. timeoutMsg: `${CASE_MARKER}: ${userMarker} 没有收到回复 ${reply}`,
  254. },
  255. );
  256. const state = await waitForV4ConversationState(
  257. (snapshot) =>
  258. Boolean(snapshot.taskId && snapshot.taskId !== "draft") &&
  259. snapshot.state === "idle" &&
  260. snapshot.queueCount === 0,
  261. `${CASE_MARKER}: ${userMarker} 完成后没有回到 idle`,
  262. SSH_LIFECYCLE_TURN_TIMEOUT_MS,
  263. );
  264. return state.taskId!;
  265. }
  266. /** 探针轮次:只回复固定文本,返回本轮模型请求里可见的推送内容与钩子是否执行。 */
  267. async function sendProbe(container: string, label: string) {
  268. const prompt = `${CASE_MARKER}_PROBE_${label}`;
  269. const reply = `DSYNC_17_PROBE_${label}_REPLY`;
  270. const hookBefore = await countRemoteHookLines(container);
  271. const start = await getUpstreamRequestRecordCount();
  272. await sendV4PromptAndWaitAccepted(
  273. `${prompt}: 只回复 ${reply}`,
  274. prompt,
  275. `${CASE_MARKER}: 探针 ${label} 没有被接受`,
  276. );
  277. await waitForUpstreamRequest(
  278. { lastUserMessageIncludes: [prompt] },
  279. `${CASE_MARKER}: 探针 ${label} 没有到达回放`,
  280. SSH_LIFECYCLE_TURN_TIMEOUT_MS,
  281. { afterIndex: start - 1 },
  282. );
  283. const taskId = await waitForTurnReply(prompt, reply);
  284. const request = await readTurnRequest(prompt, start - 1);
  285. const hookFired = (await countRemoteHookLines(container)) > hookBefore;
  286. return { taskId, facts: factsFromRequest(request, hookFired) };
  287. }
  288. /** 命令轮次:远端 CLI 展开 /命令 时,本轮请求含命令正文与参数。 */
  289. async function sendCommandProbe(label: string): Promise<boolean> {
  290. const args = `E2E_DSYNC_17_CMD_${label}`;
  291. const start = await getUpstreamRequestRecordCount();
  292. await sendV4PromptAndWaitAccepted(
  293. `/${COMMAND_NAME} ${args}`,
  294. args,
  295. `${CASE_MARKER}: 命令 ${label} 没有被接受`,
  296. );
  297. await waitForUpstreamRequest(
  298. { lastUserMessageIncludes: [args] },
  299. `${CASE_MARKER}: 命令 ${label} 没有到达回放`,
  300. SSH_LIFECYCLE_TURN_TIMEOUT_MS,
  301. { afterIndex: start - 1 },
  302. );
  303. await waitForTurnReply(args, `DSYNC_17_CMD_${label}_REPLY`);
  304. return (await readTurnRequest(args, start - 1)).body.includes(`${COMMAND_BODY} ${args}`);
  305. }
  306. interface RunOutcome {
  307. exposed: boolean;
  308. timedOut: boolean;
  309. result: UpstreamToolResultSnapshot | null;
  310. remoteProcesses?: string;
  311. }
  312. /** 远端进程快照(pid、父 pid、存活秒数、命令行),用来判断各阶段是否同一个 Agent 进程。 */
  313. async function readRemoteAgentProcesses(container: string): Promise<string[]> {
  314. return (await readRemoteProcesses(container))
  315. .split("\n")
  316. .map((line) =>
  317. line
  318. .trim()
  319. .replace(/\s+/gu, " ")
  320. .replace(/\/home\/dev\/\.zcode\/server\/releases\/[^ ]*\//gu, ""),
  321. )
  322. .filter(
  323. (line) =>
  324. line &&
  325. !/ (ps|sh|sleep|sshd: .*@notty|grep) /u.test(` ${line.split(" ").slice(3).join(" ")} `),
  326. );
  327. }
  328. /** 远端进程快照:工具卡住时用来判断 MCP 服务器进程是否还在。 */
  329. async function readRemoteProcesses(container: string): Promise<string> {
  330. return (await execInRemoteContainer(container, ["ps", "-ww", "-eo", "pid,ppid,etimes,args"]))
  331. .stdout;
  332. }
  333. /**
  334. * 执行轮次:回放在工具暴露时调用工具,否则回复 NOT_EXPOSED。
  335. * 远端默认模式可能弹权限请求;期间只批准当前请求,直到本轮出现最终回复。
  336. * 工具卡住时记录远端进程、停止本轮,继续后面的执行轮次,最后统一断言。
  337. */
  338. async function runTool(container: string, key: string, instruction: string): Promise<RunOutcome> {
  339. const prompt = `${CASE_MARKER}_RUN_${key}`;
  340. const done = `DSYNC_17_RUN_${key}_DONE`;
  341. const notExposed = `DSYNC_17_RUN_${key}_NOT_EXPOSED`;
  342. await sendV4PromptAndWaitAccepted(
  343. `${prompt}: ${instruction}`,
  344. prompt,
  345. `${CASE_MARKER}: ${key} 执行轮次没有被接受`,
  346. );
  347. const toolCallId = `call_dsync17_${key.toLowerCase()}`;
  348. let reply: string | null = null;
  349. const settled = await browser
  350. .waitUntil(
  351. async () => {
  352. if (await hasV4PermissionDialog()) await approveV4Permission();
  353. const messages = await getV4Messages();
  354. reply =
  355. [done, notExposed].find((text) => hasAssistantReplyForUserTurn(messages, prompt, text)) ??
  356. null;
  357. return reply !== null;
  358. },
  359. { timeout: 120_000 },
  360. )
  361. .then(
  362. () => true,
  363. () => false,
  364. );
  365. if (!settled) {
  366. const remoteProcesses = await readRemoteProcesses(container);
  367. await clickV4Stop();
  368. await waitForV4ConversationState(
  369. (snapshot) => snapshot.state === "idle",
  370. `${CASE_MARKER}: ${key} 停止后没有回到 idle`,
  371. SSH_LIFECYCLE_TURN_TIMEOUT_MS,
  372. );
  373. return {
  374. exposed: true,
  375. timedOut: true,
  376. result: await getLatestUpstreamToolResultByToolCallId(toolCallId),
  377. remoteProcesses,
  378. };
  379. }
  380. await waitForTurnReply(prompt, reply!);
  381. return {
  382. exposed: reply === done,
  383. timedOut: false,
  384. result: await getLatestUpstreamToolResultByToolCallId(toolCallId),
  385. };
  386. }
  387. async function readRowByText(text: string) {
  388. return await browser.execute((needle) => {
  389. const row = [
  390. ...document.querySelectorAll<HTMLElement>('[data-testid^="remote-sync-row-"]'),
  391. ].find(
  392. (candidate) =>
  393. candidate.dataset.syncStatus !== undefined && candidate.textContent?.includes(needle),
  394. );
  395. return row ? { status: row.dataset.syncStatus ?? null, text: row.textContent ?? "" } : null;
  396. }, text);
  397. }
  398. /** 进入分类页,等列出的行都是「推送」,推送后等它们都变成「已同步」。 */
  399. async function pushCategory(tab: string, rowTexts: string[], timeout = 120_000): Promise<void> {
  400. await clickTestIdByDom(`remote-sync-tab-${tab}`, {
  401. timeout: 60_000,
  402. timeoutMsg: `${CASE_MARKER}: 同步弹窗没有 ${tab} 分类`,
  403. });
  404. for (const text of rowTexts) {
  405. await browser.waitUntil(async () => (await readRowByText(text))?.status === "push", {
  406. timeout: 60_000,
  407. timeoutMsg: `${CASE_MARKER}: ${tab} 分类的 ${text} 没有显示为「推送」`,
  408. });
  409. }
  410. await clickTestIdByDom("remote-sync-push", {
  411. timeout: 30_000,
  412. timeoutMsg: `${CASE_MARKER}: ${tab} 分类的推送按钮不可用`,
  413. });
  414. for (const text of rowTexts) {
  415. await browser.waitUntil(async () => (await readRowByText(text))?.status === "synced", {
  416. timeout,
  417. timeoutMsg: `${CASE_MARKER}: ${tab} 分类的 ${text} 推送后没有变为「已同步」`,
  418. });
  419. }
  420. }
  421. /** 设置 → 数据同步 → 唯一在线设备 → 打开同步弹窗。 */
  422. async function openDataSyncDialog(): Promise<void> {
  423. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON, { timeout: 30_000 });
  424. await waitForTestIdByDom(TID_SETTINGS_PAGE, { timeout: 30_000 });
  425. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "dataSync"), {
  426. timeout: 30_000,
  427. timeoutMsg: `${CASE_MARKER}: 设置页没有数据同步分区`,
  428. });
  429. await waitForTestIdByDom("remote-sync-device-list", {
  430. timeout: 60_000,
  431. timeoutMsg: `${CASE_MARKER}: 数据同步页没有在线设备`,
  432. });
  433. await clickTestIdByDom("remote-sync-device-action");
  434. await waitForTestIdByDom("remote-sync-dialog", { timeout: 30_000 });
  435. }
  436. /** 关闭同步弹窗和设置页,回到打开设置前的界面。 */
  437. async function closeDataSyncDialogAndSettings(): Promise<void> {
  438. // 关闭按钮只在概览页底栏。
  439. await clickTestIdByDom("remote-sync-tab-overview", { timeout: 30_000 });
  440. await clickTestIdByDom("remote-sync-close", { timeout: 30_000 });
  441. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, { timeout: 30_000 });
  442. await browser.waitUntil(
  443. async () => !(await $(`[data-testid="${TID_SETTINGS_PAGE}"]`).isDisplayed()),
  444. { timeout: 30_000, timeoutMsg: `${CASE_MARKER}: 设置页没有关闭` },
  445. );
  446. }
  447. async function readMainPaneSessionId(): Promise<string | null> {
  448. return await browser.execute(
  449. (paneTestId) =>
  450. document.querySelector(`[data-testid="${paneTestId}"]`)?.getAttribute("data-session-id") ??
  451. null,
  452. testId(TID_V4_SESSION_PANE, V4_MAIN_PANE_ID),
  453. );
  454. }
  455. /** 在远程项目里打开新建任务页并选好模型:预热会话在这一步建好。 */
  456. async function openRemoteDraft(task: SSHLifecycleTask, provider: SSHLifecycleProvider) {
  457. await startDraftFromProject(task.workspacePath, { workspaceIdentity: task.identity });
  458. await selectUpstreamProviderModelById(SSH_LIFECYCLE_MODEL_ID, {
  459. includePlainModelFallback: false,
  460. providerId: provider.id,
  461. providerName: provider.name,
  462. });
  463. await selectUpstreamThoughtLevelValue(SSH_LIFECYCLE_THOUGHT_LEVEL);
  464. const tab = await readRemoteTabSnapshot(task.identity, task.workspacePath);
  465. expect(tab.activeWorkspaceIdentity).toBe(task.identity);
  466. expect(await readMainPaneSessionId()).toBe("draft");
  467. }
  468. describe(`${CASE_MARKER}: 推送内容在远端会话中的可用时机`, () => {
  469. let provider: SSHLifecycleProvider | null = null;
  470. let config: SSHRuntimeConfig;
  471. let container = "";
  472. let taskA: SSHLifecycleTask;
  473. let processesAfterTaskA: string[] = [];
  474. const facts: Record<string, unknown> = {};
  475. const record = (key: string, value: unknown) => {
  476. facts[key] = value;
  477. process.stdout.write(`[${CASE_MARKER}] ${key} ${JSON.stringify(value)}\n`);
  478. };
  479. after(async () => {
  480. await mkdir(artifactDir, { recursive: true });
  481. // 诊断:结束时容器会被删除,先把远端 ~/.zcode 下的日志尾部拷进工件。
  482. if (container) {
  483. const logs = await execInRemoteContainer(container, [
  484. "sh",
  485. "-c",
  486. 'find "$HOME/.zcode" -maxdepth 5 \\( -name "*.jsonl" -o -name "*.log" -o -name "*.ndjson" \\) -size -50M | while read -r f; do echo "=== $f"; tail -n 2000 "$f"; done',
  487. ]).catch((error: unknown) => ({ stdout: String(error) }));
  488. await writeFile(join(artifactDir, "remote-logs.txt"), logs.stdout);
  489. }
  490. await writeFile(join(artifactDir, "runtime-usage.json"), `${JSON.stringify(facts, null, 2)}\n`);
  491. await provider?.tunnel.close().catch(() => undefined);
  492. provider = null;
  493. await browser.electron.restoreAllMocks();
  494. await clearAppData();
  495. });
  496. it("DSYNC-17-01 推送前打开的新建任务页:推送子智能体、MCP、命令后在该页发送,子智能体可见;另开一页推送钩子后发送,钩子执行", async function () {
  497. this.timeout(40 * 60_000);
  498. await prepareSSHConnectionPage(CASE_MARKER);
  499. const prepared = await prepareSSHLifecycle(CASE_MARKER);
  500. provider = prepared.provider;
  501. config = prepared.config;
  502. container = readRemoteDockerContainer(CASE_MARKER);
  503. await writeLocalContent(getE2EAppDataPaths().homeDir);
  504. const marketplace = await createPluginLifecycleFixture("1.0.0");
  505. await addMarketplaceSourceThroughAgent(marketplace.marketplaceRoot);
  506. await installMarketplacePluginThroughAgent(
  507. PLUGIN_LIFECYCLE_NAME,
  508. PLUGIN_LIFECYCLE_MARKETPLACE_ID,
  509. );
  510. const controlStart = await getUpstreamRequestRecordCount();
  511. taskA = await connectSSHWorkspaceAndSendFirstTurn({
  512. caseMarker: CASE_MARKER,
  513. config,
  514. label: "A",
  515. provider,
  516. workspacePath: config.workspacePaths[0],
  517. });
  518. // 对照:推送前远端什么都没有,证明各标记不会误判为可见。
  519. const control = factsFromRequest(
  520. await readTurnRequest(taskA.firstPrompt, controlStart - 1),
  521. (await countRemoteHookLines(container)) > 0,
  522. );
  523. record("control", control);
  524. expect(Object.values(control).some(Boolean)).toBe(false);
  525. record("taskALastTurnAt", new Date().toISOString());
  526. await openRemoteDraft(taskA, provider);
  527. processesAfterTaskA = await readRemoteAgentProcesses(container);
  528. record("agentsAfterTaskA", processesAfterTaskA);
  529. await openDataSyncDialog();
  530. await pushCategory("subagents", [AGENT_NAME]);
  531. const subagentPushedAt = Date.now();
  532. await pushCategory("mcp", [MCP_SERVER]);
  533. await pushCategory("commands", [COMMAND_NAME]);
  534. await closeDataSyncDialogAndSettings();
  535. // 回到推送前打开的新建任务页(仍是草稿,没有新建)。
  536. expect(await readMainPaneSessionId()).toBe("draft");
  537. record("agentsAfterFirstPush", await readRemoteAgentProcesses(container));
  538. await waitForSubagentPublishWindow(subagentPushedAt);
  539. record("draftProbeAfterSubagentPushMs", Date.now() - subagentPushedAt);
  540. const draft = await sendProbe(container, "DRAFT");
  541. record("draftTaskId", draft.taskId);
  542. const draftCommand = await sendCommandProbe("DRAFT");
  543. record("draftPrewarmedBeforePush", { ...draft.facts, commandExpanded: draftCommand });
  544. expect(draft.facts.subagentListed).toBe(true);
  545. // 钩子推送会重建预热会话(与本机设置页保存一致),所以单独用一个新建任务页:
  546. // 与上面同批推送时,重建后的会话也会读到 MCP,上面「MCP 推送不重建」的事实就测不到了。
  547. await openRemoteDraft(taskA, provider);
  548. await openDataSyncDialog();
  549. await pushCategory("hooks", [HOOK_MARK]);
  550. await closeDataSyncDialogAndSettings();
  551. expect(await readMainPaneSessionId()).toBe("draft");
  552. const hookDraft = await sendProbe(container, "HOOK_DRAFT");
  553. record("hookDraftPrewarmedBeforePush", hookDraft.facts);
  554. expect(hookDraft.facts.hookFired).toBe(true);
  555. });
  556. it("DSYNC-17-02 推送前已有的 task:推送后续发,子智能体可见并能运行,记录其他内容;按名字调用 Skill", async function () {
  557. this.timeout(30 * 60_000);
  558. await selectV4TaskById(taskA.taskId, 30_000);
  559. await waitForRemoteTab({
  560. caseMarker: CASE_MARKER,
  561. expectedIdentity: taskA.identity,
  562. expectedPath: taskA.workspacePath,
  563. expectedRemoteSessionId: taskA.remoteSessionId,
  564. });
  565. record("existingFirstProbeAt", new Date().toISOString());
  566. const existing = await sendProbe(container, "EXISTING_1");
  567. expect(existing.taskId).toBe(taskA.taskId);
  568. const existingCommand = await sendCommandProbe("EXISTING");
  569. record("existingAfterFirstPush", { ...existing.facts, commandExpanded: existingCommand });
  570. await openDataSyncDialog();
  571. await pushCategory("skills", [SKILL_NAME]);
  572. await pushCategory("plugins", [INLINE_PLUGIN, PLUGIN_LIFECYCLE_MARKETPLACE_ID], 300_000);
  573. await closeDataSyncDialogAndSettings();
  574. await selectV4TaskById(taskA.taskId, 30_000);
  575. const existingAfterAll = await sendProbe(container, "EXISTING_2");
  576. expect(existingAfterAll.taskId).toBe(taskA.taskId);
  577. record("existingAfterAllPushes", existingAfterAll.facts);
  578. const skill = await runTool(
  579. container,
  580. "SKILL_EXISTING",
  581. `调用 Skill 工具加载 ${SKILL_NAME},然后只回复 DSYNC_17_RUN_SKILL_EXISTING_DONE`,
  582. );
  583. record("existingSkillByName", {
  584. called: skill.exposed,
  585. isError: skill.result?.isError ?? null,
  586. bodyReturned: skill.result?.content.includes(SKILL_BODY) ?? false,
  587. });
  588. // 推送前已有的 task 不只是列出子智能体,还能按推送的定义真正运行它。
  589. const existingAgent = await runTool(
  590. container,
  591. "EXISTING_AGENT",
  592. `用 Agent 工具运行子智能体 ${AGENT_NAME},然后只回复 DSYNC_17_RUN_EXISTING_AGENT_DONE`,
  593. );
  594. record("existingAgentRun", existingAgent);
  595. record("existingLastTurnAt", new Date().toISOString());
  596. record("agentsAfterTaskARuns", await readRemoteAgentProcesses(container));
  597. expect(existing.facts.subagentListed).toBe(true);
  598. expect(existingAgent.timedOut).toBe(false);
  599. expect(existingAgent.exposed).toBe(true);
  600. expect(existingAgent.result?.isError).toBe(false);
  601. expect(existingAgent.result?.content).toContain(AGENT_DONE);
  602. });
  603. it("DSYNC-17-03 推送后新建 task:六类内容都可见,MCP、插件 MCP、Skill、子智能体真正执行,钩子执行,命令展开", async function () {
  604. this.timeout(30 * 60_000);
  605. record("agentsBeforeTaskC", await readRemoteAgentProcesses(container));
  606. await openRemoteDraft(taskA, provider!);
  607. const fresh = await sendProbe(container, "NEW");
  608. const processesAfterTaskC = await readRemoteAgentProcesses(container);
  609. record("agentsAfterTaskCProbe", processesAfterTaskC);
  610. // 新建 task 不需要重启 Agent:task C 的用户 MCP 服务器挂在推送前就服务 task A 的同一个 Agent 进程下。
  611. const mcpServerParent = processesAfterTaskC
  612. .find((line) => line.includes(`"${MCP_SERVER}"`))
  613. ?.split(" ")[1];
  614. expect(processesAfterTaskA.some((line) => line.split(" ")[0] === mcpServerParent)).toBe(true);
  615. record("newTask", fresh.facts);
  616. expect(fresh.facts).toEqual({
  617. skillListed: true,
  618. subagentListed: true,
  619. mcpTool: true,
  620. inlinePluginTool: true,
  621. marketplacePluginTool: true,
  622. hookFired: true,
  623. });
  624. expect(await sendCommandProbe("NEW")).toBe(true);
  625. const mcp = await runTool(
  626. container,
  627. "MCP",
  628. `调用 ${MCP_TOOL} 一次,然后只回复 DSYNC_17_RUN_MCP_DONE`,
  629. );
  630. const inline = await runTool(
  631. container,
  632. "INLINE",
  633. `调用 ${INLINE_TOOL} 一次,然后只回复 DSYNC_17_RUN_INLINE_DONE`,
  634. );
  635. const market = await runTool(
  636. container,
  637. "MARKET",
  638. `调用 ${PLUGIN_LIFECYCLE_MCP_TOOL_NAME} 一次,然后只回复 DSYNC_17_RUN_MARKET_DONE`,
  639. );
  640. const skill = await runTool(
  641. container,
  642. "SKILL_NEW",
  643. `调用 Skill 工具加载 ${SKILL_NAME},然后只回复 DSYNC_17_RUN_SKILL_NEW_DONE`,
  644. );
  645. const agent = await runTool(
  646. container,
  647. "AGENT",
  648. `用 Agent 工具运行子智能体 ${AGENT_NAME},然后只回复 DSYNC_17_RUN_AGENT_DONE`,
  649. );
  650. const subagentRequests = await countUpstreamRequests({ includes: [AGENT_BODY] });
  651. record("newTaskRuns", {
  652. mcp,
  653. inline,
  654. market,
  655. skill: {
  656. ...skill,
  657. result: null,
  658. bodyReturned: skill.result?.content.includes(SKILL_BODY) ?? false,
  659. },
  660. agent,
  661. subagentRequests,
  662. });
  663. record("agentsAfterTaskCRuns", await readRemoteAgentProcesses(container));
  664. for (const run of [mcp, inline, market, skill, agent]) {
  665. expect(run.timedOut).toBe(false);
  666. expect(run.exposed).toBe(true);
  667. expect(run.result?.isError).toBe(false);
  668. }
  669. expect(mcp.result?.content.trim()).toBe(MCP_RESULT);
  670. expect(inline.result?.content.trim()).toBe(INLINE_RESULT);
  671. expect(market.result?.content.trim()).toBe(MARKET_RESULT);
  672. expect(skill.result?.content).toContain(SKILL_BODY);
  673. expect(agent.result?.content).toContain(AGENT_DONE);
  674. expect(subagentRequests).toBeGreaterThan(0);
  675. });
  676. });