conversation-session-r3-settings-scopes.test.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. import { mkdir, writeFile } from "node:fs/promises";
  2. import { basename, join, resolve } from "node:path";
  3. import { parseRemoteWorkspaceIdentity, encodeCustomModelValue } from "@zcode/shared";
  4. import {
  5. TID_CHAT_MODEL_SELECT_GROUP,
  6. TID_CHAT_MODEL_SELECT_ITEM,
  7. TID_CHAT_MODEL_SELECT_TRIGGER,
  8. TID_CHAT_THOUGHT_LEVEL_SELECT_ITEM,
  9. TID_CHAT_THOUGHT_LEVEL_SELECT_TRIGGER,
  10. TID_SETTINGS_BACK_BUTTON,
  11. TID_SETTINGS_PAGE,
  12. TID_SETTINGS_SECTION_NAV,
  13. TID_SUBAGENT_ROW,
  14. TID_TASK_SETTINGS_BUTTON,
  15. testId,
  16. } from "@zcode/shared/test-ids";
  17. import { access } from "node:fs/promises";
  18. import {
  19. clearAppData,
  20. clickTestIdByDom,
  21. DEFAULT_WORKSPACE,
  22. waitForTestIdByDom,
  23. } from "#e2e/helpers/desktop-app";
  24. import { resolveE2EStorageRoot } from "#e2e/helpers/e2e-runtime-paths";
  25. import {
  26. clickOpenScopeMenuOption,
  27. readOpenScopeMenuOptions,
  28. } from "#e2e/helpers/settings-scope-menu";
  29. import {
  30. createSSHLifecycleProvider,
  31. SSH_LIFECYCLE_MODEL_ID,
  32. type SSHLifecycleProvider,
  33. } from "#e2e/helpers/ssh-remote-lifecycle";
  34. import {
  35. clickLastEnabledSSHDialogButton,
  36. fillSSHPasswordSettings,
  37. openSSHRemoteDialog,
  38. openSSHSourceDirectory,
  39. readHostProcesses,
  40. readSSHRuntimeConfig,
  41. prepareSSHConnectionPage,
  42. runSSHCommand,
  43. selectSSHRemoteDirectory,
  44. waitForRemoteTab,
  45. completeSSHProjectConnection,
  46. waitForSSHDirectoryStep,
  47. } from "#e2e/helpers/ssh-remote-p0";
  48. import { prepareV4ConversationE2E, startNewV4Draft } from "#e2e/helpers/v4-conversation";
  49. const CASE_MARKER = "E2E_R3_SETTINGS_SCOPES";
  50. const artifactDir = resolve(
  51. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/r3-settings-scopes",
  52. );
  53. const AGENT_NAME = "r3-remote-conversation-agent";
  54. const AGENT_NAME_PROJECT = "r3-remote-project-agent";
  55. const SUBAGENT_FORM_SELECTOR = `form:has(input[type="text"]):has([data-testid="${TID_CHAT_MODEL_SELECT_TRIGGER}"])`;
  56. const SECTIONS = ["skill", "mcp", "plugin", "hooks", "subagents", "memory", "general"] as const;
  57. async function openSettingsSection(section: string): Promise<void> {
  58. const onSettings = await browser.execute(
  59. (pageId) => Boolean(document.querySelector(`[data-testid="${pageId}"]`)),
  60. TID_SETTINGS_PAGE,
  61. );
  62. if (!onSettings) {
  63. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON, {
  64. timeout: 15_000,
  65. timeoutMsg: `${CASE_MARKER}: 没有设置入口`,
  66. });
  67. await waitForTestIdByDom(TID_SETTINGS_PAGE, {
  68. timeout: 15_000,
  69. timeoutMsg: `${CASE_MARKER}: 设置页没有渲染`,
  70. });
  71. }
  72. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, section), {
  73. timeout: 15_000,
  74. timeoutMsg: `${CASE_MARKER}: 设置页没有 ${section} 分区`,
  75. });
  76. const scopedSection = ["skill", "mcp", "plugin", "hooks", "subagents", "memory"].includes(
  77. section,
  78. );
  79. await browser.waitUntil(
  80. async () => (await $('[data-plugin-scope-trigger="true"]').isExisting()) === scopedSection,
  81. { timeout: 15_000, timeoutMsg: `${CASE_MARKER}: ${section} 分区的 scope 入口未就绪` },
  82. );
  83. }
  84. /** 读取当前分区的 scope 选择器可选项(Source/项目/User 等),没有 scope 选择器时返回 null。 */
  85. async function readScopeOptions(): Promise<{ current: string; options: string[] } | null> {
  86. const trigger = $('[data-plugin-scope-trigger="true"]');
  87. if (!(await trigger.isExisting())) return null;
  88. const current = (await trigger.getText()).trim();
  89. await trigger.click();
  90. await browser.waitUntil(
  91. () => browser.execute(() => document.querySelectorAll('[role="menuitemradio"]').length > 0),
  92. { timeout: 10_000, timeoutMsg: "scope-menu" },
  93. );
  94. // 项目在各设备的「项目」子菜单里,逐个打开后合并。
  95. const options = (await readOpenScopeMenuOptions()).map((option) => option.text);
  96. await browser.keys(["Escape"]);
  97. return { current, options };
  98. }
  99. /** 打开 scope 菜单(等待上一次菜单完全关闭,最多重试 3 次)。 */
  100. async function openScopeMenu(): Promise<void> {
  101. const trigger = $('[data-plugin-scope-trigger="true"]');
  102. await trigger.waitForClickable({ timeout: 15_000 });
  103. await browser
  104. .waitUntil(
  105. () => browser.execute(() => document.querySelectorAll('[role="menuitemradio"]').length === 0),
  106. { timeout: 10_000, timeoutMsg: `${CASE_MARKER}: 旧 scope 菜单没有关闭` },
  107. )
  108. .catch(() => undefined);
  109. for (let attempt = 0; attempt < 3; attempt += 1) {
  110. await trigger.click();
  111. const opened = await browser
  112. .waitUntil(
  113. () => browser.execute(() => document.querySelectorAll('[role="menuitemradio"]').length > 0),
  114. { timeout: 5_000, timeoutMsg: "scope-menu-open" },
  115. )
  116. .then(() => true)
  117. .catch(() => false);
  118. if (opened) return;
  119. await browser.pause(500);
  120. }
  121. throw new Error(`${CASE_MARKER}: scope 菜单打不开`);
  122. }
  123. async function createSubagent(name: string, providerId: string, modelId: string): Promise<void> {
  124. const newButton = $('button[aria-label="新建"], button[aria-label="New"]');
  125. await newButton.waitForClickable({ timeout: 15_000 });
  126. await newButton.click();
  127. const form = $(SUBAGENT_FORM_SELECTOR);
  128. await form.waitForDisplayed({ timeout: 15_000 });
  129. const inputs = await form.$$('input[type="text"]');
  130. await inputs[0]!.setValue(name);
  131. await inputs[1]!.setValue(`${CASE_MARKER} description`);
  132. await form.$("textarea").setValue(`${CASE_MARKER} system prompt for ${name}`);
  133. // 模型:与 settings-subagent E2E 同一路径(provider 分组 → 模型项),值为 encodeCustomModelValue。
  134. const model = encodeCustomModelValue(providerId, modelId);
  135. const itemTestId = testId(TID_CHAT_MODEL_SELECT_ITEM, model);
  136. const groupTestId = testId(TID_CHAT_MODEL_SELECT_GROUP, `registry-provider:${providerId}`);
  137. const trigger = form.$(`[data-testid="${TID_CHAT_MODEL_SELECT_TRIGGER}"]`);
  138. await trigger.waitForClickable({ timeout: 15_000 });
  139. await trigger.click();
  140. await browser.waitUntil(
  141. () =>
  142. browser.execute(
  143. (item, group) =>
  144. Boolean(
  145. document.querySelector(`[data-testid="${item}"]`) ||
  146. document.querySelector(`[data-testid="${group}"]`),
  147. ),
  148. itemTestId,
  149. groupTestId,
  150. ),
  151. { timeout: 15_000, timeoutMsg: `${CASE_MARKER}: Subagent 表单模型菜单没有 ${providerId}` },
  152. );
  153. await browser.execute(
  154. (item, group) => {
  155. if (document.querySelector(`[data-testid="${item}"]`)) return;
  156. const node = document.querySelector<HTMLElement>(`[data-testid="${group}"]`);
  157. if (!node) return;
  158. node.focus();
  159. for (const eventName of ["pointerenter", "mouseenter", "mousemove"])
  160. node.dispatchEvent(
  161. new MouseEvent(eventName, { bubbles: true, cancelable: true, view: window }),
  162. );
  163. node.click();
  164. },
  165. itemTestId,
  166. groupTestId,
  167. );
  168. await browser.waitUntil(
  169. () =>
  170. browser.execute(
  171. (item) => Boolean(document.querySelector(`[data-testid="${item}"]`)),
  172. itemTestId,
  173. ),
  174. { timeout: 15_000, timeoutMsg: `${CASE_MARKER}: 模型菜单没有出现 ${model}` },
  175. );
  176. await browser.execute(
  177. (item) => document.querySelector<HTMLElement>(`[data-testid="${item}"]`)?.click(),
  178. itemTestId,
  179. );
  180. await browser.waitUntil(
  181. async () => (await trigger.getAttribute("data-model-current-value")) === model,
  182. { timeout: 15_000, timeoutMsg: `${CASE_MARKER}: 模型控件没有切换到 ${model}` },
  183. );
  184. // 思考档位可选:产品 canSave 只校验"填了必须有效"(SubagentsSection
  185. // thoughtLevelInvalid),不要求非空。经 UI 流程种的自定义 openai 模型没有
  186. // reasoning 元数据(ProviderModelMetadataDialog 无该字段,与 store 直写版
  187. // seed 的 reasoningLevel:disabled 不同),档位控件可能不渲染或菜单无
  188. // disabled 项——均跳过,不影响提交;模型带档位时仍优先选 disabled。
  189. let levelSelected = false;
  190. const levelTrigger = form.$(`[data-testid="${TID_CHAT_THOUGHT_LEVEL_SELECT_TRIGGER}"]`);
  191. const levelTriggerClickable = await levelTrigger.waitForClickable({ timeout: 5_000 }).then(
  192. () => true,
  193. () => false,
  194. );
  195. for (let attempt = 0; attempt < 3 && levelTriggerClickable && !levelSelected; attempt += 1) {
  196. await levelTrigger.click();
  197. try {
  198. const item = $(`[data-testid="${testId(TID_CHAT_THOUGHT_LEVEL_SELECT_ITEM, "disabled")}"]`);
  199. await item.waitForClickable({ timeout: 3_000 });
  200. await item.click();
  201. levelSelected = true;
  202. } catch {
  203. await browser.keys(["Escape"]);
  204. }
  205. }
  206. // 等下拉菜单完全关闭再提交;提交后 8s 未关闭则再点一次(Radix 菜单退场期间的点击会被吞)。
  207. await browser
  208. .waitUntil(
  209. () =>
  210. browser.execute(
  211. () => !document.querySelector('[role="menu"][data-state="open"], [role="listbox"]'),
  212. ),
  213. { timeout: 5_000, timeoutMsg: "menus-closed" },
  214. )
  215. .catch(() => undefined);
  216. for (let attempt = 0; attempt < 3; attempt += 1) {
  217. // 先经 DOM requestSubmit 触发 onSubmit(不依赖按钮命中),再退回真实点击。
  218. const submitted = await browser.execute(
  219. (selector, attemptIndex) => {
  220. const formNode = document.querySelector<HTMLFormElement>(selector);
  221. if (!formNode) return "no-form";
  222. const button = formNode.querySelector<HTMLButtonElement>('button[type="submit"]');
  223. if (button?.disabled) return "disabled";
  224. if (attemptIndex === 0) {
  225. formNode.requestSubmit(button ?? undefined);
  226. return "requestSubmit";
  227. }
  228. button?.click();
  229. return "click";
  230. },
  231. SUBAGENT_FORM_SELECTOR,
  232. attempt,
  233. );
  234. void submitted;
  235. const closed = await browser
  236. .waitUntil(async () => !(await $(SUBAGENT_FORM_SELECTOR).isExisting()), {
  237. timeout: 20_000,
  238. timeoutMsg: "form-close",
  239. })
  240. .then(() => true)
  241. .catch(() => false);
  242. if (closed) break;
  243. }
  244. await browser
  245. .waitUntil(async () => !(await $(SUBAGENT_FORM_SELECTOR).isExisting()), {
  246. timeout: 5_000,
  247. timeoutMsg: `${CASE_MARKER}: Subagent 保存后表单没有关闭`,
  248. })
  249. .catch(async (error) => {
  250. const diagnostics = await browser.execute((selector) => {
  251. const formNode = document.querySelector<HTMLElement>(selector);
  252. const alerts = Array.from(
  253. document.querySelectorAll<HTMLElement>(
  254. '[role="alert"], [role="status"], [data-sonner-toast]',
  255. ),
  256. )
  257. .map((n) => (n.innerText ?? "").trim())
  258. .filter(Boolean);
  259. return {
  260. formText: (formNode?.innerText ?? "").replace(/\s+/gu, " ").slice(0, 600),
  261. alerts: alerts.slice(0, 5),
  262. submitDisabled:
  263. formNode?.querySelector<HTMLButtonElement>('button[type="submit"]')?.disabled ?? null,
  264. };
  265. }, SUBAGENT_FORM_SELECTOR);
  266. throw new Error(`${String(error)}; diagnostics=${JSON.stringify(diagnostics)}`);
  267. });
  268. await waitForTestIdByDom(testId(TID_SUBAGENT_ROW, name), {
  269. timeout: 15_000,
  270. timeoutMsg: `${CASE_MARKER}: Subagent 行没有出现: ${name}`,
  271. });
  272. }
  273. /** 同名 default 工作区必须按 identity 选择,不能用位置推断归属。 */
  274. async function selectScopeKey(key: string): Promise<void> {
  275. await openScopeMenu();
  276. await clickOpenScopeMenuOption(key, { timeoutMsg: `${CASE_MARKER}: scope 菜单没有 ${key}` });
  277. await browser.waitUntil(
  278. async () =>
  279. (await $('[data-plugin-scope-trigger="true"]').getAttribute("data-plugin-scope-key")) === key,
  280. { timeout: 15_000, timeoutMsg: CASE_MARKER + ": scope identity 未切换" },
  281. );
  282. }
  283. async function localFileExists(path: string, waitMs = 0): Promise<boolean> {
  284. const deadline = Date.now() + waitMs;
  285. for (;;) {
  286. try {
  287. await access(path);
  288. return true;
  289. } catch {
  290. if (Date.now() >= deadline) return false;
  291. await browser.pause(500);
  292. }
  293. }
  294. }
  295. describe(`${CASE_MARKER}: 远端 Source 在线时设置 scope 与子智能体落盘位置`, () => {
  296. let provider: SSHLifecycleProvider | null = null;
  297. const facts: Record<string, unknown> = {};
  298. after(async () => {
  299. await mkdir(artifactDir, { recursive: true });
  300. await writeFile(resolve(artifactDir, "settings-scopes.json"), JSON.stringify(facts, null, 2));
  301. await provider?.tunnel.close().catch(() => undefined);
  302. provider = null;
  303. await browser.electron.restoreAllMocks();
  304. await clearAppData();
  305. });
  306. it("R3A-DEV-06 远程项目 B 激活时默认选中该设备「用户」;「本机 · 用户」新建只落本机;项目 A/B scope 按 identity 分别落盘", async function () {
  307. this.timeout(30 * 60_000);
  308. const config = readSSHRuntimeConfig(CASE_MARKER);
  309. const [workspaceA, workspaceB] = config.workspacePaths;
  310. // 冷启动先等待并关闭引导页,再进入工作区;否则测试停在 onboarding,尚未触达设置。
  311. await prepareSSHConnectionPage(CASE_MARKER);
  312. await prepareV4ConversationE2E({ skipProvider: true });
  313. const initialHosts = await readHostProcesses();
  314. provider = await createSSHLifecycleProvider(config, CASE_MARKER, { tunnelUsername: "tunnel" });
  315. await runSSHCommand(
  316. config,
  317. `rm -f "$HOME/.zcode/agents/${AGENT_NAME}.md" "${workspaceA}/.zcode/agents/${AGENT_NAME_PROJECT}.md"`,
  318. );
  319. // Source 在线,先激活远程项目 B;远程无项目入口已退役。
  320. await startNewV4Draft();
  321. await openSSHRemoteDialog(CASE_MARKER);
  322. await fillSSHPasswordSettings(config);
  323. await clickLastEnabledSSHDialogButton(CASE_MARKER);
  324. // 全新容器首连必须经过“安装并继续”确认(inline 在 connecting 步);缺这一步
  325. // 安装确认悬挂,conversation 永不打开(0910 实锤:auth 成功 → probe INSTALLED=0
  326. // → 无后续 channel 活动,keepalive 吊 2min 至超时)。与 entry-attribution 同款。
  327. const conversation = await completeSSHProjectConnection(
  328. { ...config, workspacePaths: [workspaceB, workspaceA] },
  329. CASE_MARKER,
  330. );
  331. const sourceId =
  332. parseRemoteWorkspaceIdentity(conversation.workspaceIdentity!)?.sourceServerId ?? "";
  333. expect(sourceId).toBeTruthy();
  334. // 各分区都必须实际打开;可选项不能仅记录或吞掉失败。
  335. const scopesProjectB: Record<string, unknown> = {};
  336. for (const section of SECTIONS) {
  337. await openSettingsSection(section);
  338. const scopes = await readScopeOptions();
  339. scopesProjectB[section] = scopes;
  340. if (section === "general") {
  341. expect(scopes).toBeNull();
  342. } else if (section === "memory") {
  343. // 记忆按设备保存,只提供两端的用户开关,不伪造项目级开关。
  344. expect(scopes?.options).toHaveLength(2);
  345. expect(scopes?.options.every((option) => option.includes("用户"))).toBe(true);
  346. } else {
  347. expect(scopes?.options).toEqual(
  348. expect.arrayContaining([
  349. expect.stringContaining("用户"),
  350. expect.stringContaining(basename(workspaceB)),
  351. ]),
  352. );
  353. expect(scopes?.options).not.toContain(basename(workspaceA));
  354. }
  355. }
  356. facts.scopeOptionsForProjectB = scopesProjectB;
  357. // DEV-06(2026-10 数据同步票 15 修订):Scope 菜单按设备分组,远程 tab 默认选中该设备的「用户」;
  358. // 显式选「本机 · 用户」后新建只落本机。
  359. await openSettingsSection("subagents");
  360. await waitForTestIdByDom(testId(TID_SUBAGENT_ROW, "general-purpose"), { timeout: 30_000 });
  361. const subagentScopes = await readScopeOptions();
  362. facts.subagentScopesForProjectB = subagentScopes;
  363. expect(
  364. await $('[data-plugin-scope-trigger="true"]').getAttribute("data-plugin-scope-key"),
  365. ).toBe(`source-user:${sourceId}`);
  366. // 对照组:本机“用户”scope 新建 → 落本机 storage/agents(证明表单与模型选择路径正常)。
  367. await selectScopeKey("user");
  368. const localControlName = "r3-local-user-agent";
  369. await createSubagent(localControlName, provider.id, SSH_LIFECYCLE_MODEL_ID);
  370. facts.localControlFileExists = await localFileExists(
  371. join(resolveE2EStorageRoot(), "agents", `${localControlName}.md`),
  372. 15_000,
  373. );
  374. expect(facts.localControlFileExists).toBe(true);
  375. const remoteControlFile = await runSSHCommand(
  376. config,
  377. 'find "$HOME" -name "r3-local-user-agent.md" -print',
  378. );
  379. facts.remoteControlFiles = remoteControlFile.stdout.trim();
  380. expect(remoteControlFile.stdout.trim()).toBe("");
  381. // 项目 B 的 scope 必须落在自己的 workspace,不能冒充 Source User。
  382. await selectScopeKey(conversation.workspaceIdentity!);
  383. await createSubagent(AGENT_NAME, provider.id, SSH_LIFECYCLE_MODEL_ID);
  384. const remoteConversationFile = await runSSHCommand(
  385. config,
  386. `test -f "${conversation.workspacePath}/.zcode/agents/${AGENT_NAME}.md" && echo FOUND; test ! -f "$HOME/.zcode/agents/${AGENT_NAME}.md" && echo USER_UNCHANGED`,
  387. );
  388. facts.remoteConversationFile = remoteConversationFile.stdout.trim();
  389. expect(remoteConversationFile.stdout).toContain("FOUND");
  390. expect(remoteConversationFile.stdout).toContain("USER_UNCHANGED");
  391. expect(await localFileExists(join(resolveE2EStorageRoot(), "agents", AGENT_NAME + ".md"))).toBe(
  392. false,
  393. );
  394. facts.sourceUserCoverage = "未覆盖:显式 Source User 与 conversation workspace 分别验收";
  395. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, {
  396. timeout: 15_000,
  397. timeoutMsg: `${CASE_MARKER}: 设置页返回按钮没有出现`,
  398. });
  399. // 打开远端 project a → Subagents 选中项目 scope 新建 → 远端项目 .zcode/agents。
  400. await openSSHSourceDirectory(config, CASE_MARKER);
  401. expect(await waitForSSHDirectoryStep(CASE_MARKER)).toBe("directory");
  402. await selectSSHRemoteDirectory(workspaceA, CASE_MARKER);
  403. const project = await waitForRemoteTab({
  404. caseMarker: CASE_MARKER,
  405. expectedPath: workspaceA,
  406. timeoutMs: 120_000,
  407. });
  408. await openSettingsSection("subagents");
  409. await waitForTestIdByDom(testId(TID_SUBAGENT_ROW, "general-purpose"), { timeout: 30_000 });
  410. const subagentScopesWithProject = await readScopeOptions();
  411. facts.subagentScopesWithProject = subagentScopesWithProject;
  412. const projectScope =
  413. subagentScopesWithProject?.options.find((option) => option.includes(basename(workspaceA))) ??
  414. null;
  415. facts.projectScopeLabel = projectScope;
  416. expect(projectScope).toBeTruthy();
  417. await selectScopeKey(project.workspaceIdentity!);
  418. let projectScopeSaveError: string | null = null;
  419. await createSubagent(AGENT_NAME_PROJECT, provider.id, SSH_LIFECYCLE_MODEL_ID).catch(
  420. async (error) => {
  421. projectScopeSaveError = String(error).slice(0, 600);
  422. await browser.execute(() => {
  423. const cancel = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find(
  424. (b) => b.innerText.trim() === "取消" && b.getClientRects().length,
  425. );
  426. cancel?.click();
  427. });
  428. await browser.pause(500);
  429. },
  430. );
  431. facts.remoteProjectScopeSaveError = projectScopeSaveError;
  432. await browser.pause(3_000);
  433. const remoteProjectFile = await runSSHCommand(
  434. config,
  435. `test -f "${workspaceA}/.zcode/agents/${AGENT_NAME_PROJECT}.md" && echo FOUND || echo MISSING; find "$HOME/.zcode" "${workspaceA}" -name "${AGENT_NAME_PROJECT}.md" 2>/dev/null`,
  436. );
  437. facts.remoteProjectAgentFile = remoteProjectFile.stdout.trim().split("\n");
  438. facts.localProjectAgentFileExists = await localFileExists(
  439. join(DEFAULT_WORKSPACE, ".zcode", "agents", `${AGENT_NAME_PROJECT}.md`),
  440. );
  441. facts.localStorageProjectAgentFileExists = await localFileExists(
  442. join(resolveE2EStorageRoot(), "agents", `${AGENT_NAME_PROJECT}.md`),
  443. );
  444. expect(facts.localProjectAgentFileExists).toBe(false);
  445. // 其余分区在选中远端 project 时的 scope 选项。
  446. const scopesWithProject: Record<string, unknown> = {};
  447. for (const section of SECTIONS) {
  448. if (section === "subagents") continue;
  449. await openSettingsSection(section);
  450. const scopes = await readScopeOptions();
  451. scopesWithProject[section] = scopes;
  452. if (section === "general") {
  453. expect(scopes).toBeNull();
  454. } else if (section === "memory") {
  455. expect(scopes?.options).toHaveLength(2);
  456. expect(scopes?.options.every((option) => option.includes("用户"))).toBe(true);
  457. } else {
  458. expect(scopes?.options).toEqual(
  459. expect.arrayContaining([
  460. expect.stringContaining("用户"),
  461. expect.stringContaining(basename(workspaceA)),
  462. expect.stringContaining(basename(workspaceB)),
  463. ]),
  464. );
  465. }
  466. }
  467. facts.scopeOptionsWithProject = scopesWithProject;
  468. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, {
  469. timeout: 15_000,
  470. timeoutMsg: `${CASE_MARKER}: 设置页返回按钮没有出现`,
  471. });
  472. expect(await readHostProcesses()).toEqual(initialHosts);
  473. expect(facts.localStorageProjectAgentFileExists).toBe(false);
  474. expect(projectScopeSaveError).toBeNull();
  475. expect(remoteProjectFile.stdout).toContain("FOUND");
  476. });
  477. });