conversation-session-remote-data-sync-scope-by-device.test.ts 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  1. import { access, readFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { parseRemoteWorkspaceIdentity } from "@zcode/shared";
  4. import {
  5. TID_MCP_SERVER_ROW,
  6. TID_SETTINGS_BACK_BUTTON,
  7. TID_SETTINGS_PAGE,
  8. TID_SETTINGS_SECTION_NAV,
  9. TID_SUBAGENT_ROW,
  10. TID_TASK_SETTINGS_BUTTON,
  11. testId,
  12. } from "@zcode/shared/test-ids";
  13. import {
  14. clearAppData,
  15. clickTestIdByDom,
  16. DEFAULT_WORKSPACE,
  17. getE2EAppDataPaths,
  18. waitForTestIdByDom,
  19. } from "#e2e/helpers/desktop-app";
  20. import { resolveE2EStorageRoot } from "#e2e/helpers/e2e-runtime-paths";
  21. import { startDraftFromProject } from "#e2e/helpers/project-sidebar";
  22. import {
  23. bringRemoteDeviceOnline,
  24. readRemoteContainerFile,
  25. readRemoteDockerContainer,
  26. remoteContainerPathExists,
  27. takeRemoteDeviceOffline,
  28. writeRemoteContainerFile,
  29. } from "#e2e/helpers/remote-docker-target";
  30. import {
  31. connectSSHWorkspace,
  32. prepareSSHConnectionPage,
  33. readSSHRuntimeConfig,
  34. waitForRemoteTab,
  35. } from "#e2e/helpers/ssh-remote-p0";
  36. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  37. import { openScopeProjectSubmenu } from "#e2e/helpers/settings-scope-menu";
  38. // DSYNC-15:设置页 Scope 菜单按设备分组(docs/remote/data-sync.md「Scope 菜单按设备分组」)。
  39. // 远端「用户」经该设备的 source-settings attachment 读写,不要求打开项目;远端断言用 docker exec。
  40. const CASE_MARKER = "E2E_DSYNC_15_SCOPE_BY_DEVICE";
  41. const REMOTE_AGENT = "e2e-dsync15-remote-agent";
  42. // 带显式模型与推理档位的远端子智能体(例如从本机同步过来的);远端「用户」没有模型目录。
  43. const REMOTE_MODEL_AGENT = "e2e-dsync15-remote-model-agent";
  44. const REMOTE_MODEL_AGENT_MODEL = "e2e-provider/e2e-model";
  45. const REMOTE_MODEL_AGENT_THOUGHT_LEVEL = "high";
  46. const LOCAL_AGENT = "e2e-dsync15-local-agent";
  47. const REMOTE_COMMAND = "e2e-dsync15-remote-command";
  48. const REMOTE_MCP = "e2e-dsync15-remote-mcp";
  49. const LOCAL_MCP = "e2e-dsync15-local-mcp";
  50. const LOCAL_HOOK_MARKER = "E2E_DSYNC_15_LOCAL_HOOK";
  51. const REMOTE_HOOK_MARKER = "E2E_DSYNC_15_REMOTE_HOOK";
  52. const HOOK_FORM = '[data-testid="hooks-form"]';
  53. const REMOTE_HOME = "/home/dev";
  54. const SCOPE_TRIGGER = '[data-plugin-scope-trigger="true"]';
  55. async function openSettingsSection(section: string): Promise<void> {
  56. const onSettings = await browser.execute(
  57. (pageId) => Boolean(document.querySelector(`[data-testid="${pageId}"]`)),
  58. TID_SETTINGS_PAGE,
  59. );
  60. if (!onSettings) {
  61. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON, { timeout: 30_000 });
  62. await waitForTestIdByDom(TID_SETTINGS_PAGE, { timeout: 30_000 });
  63. }
  64. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, section), {
  65. timeout: 30_000,
  66. timeoutMsg: `${CASE_MARKER}: 设置页没有 ${section} 分区`,
  67. });
  68. }
  69. async function readVisibleTriggerKey(): Promise<string | null> {
  70. return await browser.execute((selector) => {
  71. const trigger = Array.from(document.querySelectorAll<HTMLElement>(selector)).find(
  72. (element) => element.getClientRects().length > 0,
  73. );
  74. return trigger?.dataset.pluginScopeKey ?? null;
  75. }, SCOPE_TRIGGER);
  76. }
  77. async function waitForScopeKey(key: string, timeoutMsg: string): Promise<void> {
  78. let current: string | null = null;
  79. await browser
  80. .waitUntil(
  81. async () => {
  82. current = await readVisibleTriggerKey();
  83. return current === key;
  84. },
  85. { timeout: 60_000, interval: 300 },
  86. )
  87. .catch((error: unknown) => {
  88. throw new Error(`${CASE_MARKER}: ${timeoutMsg};当前 scope=${current}`, { cause: error });
  89. });
  90. }
  91. /** Radix 菜单需要 pointerdown 打开;只操作当前可见的触发器(插件容器 forceMount 多个分区)。 */
  92. async function openScopeMenu(): Promise<void> {
  93. await browser.waitUntil(
  94. () =>
  95. browser.execute((selector) => {
  96. if (document.querySelector('[role="menuitemradio"]')) return true;
  97. const trigger = Array.from(document.querySelectorAll<HTMLElement>(selector)).find(
  98. (element) => element.getClientRects().length > 0,
  99. );
  100. trigger?.dispatchEvent(
  101. new PointerEvent("pointerdown", { bubbles: true, button: 0, pointerType: "mouse" }),
  102. );
  103. return false;
  104. }, SCOPE_TRIGGER),
  105. { timeout: 15_000, interval: 500, timeoutMsg: `${CASE_MARKER}: scope 菜单打不开` },
  106. );
  107. }
  108. /** 读取菜单:第一层的标题、选项和「项目」入口所属设备,以及打开 `projectsDevice` 子菜单后的项目。 */
  109. async function readScopeMenu(projectsDevice: string) {
  110. await openScopeMenu();
  111. const menu = await browser.execute(() => ({
  112. headings: Array.from(
  113. document.querySelectorAll<HTMLElement>('[data-scope-device-heading="true"]'),
  114. ).map((heading) => heading.innerText.trim()),
  115. keys: Array.from(document.querySelectorAll<HTMLElement>('[role="menuitemradio"]')).map(
  116. (item) => item.dataset.pluginScopeKey ?? "",
  117. ),
  118. projectsDevices: Array.from(
  119. document.querySelectorAll<HTMLElement>('[data-scope-projects-trigger="true"]'),
  120. ).map((trigger) => trigger.dataset.scopeDevice ?? ""),
  121. lines: (document.querySelector<HTMLElement>('[role="menu"]')?.innerText ?? "")
  122. .split("\n")
  123. .map((line) => line.trim())
  124. .filter(Boolean),
  125. }));
  126. await openScopeProjectSubmenu(projectsDevice);
  127. const projectKeys = await browser.execute(() =>
  128. Array.from(
  129. document.querySelectorAll<HTMLElement>(
  130. '[data-slot="dropdown-menu-sub-content"] [role="menuitemradio"]',
  131. ),
  132. ).map((item) => item.dataset.pluginScopeKey ?? ""),
  133. );
  134. await browser.keys(["Escape"]);
  135. return { ...menu, projectKeys };
  136. }
  137. async function selectScopeKey(key: string): Promise<void> {
  138. await openScopeMenu();
  139. const clicked = await browser.execute((expected) => {
  140. const item = Array.from(document.querySelectorAll<HTMLElement>('[role="menuitemradio"]')).find(
  141. (candidate) => candidate.dataset.pluginScopeKey === expected,
  142. );
  143. item?.click();
  144. return Boolean(item);
  145. }, key);
  146. if (!clicked) throw new Error(`${CASE_MARKER}: scope 菜单没有 ${key}`);
  147. await waitForScopeKey(key, `scope 没有切到 ${key}`);
  148. }
  149. async function clickVisibleNewButton(): Promise<void> {
  150. await browser.waitUntil(
  151. () =>
  152. browser.execute(() => {
  153. const button = Array.from(
  154. document.querySelectorAll<HTMLButtonElement>(
  155. 'button[aria-label="新建"], button[aria-label="New"]',
  156. ),
  157. ).find((element) => element.getClientRects().length > 0 && !element.disabled);
  158. button?.click();
  159. return Boolean(button);
  160. }),
  161. { timeout: 60_000, interval: 500, timeoutMsg: `${CASE_MARKER}: 没有可用的「新建」按钮` },
  162. );
  163. }
  164. /** 按 placeholder 填写当前表单的输入框(React 受控组件需要原生 setter + input 事件)。 */
  165. async function fillByPlaceholder(placeholder: string, value: string): Promise<void> {
  166. const filled = await browser.execute(
  167. (expected, nextValue) => {
  168. const field = Array.from(
  169. document.querySelectorAll<HTMLInputElement | HTMLTextAreaElement>("input, textarea"),
  170. ).find((element) => element.placeholder === expected && element.getClientRects().length > 0);
  171. if (!field) return false;
  172. const prototype =
  173. field instanceof HTMLTextAreaElement
  174. ? HTMLTextAreaElement.prototype
  175. : HTMLInputElement.prototype;
  176. Object.getOwnPropertyDescriptor(prototype, "value")?.set?.call(field, nextValue);
  177. field.dispatchEvent(new Event("input", { bubbles: true }));
  178. return true;
  179. },
  180. placeholder,
  181. value,
  182. );
  183. if (!filled) throw new Error(`${CASE_MARKER}: 表单没有输入框 ${placeholder}`);
  184. }
  185. /** 提交含指定输入框的表单(页面上还有搜索等其他 form,不能取第一个可见 form)。 */
  186. async function submitFormOf(placeholder: string): Promise<void> {
  187. let state = "";
  188. await browser
  189. .waitUntil(
  190. async () => {
  191. state = await browser.execute((expected) => {
  192. const field = Array.from(
  193. document.querySelectorAll<HTMLInputElement>("input, textarea"),
  194. ).find((element) => element.placeholder === expected);
  195. const form = field?.closest("form");
  196. const submit = form?.querySelector<HTMLButtonElement>('button[type="submit"]');
  197. if (!form || !submit) return "no-form";
  198. if (submit.disabled) return "disabled";
  199. form.requestSubmit(submit);
  200. return "submitted";
  201. }, placeholder);
  202. return state === "submitted";
  203. },
  204. { timeout: 15_000, interval: 300 },
  205. )
  206. .catch((error: unknown) => {
  207. throw new Error(`${CASE_MARKER}: 表单不能保存(${state})`, { cause: error });
  208. });
  209. await browser.waitUntil(
  210. () =>
  211. browser.execute(
  212. (expected) =>
  213. !Array.from(document.querySelectorAll<HTMLInputElement>("input")).some(
  214. (element) => element.placeholder === expected,
  215. ),
  216. placeholder,
  217. ),
  218. { timeout: 30_000, timeoutMsg: `${CASE_MARKER}: 保存后表单没有关闭` },
  219. );
  220. }
  221. async function createSubagent(name: string): Promise<void> {
  222. await clickVisibleNewButton();
  223. await fillByPlaceholder("code-reviewer", name);
  224. await fillByPlaceholder("展示给模型的简短说明", `${CASE_MARKER} description`);
  225. await fillByPlaceholder("描述这个子智能体的角色、边界和规则...", `${CASE_MARKER} prompt`);
  226. await submitFormOf("code-reviewer");
  227. await waitForTestIdByDom(testId(TID_SUBAGENT_ROW, name), {
  228. timeout: 30_000,
  229. timeoutMsg: `${CASE_MARKER}: 子智能体行没有出现 ${name}`,
  230. });
  231. }
  232. /** 子智能体表单名称输入框的值;没有表单时返回 null。 */
  233. async function readSubagentFormName(): Promise<string | null> {
  234. return await browser.execute(() => {
  235. const field = Array.from(document.querySelectorAll<HTMLInputElement>("input")).find(
  236. (element) => element.placeholder === "code-reviewer" && element.getClientRects().length > 0,
  237. );
  238. return field ? field.value : null;
  239. });
  240. }
  241. async function localPathExists(path: string): Promise<boolean> {
  242. return await access(path).then(
  243. () => true,
  244. () => false,
  245. );
  246. }
  247. /** 打开 MCP 新建表单:有已安装项时是分组标题里的「+」,列表为空时是空状态按钮。 */
  248. async function openNewMcpForm(): Promise<void> {
  249. await browser.waitUntil(
  250. () =>
  251. browser.execute(() => {
  252. const button = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find(
  253. (element) =>
  254. element.getClientRects().length > 0 &&
  255. !element.disabled &&
  256. (element.dataset.settingsCreateAction === "settings.mcp.create.open" ||
  257. element.innerText.trim() === "新建 MCP 服务器"),
  258. );
  259. button?.click();
  260. return Boolean(button);
  261. }),
  262. { timeout: 60_000, interval: 500, timeoutMsg: `${CASE_MARKER}: 没有可用的「新建 MCP 服务器」` },
  263. );
  264. }
  265. async function clickVisibleButtonText(text: string): Promise<void> {
  266. await browser.waitUntil(
  267. () =>
  268. browser.execute((expected) => {
  269. const button = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find(
  270. (element) =>
  271. element.getClientRects().length > 0 &&
  272. !element.disabled &&
  273. element.innerText.trim() === expected,
  274. );
  275. button?.click();
  276. return Boolean(button);
  277. }, text),
  278. { timeout: 15_000, interval: 300, timeoutMsg: `${CASE_MARKER}: 没有可用的「${text}」按钮` },
  279. );
  280. }
  281. /** 新建一个 stdio MCP;只断言配置落盘位置,不要求它能连接。 */
  282. async function createMcpServer(name: string): Promise<void> {
  283. await openNewMcpForm();
  284. await fillByPlaceholder("my-mcp-server", name);
  285. await fillByPlaceholder("npx", "node");
  286. await fillByPlaceholder("-y @modelcontextprotocol/server-memory", `${name}.mjs`);
  287. await clickVisibleButtonText("保存");
  288. await waitForTestIdByDom(testId(TID_MCP_SERVER_ROW, name), {
  289. timeout: 30_000,
  290. timeoutMsg: `${CASE_MARKER}: MCP 行没有出现 ${name}`,
  291. });
  292. }
  293. async function toggleMcpServer(name: string): Promise<void> {
  294. const clicked = await browser.execute(
  295. (rowId) => {
  296. const toggle = document.querySelector<HTMLElement>(
  297. `[data-testid="${rowId}"] [role="switch"]`,
  298. );
  299. toggle?.click();
  300. return Boolean(toggle);
  301. },
  302. testId(TID_MCP_SERVER_ROW, name),
  303. );
  304. if (!clicked) throw new Error(`${CASE_MARKER}: MCP 行没有开关 ${name}`);
  305. }
  306. type McpServerEntries = Record<string, { enabled?: boolean } | undefined>;
  307. function readMcpServerEntries(raw: string): McpServerEntries {
  308. if (!raw.trim()) return {};
  309. const parsed = JSON.parse(raw) as { mcp?: { servers?: McpServerEntries } };
  310. return parsed.mcp?.servers ?? {};
  311. }
  312. async function readLocalMcpServers(): Promise<McpServerEntries> {
  313. const raw = await readFile(join(resolveE2EStorageRoot(), "cli", "config.json"), "utf8").catch(
  314. (error: NodeJS.ErrnoException) => {
  315. if (error.code === "ENOENT") return "";
  316. throw error;
  317. },
  318. );
  319. return readMcpServerEntries(raw);
  320. }
  321. async function readRemoteMcpServers(container: string): Promise<McpServerEntries> {
  322. const path = `${REMOTE_HOME}/.zcode/cli/config.json`;
  323. if (!(await remoteContainerPathExists(container, path))) return {};
  324. return readMcpServerEntries(await readRemoteContainerFile(container, path));
  325. }
  326. async function waitForMcpEntry(
  327. read: () => Promise<McpServerEntries>,
  328. name: string,
  329. matches: (entry: { enabled?: boolean }) => boolean,
  330. timeoutMsg: string,
  331. ): Promise<void> {
  332. let latest: McpServerEntries = {};
  333. await browser
  334. .waitUntil(
  335. async () => {
  336. latest = await read();
  337. const entry = latest[name];
  338. return Boolean(entry && matches(entry));
  339. },
  340. { timeout: 30_000, interval: 500 },
  341. )
  342. .catch((error: unknown) => {
  343. throw new Error(`${CASE_MARKER}: ${timeoutMsg};当前 ${JSON.stringify(latest)}`, {
  344. cause: error,
  345. });
  346. });
  347. }
  348. /** 当前钩子表单 #args 的值;没有表单时返回 null。 */
  349. async function readHookFormArgs(): Promise<string | null> {
  350. return await browser.execute((selector) => {
  351. const form = document.querySelector<HTMLElement>(selector);
  352. return form?.querySelector<HTMLTextAreaElement>("#args")?.value ?? (form ? "" : null);
  353. }, HOOK_FORM);
  354. }
  355. /** 按 id 填写钩子表单的输入框(React 受控组件需要原生 setter + input 事件)。 */
  356. async function fillHookField(id: string, value: string): Promise<void> {
  357. const filled = await browser.execute(
  358. (selector, fieldId, nextValue) => {
  359. const field = document
  360. .querySelector<HTMLElement>(selector)
  361. ?.querySelector<HTMLInputElement | HTMLTextAreaElement>(`#${fieldId}`);
  362. if (!field) return false;
  363. const prototype =
  364. field instanceof HTMLTextAreaElement
  365. ? HTMLTextAreaElement.prototype
  366. : HTMLInputElement.prototype;
  367. Object.getOwnPropertyDescriptor(prototype, "value")?.set?.call(field, nextValue);
  368. field.dispatchEvent(new Event("input", { bubbles: true }));
  369. return true;
  370. },
  371. HOOK_FORM,
  372. id,
  373. value,
  374. );
  375. if (!filled) throw new Error(`${CASE_MARKER}: 钩子表单没有输入框 #${id}`);
  376. }
  377. /** 新建一个只在不存在的 matcher 上触发的 process 钩子(本用例不信任、不执行它)。 */
  378. async function createUserHook(marker: string): Promise<void> {
  379. await browser.waitUntil(
  380. () =>
  381. browser.execute(() => {
  382. const button = Array.from(
  383. document.querySelectorAll<HTMLButtonElement>(
  384. '[data-settings-create-action="settings.hooks.add"]',
  385. ),
  386. ).find((element) => element.getClientRects().length > 0 && !element.disabled);
  387. button?.click();
  388. return Boolean(button);
  389. }),
  390. { timeout: 60_000, interval: 500, timeoutMsg: `${CASE_MARKER}: 没有可用的「新建钩子」` },
  391. );
  392. await $(HOOK_FORM).waitForDisplayed({ timeout: 15_000 });
  393. await fillHookField("matcher", `${marker}_MATCHER_NEVER`);
  394. await fillHookField("command", "/usr/bin/printf");
  395. await fillHookField("args", marker);
  396. await browser.waitUntil(
  397. () =>
  398. browser.execute((selector) => {
  399. const button = Array.from(
  400. document
  401. .querySelector<HTMLElement>(selector)
  402. ?.querySelectorAll<HTMLButtonElement>("button") ?? [],
  403. ).find((item) => /^(保存|Save)$/iu.test(item.innerText.trim()) && !item.disabled);
  404. button?.click();
  405. return Boolean(button);
  406. }, HOOK_FORM),
  407. { timeout: 15_000, timeoutMsg: `${CASE_MARKER}: 钩子表单没有可用的保存按钮` },
  408. );
  409. await browser.waitUntil(async () => !(await $(HOOK_FORM).isExisting()), {
  410. timeout: 30_000,
  411. timeoutMsg: `${CASE_MARKER}: 保存后钩子表单没有关闭`,
  412. });
  413. }
  414. /** 当前列表中命令文本含 marker 的钩子行是否可见。 */
  415. async function isHookRowVisible(marker: string): Promise<boolean> {
  416. return await browser.execute(
  417. (expected) =>
  418. Array.from(
  419. document.querySelectorAll<HTMLElement>('[data-testid="configured-hook-row"]'),
  420. ).some((row) => row.getClientRects().length > 0 && row.innerText.includes(expected)),
  421. marker,
  422. );
  423. }
  424. async function clickHookRow(marker: string): Promise<void> {
  425. await browser.waitUntil(
  426. () =>
  427. browser.execute((expected) => {
  428. const row = Array.from(
  429. document.querySelectorAll<HTMLElement>('[data-testid="configured-hook-row"]'),
  430. ).find((item) => item.getClientRects().length > 0 && item.innerText.includes(expected));
  431. row?.click();
  432. return Boolean(row);
  433. }, marker),
  434. { timeout: 60_000, interval: 500, timeoutMsg: `${CASE_MARKER}: 列表里没有钩子 ${marker}` },
  435. );
  436. }
  437. /** 用户级钩子在 `<home>/.zcode/cli/config.json` 的 hooks 字段。 */
  438. function readHooksConfig(raw: string): unknown {
  439. if (!raw.trim()) return null;
  440. return (JSON.parse(raw) as { hooks?: unknown }).hooks ?? null;
  441. }
  442. async function readLocalUserConfigRaw(): Promise<string> {
  443. return await readFile(join(resolveE2EStorageRoot(), "cli", "config.json"), "utf8").catch(
  444. (error: NodeJS.ErrnoException) => {
  445. if (error.code === "ENOENT") return "";
  446. throw error;
  447. },
  448. );
  449. }
  450. async function waitForRemotePath(container: string, path: string): Promise<void> {
  451. await browser.waitUntil(async () => await remoteContainerPathExists(container, path), {
  452. timeout: 30_000,
  453. interval: 500,
  454. timeoutMsg: `${CASE_MARKER}: 远端没有写入 ${path}`,
  455. });
  456. }
  457. describe(`${CASE_MARKER}: 设置页 Scope 菜单按设备分组`, () => {
  458. let sourceServerId = "";
  459. let container = "";
  460. let remoteWorkspacePath = "";
  461. let remoteWorkspaceIdentity = "";
  462. let offlineTarget: { host: string; port: number } | null = null;
  463. after(async () => {
  464. // DSYNC-15-04 / 15-05 中途失败时恢复容器,避免影响同一 runner 的后续 spec。
  465. if (offlineTarget)
  466. await bringRemoteDeviceOnline(container, offlineTarget).catch(() => undefined);
  467. await browser.electron.restoreAllMocks();
  468. await clearAppData();
  469. });
  470. it("DSYNC-15-01 远程 tab 默认「该设备 · 用户」,新建子智能体写入远端;切到「本机 · 用户」写入本机", async function () {
  471. this.timeout(20 * 60_000);
  472. const config = readSSHRuntimeConfig(CASE_MARKER);
  473. container = readRemoteDockerContainer(CASE_MARKER);
  474. const workspacePath = config.workspacePaths[0];
  475. await prepareSSHConnectionPage(CASE_MARKER);
  476. await prepareV4ConversationE2E({ skipProvider: true });
  477. const remoteTab = await connectSSHWorkspace({ caseMarker: CASE_MARKER, config, workspacePath });
  478. sourceServerId =
  479. parseRemoteWorkspaceIdentity(remoteTab.workspaceIdentity ?? "")?.sourceServerId ?? "";
  480. expect(sourceServerId).toBeTruthy();
  481. remoteWorkspacePath = workspacePath;
  482. remoteWorkspaceIdentity = remoteTab.workspaceIdentity ?? "";
  483. const remoteUserKey = `source-user:${sourceServerId}`;
  484. const remoteModelAgentPath = `${REMOTE_HOME}/.zcode/agents/${REMOTE_MODEL_AGENT}.md`;
  485. await writeRemoteContainerFile(
  486. container,
  487. remoteModelAgentPath,
  488. [
  489. "---",
  490. `name: "${REMOTE_MODEL_AGENT}"`,
  491. `description: "${CASE_MARKER} model agent"`,
  492. `model: "${REMOTE_MODEL_AGENT_MODEL}"`,
  493. `thoughtLevel: "${REMOTE_MODEL_AGENT_THOUGHT_LEVEL}"`,
  494. "---",
  495. `${CASE_MARKER} model agent prompt`,
  496. "",
  497. ].join("\n"),
  498. );
  499. await openSettingsSection("subagents");
  500. await waitForScopeKey(remoteUserKey, "远程 tab 下子智能体页没有默认选中该设备的「用户」");
  501. await waitForTestIdByDom(testId(TID_SUBAGENT_ROW, "general-purpose"), { timeout: 60_000 });
  502. // 菜单:本机在前,远端设备一组;第一层只有各设备的「用户」和「项目」入口,项目在子菜单里
  503. // (19 号票),没有「工作区」小标题。
  504. const menu = await readScopeMenu(sourceServerId);
  505. expect(menu.headings).toHaveLength(2);
  506. expect(menu.headings[0]).toBe("本机");
  507. expect(menu.keys).toEqual(["user", remoteUserKey]);
  508. // 本机是否有项目取决于 E2E 存储,只断言远端设备有「项目」入口。
  509. expect(menu.projectsDevices).toContain(sourceServerId);
  510. expect(menu.projectKeys).toContain(remoteTab.workspaceIdentity!);
  511. expect(menu.lines).not.toContain("工作区");
  512. // 触发器设备名在前:「<设备> · 用户」。
  513. const triggerText = await browser.execute((selector) => {
  514. const trigger = Array.from(document.querySelectorAll<HTMLElement>(selector)).find(
  515. (element) => element.getClientRects().length > 0,
  516. );
  517. return trigger?.innerText.replace(/\s+/gu, "") ?? "";
  518. }, SCOPE_TRIGGER);
  519. expect(triggerText).toBe(`${menu.headings[1]!.replace(/\s+/gu, "")}·用户`);
  520. // 远端「用户」:新建写入远端 ~/.zcode/agents,本机不变。
  521. await createSubagent(REMOTE_AGENT);
  522. await waitForRemotePath(container, `${REMOTE_HOME}/.zcode/agents/${REMOTE_AGENT}.md`);
  523. expect(
  524. await localPathExists(join(resolveE2EStorageRoot(), "agents", `${REMOTE_AGENT}.md`)),
  525. ).toBe(false);
  526. // source-settings attachment 不暴露 model-selection:页面不读模型目录,也不显示加载失败。
  527. // 旧实现约 1s 后就会显示该提示;此时已完成新建与远端写入,足以观察到它。
  528. expect(await browser.execute(() => document.body.innerText.includes("模型列表加载失败"))).toBe(
  529. false,
  530. );
  531. // 已存显式模型的子智能体:没有模型目录,推理档位显示「推理档位暂不可用」,不能一直加载中;
  532. // 保存后 model / thoughtLevel 保持原值。
  533. await clickTestIdByDom(testId(TID_SUBAGENT_ROW, REMOTE_MODEL_AGENT), {
  534. timeout: 60_000,
  535. timeoutMsg: `${CASE_MARKER}: 远端「用户」没有子智能体 ${REMOTE_MODEL_AGENT}`,
  536. });
  537. await browser.waitUntil(async () => (await readSubagentFormName()) === REMOTE_MODEL_AGENT, {
  538. timeout: 30_000,
  539. timeoutMsg: `${CASE_MARKER}: 没有打开 ${REMOTE_MODEL_AGENT} 的编辑表单`,
  540. });
  541. let reasoning = { loading: false, unavailable: false };
  542. await browser
  543. .waitUntil(
  544. async () => {
  545. reasoning = await browser.execute(() => ({
  546. loading: Boolean(
  547. document.querySelector('[data-subagent-thought-level-loading="true"]'),
  548. ),
  549. unavailable: Boolean(
  550. document.querySelector('[data-subagent-thought-level-unavailable="true"]'),
  551. ),
  552. }));
  553. return reasoning.unavailable;
  554. },
  555. { timeout: 15_000, interval: 300 },
  556. )
  557. .catch((error: unknown) => {
  558. throw new Error(
  559. `${CASE_MARKER}: 推理档位没有显示「暂不可用」(${JSON.stringify(reasoning)})`,
  560. { cause: error },
  561. );
  562. });
  563. expect(reasoning.loading).toBe(false);
  564. await submitFormOf("code-reviewer");
  565. const savedModelAgent = await readRemoteContainerFile(container, remoteModelAgentPath);
  566. // 保存按 YAML plain scalar 写回(不带引号)。
  567. expect(savedModelAgent).toContain(`\nmodel: ${REMOTE_MODEL_AGENT_MODEL}\n`);
  568. expect(savedModelAgent).toContain(`\nthoughtLevel: ${REMOTE_MODEL_AGENT_THOUGHT_LEVEL}\n`);
  569. // 「本机 · 用户」:新建写入本机,远端不变。
  570. await selectScopeKey("user");
  571. await createSubagent(LOCAL_AGENT);
  572. await browser.waitUntil(
  573. async () =>
  574. await localPathExists(join(resolveE2EStorageRoot(), "agents", `${LOCAL_AGENT}.md`)),
  575. { timeout: 30_000, timeoutMsg: `${CASE_MARKER}: 本机没有写入 ${LOCAL_AGENT}` },
  576. );
  577. expect(
  578. await remoteContainerPathExists(container, `${REMOTE_HOME}/.zcode/agents/${LOCAL_AGENT}.md`),
  579. ).toBe(false);
  580. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, { timeout: 15_000 });
  581. });
  582. it("DSYNC-15-02 本地 tab 默认「本机 · 用户」;选择远端设备「用户」新建命令写入远端", async function () {
  583. this.timeout(10 * 60_000);
  584. expect(sourceServerId).toBeTruthy();
  585. const remoteUserKey = `source-user:${sourceServerId}`;
  586. const { homeDir } = getE2EAppDataPaths();
  587. // 切到本机项目的 tab:远端设备仍在线,但不是当前 workspace 所在设备。
  588. if (await $(`[data-testid="${TID_SETTINGS_PAGE}"]`).isExisting()) {
  589. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, { timeout: 15_000 });
  590. }
  591. await startDraftFromProject(DEFAULT_WORKSPACE);
  592. await openSettingsSection("commands");
  593. await waitForScopeKey("user", "本地 tab 下命令页没有默认选中「本机 · 用户」");
  594. // 不打开远程项目,直接选择远端设备的「用户」编辑命令。
  595. await selectScopeKey(remoteUserKey);
  596. await clickVisibleNewButton();
  597. await fillByPlaceholder("my-command", REMOTE_COMMAND);
  598. await fillByPlaceholder("在命令选择器中显示的简短描述", `${CASE_MARKER} description`);
  599. await fillByPlaceholder("填写调用该命令时发送的提示词...", `${CASE_MARKER} prompt`);
  600. await submitFormOf("my-command");
  601. const remotePath = `${REMOTE_HOME}/.zcode/commands/${REMOTE_COMMAND}.md`;
  602. await waitForRemotePath(container, remotePath);
  603. expect(await readRemoteContainerFile(container, remotePath)).toContain(`${CASE_MARKER} prompt`);
  604. expect(await localPathExists(join(homeDir, ".zcode", "commands", `${REMOTE_COMMAND}.md`))).toBe(
  605. false,
  606. );
  607. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, { timeout: 15_000 });
  608. });
  609. it("DSYNC-15-03 MCP 只按 Scope 目标读写:本机 tab 选远端「用户」新增、开关写容器;远程 tab 选「本机 · 用户」新增写本机", async function () {
  610. this.timeout(15 * 60_000);
  611. expect(sourceServerId).toBeTruthy();
  612. expect(remoteWorkspaceIdentity).toBeTruthy();
  613. const remoteUserKey = `source-user:${sourceServerId}`;
  614. // 本机 tab(DSYNC-15-02 已切到本机项目):选远端设备「用户」,新增与开关都写进容器,本机不变。
  615. if (await $(`[data-testid="${TID_SETTINGS_PAGE}"]`).isExisting()) {
  616. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, { timeout: 15_000 });
  617. }
  618. await startDraftFromProject(DEFAULT_WORKSPACE);
  619. await openSettingsSection("mcp");
  620. await waitForScopeKey("user", "本地 tab 下 MCP 页没有默认选中「本机 · 用户」");
  621. await selectScopeKey(remoteUserKey);
  622. await createMcpServer(REMOTE_MCP);
  623. await waitForMcpEntry(
  624. () => readRemoteMcpServers(container),
  625. REMOTE_MCP,
  626. (entry) => entry.enabled !== false,
  627. "远端「用户」新增的 MCP 没有写进容器",
  628. );
  629. await toggleMcpServer(REMOTE_MCP);
  630. await waitForMcpEntry(
  631. () => readRemoteMcpServers(container),
  632. REMOTE_MCP,
  633. (entry) => entry.enabled === false,
  634. "远端「用户」关闭 MCP 没有写进容器",
  635. );
  636. expect((await readLocalMcpServers())[REMOTE_MCP]).toBeUndefined();
  637. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, { timeout: 15_000 });
  638. // 远程 tab:默认「该设备 · 用户」,显式选「本机 · 用户」后新增只写本机,容器不变。
  639. await startDraftFromProject(remoteWorkspacePath, {
  640. workspaceIdentity: remoteWorkspaceIdentity,
  641. });
  642. await waitForRemoteTab({
  643. caseMarker: CASE_MARKER,
  644. expectedIdentity: remoteWorkspaceIdentity,
  645. expectedPath: remoteWorkspacePath,
  646. });
  647. await openSettingsSection("mcp");
  648. await waitForScopeKey(remoteUserKey, "远程 tab 下 MCP 页没有默认选中该设备的「用户」");
  649. await selectScopeKey("user");
  650. await createMcpServer(LOCAL_MCP);
  651. await waitForMcpEntry(
  652. readLocalMcpServers,
  653. LOCAL_MCP,
  654. () => true,
  655. "「本机 · 用户」新增的 MCP 没有写进本机",
  656. );
  657. expect((await readRemoteMcpServers(container))[LOCAL_MCP]).toBeUndefined();
  658. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, { timeout: 15_000 });
  659. });
  660. it("DSYNC-15-04 远端「用户」编辑子智能体时设备离线,切到「本机 · 用户」不显示旧表单、本机不写入", async function () {
  661. this.timeout(15 * 60_000);
  662. expect(sourceServerId).toBeTruthy();
  663. const config = readSSHRuntimeConfig(CASE_MARKER);
  664. const remoteUserKey = `source-user:${sourceServerId}`;
  665. const localAgentFile = join(resolveE2EStorageRoot(), "agents", `${REMOTE_AGENT}.md`);
  666. // 远端「用户」打开 15-01 新建的子智能体的编辑表单。
  667. if (await $(`[data-testid="${TID_SETTINGS_PAGE}"]`).isExisting()) {
  668. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, { timeout: 15_000 });
  669. }
  670. await openSettingsSection("subagents");
  671. await selectScopeKey(remoteUserKey);
  672. await clickTestIdByDom(testId(TID_SUBAGENT_ROW, REMOTE_AGENT), {
  673. timeout: 60_000,
  674. timeoutMsg: `${CASE_MARKER}: 远端「用户」没有子智能体 ${REMOTE_AGENT}`,
  675. });
  676. await browser.waitUntil(async () => (await readSubagentFormName()) === REMOTE_AGENT, {
  677. timeout: 30_000,
  678. timeoutMsg: `${CASE_MARKER}: 没有打开 ${REMOTE_AGENT} 的编辑表单`,
  679. });
  680. // 设备离线:表单隐藏,只显示离线提示(管理快照判定离线可能要几分钟)。
  681. offlineTarget = { host: config.host, port: config.port };
  682. await takeRemoteDeviceOffline(container);
  683. await browser.waitUntil(
  684. () =>
  685. browser.execute(() => Boolean(document.querySelector('[data-scope-blocked="offline"]'))),
  686. {
  687. timeout: 5 * 60_000,
  688. interval: 1_000,
  689. timeoutMsg: `${CASE_MARKER}: 设备离线后没有离线提示`,
  690. },
  691. );
  692. expect(await readSubagentFormName()).toBeNull();
  693. // 列表页切到「本机 · 用户」:显示本机列表,旧表单不出现,本机不写入远端子智能体。
  694. await selectScopeKey("user");
  695. await waitForTestIdByDom(testId(TID_SUBAGENT_ROW, LOCAL_AGENT), {
  696. timeout: 60_000,
  697. timeoutMsg: `${CASE_MARKER}: 切到「本机 · 用户」后没有显示本机列表`,
  698. });
  699. expect(await readSubagentFormName()).toBeNull();
  700. expect(await localPathExists(localAgentFile)).toBe(false);
  701. await bringRemoteDeviceOnline(container, offlineTarget);
  702. offlineTarget = null;
  703. // 本例验证离线表单归属;恢复连接是下一例的前置。tab 的旧 identity/session 不代表在线。
  704. await openSettingsSection("remoteDevices");
  705. await browser.waitUntil(
  706. () =>
  707. browser.execute((sourceId) => {
  708. const card = document.querySelector(`[data-source-server-card="${sourceId}"]`);
  709. if (card?.querySelector('[data-remote-connection-status="online"]')) return true;
  710. const connect = [...(card?.querySelectorAll<HTMLButtonElement>("button") ?? [])].find(
  711. (button) => !button.disabled && ["连接", "Connect"].includes(button.innerText.trim()),
  712. );
  713. connect?.click();
  714. return Boolean(connect);
  715. }, sourceServerId),
  716. { timeout: 30_000, timeoutMsg: `${CASE_MARKER}: 设备没有恢复在线,也没有可用连接入口` },
  717. );
  718. await $(
  719. `[data-source-server-card="${sourceServerId}"] [data-remote-connection-status="online"]`,
  720. ).waitForDisplayed({
  721. timeout: 120_000,
  722. timeoutMsg: `${CASE_MARKER}: sshd 恢复后,设备管理快照仍未在线`,
  723. });
  724. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, { timeout: 15_000 });
  725. await waitForRemoteTab({
  726. caseMarker: CASE_MARKER,
  727. expectedIdentity: remoteWorkspaceIdentity,
  728. expectedPath: remoteWorkspacePath,
  729. });
  730. });
  731. it("DSYNC-15-05 远端「用户」编辑钩子时设备离线,切到「本机 · 用户」不显示旧表单、本机钩子不变", async function () {
  732. this.timeout(15 * 60_000);
  733. expect(sourceServerId).toBeTruthy();
  734. const config = readSSHRuntimeConfig(CASE_MARKER);
  735. const remoteUserKey = `source-user:${sourceServerId}`;
  736. const remoteConfigPath = `${REMOTE_HOME}/.zcode/cli/config.json`;
  737. // 两台设备各有一个用户钩子:两边的 hook ID 都从 hook-zcode-user-0 编号,旧表单带到本机保存会覆盖本机这条。
  738. if (await $(`[data-testid="${TID_SETTINGS_PAGE}"]`).isExisting()) {
  739. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, { timeout: 15_000 });
  740. }
  741. await openSettingsSection("hooks");
  742. await selectScopeKey("user");
  743. await createUserHook(LOCAL_HOOK_MARKER);
  744. await browser.waitUntil(
  745. async () => (await readLocalUserConfigRaw()).includes(LOCAL_HOOK_MARKER),
  746. {
  747. timeout: 30_000,
  748. timeoutMsg: `${CASE_MARKER}: 本机没有写入钩子 ${LOCAL_HOOK_MARKER}`,
  749. },
  750. );
  751. await selectScopeKey(remoteUserKey);
  752. await createUserHook(REMOTE_HOOK_MARKER);
  753. await browser.waitUntil(
  754. async () =>
  755. (await remoteContainerPathExists(container, remoteConfigPath)) &&
  756. (await readRemoteContainerFile(container, remoteConfigPath)).includes(REMOTE_HOOK_MARKER),
  757. { timeout: 30_000, interval: 500, timeoutMsg: `${CASE_MARKER}: 远端没有写入钩子` },
  758. );
  759. const localHooksBefore = readHooksConfig(await readLocalUserConfigRaw());
  760. expect(JSON.stringify(localHooksBefore)).not.toContain(REMOTE_HOOK_MARKER);
  761. // 远端「用户」打开该钩子的编辑表单。
  762. await clickHookRow(REMOTE_HOOK_MARKER);
  763. await browser.waitUntil(async () => (await readHookFormArgs()) === REMOTE_HOOK_MARKER, {
  764. timeout: 30_000,
  765. timeoutMsg: `${CASE_MARKER}: 没有打开远端钩子的编辑表单`,
  766. });
  767. // 设备离线:表单隐藏,只显示离线提示(管理快照判定离线可能要几分钟)。
  768. offlineTarget = { host: config.host, port: config.port };
  769. await takeRemoteDeviceOffline(container);
  770. await browser.waitUntil(
  771. () =>
  772. browser.execute(() => Boolean(document.querySelector('[data-scope-blocked="offline"]'))),
  773. {
  774. timeout: 5 * 60_000,
  775. interval: 1_000,
  776. timeoutMsg: `${CASE_MARKER}: 设备离线后没有离线提示`,
  777. },
  778. );
  779. expect(await readHookFormArgs()).toBeNull();
  780. // 列表页切到「本机 · 用户」:显示本机列表,旧表单不出现,本机钩子不变。
  781. await selectScopeKey("user");
  782. await browser.waitUntil(
  783. async () =>
  784. (await readHookFormArgs()) !== null || (await isHookRowVisible(LOCAL_HOOK_MARKER)),
  785. {
  786. timeout: 60_000,
  787. interval: 500,
  788. timeoutMsg: `${CASE_MARKER}: 切到「本机 · 用户」后既没有本机列表也没有表单`,
  789. },
  790. );
  791. expect(await readHookFormArgs()).toBeNull();
  792. expect(await isHookRowVisible(LOCAL_HOOK_MARKER)).toBe(true);
  793. await browser.pause(1_000);
  794. expect(await readHookFormArgs()).toBeNull();
  795. expect(readHooksConfig(await readLocalUserConfigRaw())).toEqual(localHooksBefore);
  796. await bringRemoteDeviceOnline(container, offlineTarget);
  797. offlineTarget = null;
  798. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, { timeout: 15_000 });
  799. });
  800. });