conversation-session-memory.test.ts 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  1. import { createHash } from "node:crypto";
  2. import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
  3. import { basename, dirname, join, resolve } from "node:path";
  4. import {
  5. TID_SETTINGS_BACK_BUTTON,
  6. TID_SETTINGS_MEMORY_COUNT,
  7. TID_SETTINGS_MEMORY_FILE,
  8. TID_SETTINGS_MEMORY_FILE_EDITOR_ACTIONS,
  9. TID_SETTINGS_MEMORY_FILE_ICON,
  10. TID_SETTINGS_MEMORY_FILE_NAME,
  11. TID_SETTINGS_MEMORY_FILE_UPDATED_AT,
  12. TID_SETTINGS_MEMORY_REFRESH,
  13. TID_SETTINGS_MEMORY_SCOPE_ICON,
  14. TID_SETTINGS_MEMORY_SCOPE_TRIGGER,
  15. TID_SETTINGS_MEMORY_SEARCH_CLEAR,
  16. TID_SETTINGS_MEMORY_SEARCH_INPUT,
  17. TID_SETTINGS_MEMORY_SWITCH,
  18. TID_SETTINGS_MEMORY_WORKSPACE,
  19. TID_SETTINGS_PAGE,
  20. TID_SETTINGS_SECTION_NAV,
  21. TID_TASK_SETTINGS_BUTTON,
  22. testId,
  23. } from "@zcode/shared/test-ids";
  24. import type { E2ENetworkCaptureArtifact } from "#e2e/helpers/network-capture-proxy";
  25. import {
  26. clearAppData,
  27. clickTestIdByDom,
  28. DEFAULT_WORKSPACE,
  29. getE2EAppDataPaths,
  30. readSettings,
  31. seedCliConfig,
  32. } from "#e2e/helpers/desktop-app";
  33. import { waitForUpstreamRequest } from "#e2e/helpers/conversation-session-network";
  34. import { ensureToolCrossProductFullAccessMode } from "#e2e/helpers/conversation-session-tool-cross-product";
  35. import {
  36. getV4PaneSnapshot,
  37. prepareV4ConversationE2E,
  38. sendV4Prompt,
  39. sendV4PromptAndWaitAccepted,
  40. startNewV4Draft,
  41. waitForV4Pane,
  42. waitForV4TimelineContaining,
  43. } from "#e2e/helpers/v4-conversation";
  44. const E2E_TIMEOUT_MS = 240_000;
  45. const DEFAULT_BRANCH_PROMPT = "E2E_MEMORY_WDIO_DEFAULT_BRANCH check";
  46. const EXTRACTION_PROMPT =
  47. "E2E_MEMORY_WDIO_EXTRACTION deployments require staging approval because release managers need an audit trail.";
  48. const EXTRACTED_DEFAULT_PROMPT = "E2E_MEMORY_WDIO_EXTRACTED_DEFAULT check";
  49. const CUSTOM_PROMPT =
  50. "E2E_MEMORY_WDIO_CUSTOM delegate this durable review convention to the memory curator.";
  51. const ACTIVE_AFTER_DISABLE_PROMPT = "E2E_MEMORY_WDIO_ACTIVE_AFTER_DISABLE";
  52. const DISABLED_PROMPT = "E2E_MEMORY_WDIO_DISABLED";
  53. const DEFAULT_BRANCH_DONE = "E2E_MEMORY_WDIO_DEFAULT_BRANCH_DONE";
  54. const EXTRACTION_DONE = "E2E_MEMORY_WDIO_EXTRACTION_DONE";
  55. const EXTRACTED_DEFAULT_DONE = "E2E_MEMORY_WDIO_EXTRACTED_DEFAULT_DONE";
  56. const CUSTOM_DONE = "E2E_MEMORY_WDIO_CUSTOM_DONE";
  57. const ACTIVE_AFTER_DISABLE_DONE = "E2E_MEMORY_WDIO_ACTIVE_AFTER_DISABLE_DONE";
  58. const DISABLED_DONE = "E2E_MEMORY_WDIO_DISABLED_DONE";
  59. const EXTRACTION_FILE_MARKER = "E2E_MEMORY_WDIO_EXTRACTION_FILE";
  60. const CUSTOM_FILE_MARKER = "E2E_MEMORY_WDIO_CUSTOM_FILE";
  61. const RELEVANT_MEMORY_MARKER = "Retrieved for possible relevance — use only if it actually applies";
  62. const SELECTOR_MARKER = "You are selecting memories that will be useful";
  63. const EXTRACTION_MARKER = "You are now acting as the memory extraction subagent";
  64. const CUSTOM_MEMORY_MARKER = "# Persistent Agent Memory";
  65. const MAIN_MEMORY_INDEX_POINTER =
  66. "After writing the file, add a one-line pointer in `MEMORY.md` (`- [Title](file.md) — hook`).";
  67. const MAIN_MEMORY_INDEX_SOURCE = "user's auto-memory, persists across conversations";
  68. const PROJECT_MEMORY_INDEX_CONTENT =
  69. "- [Database test policy](database-test-policy.md) — integration tests use isolated databases";
  70. const PROJECT_MEMORY_UPDATED_POINTER =
  71. "- [Deployment approval policy](deployment-approval-policy.md) — staging approval required";
  72. const PROJECT_MEMORY_UPDATED_INDEX_CONTENT = `${PROJECT_MEMORY_INDEX_CONTENT}\n${PROJECT_MEMORY_UPDATED_POINTER}`;
  73. const SECOND_PROJECT_MEMORY_INDEX_CONTENT =
  74. "- [Incident review policy](incident-review-policy.md) — preserve the original evidence";
  75. const REFRESHED_MEMORY_FACT_MARKER = "E2E_MEMORY_SETTINGS_REFRESHED_FACT";
  76. const MEMORY_ENABLED_MAIN_FIXTURES = [
  77. { id: "memory-window-default-branch-boundary", index: "initial" },
  78. { id: "memory-window-default-branch-final", index: "initial" },
  79. { id: "memory-window-extraction-main", index: "initial" },
  80. { id: "memory-window-extracted-default-main", index: "updated" },
  81. { id: "memory-window-custom-parent-agent", index: "updated" },
  82. { id: "memory-window-custom-parent-final", index: "updated" },
  83. { id: "memory-window-active-after-disable", index: "updated" },
  84. ] as const;
  85. const PROFILE_NAME = "memory-window-curator";
  86. const PROJECT_MEMORY_ROOT = resolveProjectMemoryRoot(DEFAULT_WORKSPACE);
  87. const PROJECT_MEMORY_INDEX = join(PROJECT_MEMORY_ROOT, "MEMORY.md");
  88. const EXISTING_FILE = join(PROJECT_MEMORY_ROOT, "database-test-policy.md");
  89. const EXTRACTED_FILE = join(PROJECT_MEMORY_ROOT, "deployment-approval-policy.md");
  90. const SECOND_PROJECT_MEMORY_WORKSPACE_LABEL =
  91. "secondary-project-with-an-intentionally-very-long-workspace-name";
  92. const SECOND_PROJECT_MEMORY_WORKSPACE_ID = `${SECOND_PROJECT_MEMORY_WORKSPACE_LABEL}-2222222222222222`;
  93. const SECOND_PROJECT_MEMORY_ROOT = join(
  94. getE2EAppDataPaths().storageRoot,
  95. "cli",
  96. "memories",
  97. "projects",
  98. SECOND_PROJECT_MEMORY_WORKSPACE_ID,
  99. "memory",
  100. );
  101. const SECOND_PROJECT_MEMORY_INDEX = join(SECOND_PROJECT_MEMORY_ROOT, "MEMORY.md");
  102. const SECOND_PROJECT_MEMORY_FACT = join(SECOND_PROJECT_MEMORY_ROOT, "incident-review-policy.md");
  103. const REFRESHED_FILE = join(SECOND_PROJECT_MEMORY_ROOT, "manual-refresh.md");
  104. const PROFILE_FILE = join(DEFAULT_WORKSPACE, ".zcode", "agents", `${PROFILE_NAME}.md`);
  105. const CUSTOM_MEMORY_ROOT = join(DEFAULT_WORKSPACE, ".zcode", "agent-memory", PROFILE_NAME);
  106. const CUSTOM_MEMORY_FILE = join(CUSTOM_MEMORY_ROOT, "review-convention.md");
  107. let providerCaptureStartIndex = 0;
  108. describe("Desktop Memory continuous 链路 WDIO", () => {
  109. before(async function () {
  110. this.timeout(E2E_TIMEOUT_MS);
  111. await seedMemoryFixtures();
  112. await seedCliConfig({ features: { memory: true }, memory: { use: true } });
  113. await prepareV4ConversationE2E();
  114. await ensureToolCrossProductFullAccessMode();
  115. // Bug 根因:replay capture 文件跨 WDIO spec/run 复用;按 fixtureId 全文件查找会把
  116. // 上一次同名 Memory 轨迹算进本次 proof。记录本 spec 的起始下标,只裁剪旧记录,
  117. // 保留本次每条 Main/Extraction 请求必须恰好一条的原有断言。
  118. providerCaptureStartIndex = (await readProviderCapture()).records.length;
  119. });
  120. after(async () => {
  121. await browser.electron.restoreAllMocks();
  122. await rm(PROJECT_MEMORY_ROOT, { force: true, recursive: true });
  123. await rm(SECOND_PROJECT_MEMORY_ROOT, { force: true, recursive: true });
  124. await rm(join(DEFAULT_WORKSPACE, ".zcode"), {
  125. force: true,
  126. recursive: true,
  127. });
  128. await clearAppData();
  129. });
  130. it("从真实窗口覆盖默认分支、Extraction、custom agent 和 disabled gate", async function () {
  131. this.timeout(E2E_TIMEOUT_MS);
  132. const telemetryFetch = await browser.electron.mock("net", "fetch");
  133. await telemetryFetch.mockResolvedValue({ ok: true, status: 204 });
  134. await openMemorySettings();
  135. expect(await readMemorySwitch()).toBe(false);
  136. expect((await readSettings()).memoryEnabled).toBe(false);
  137. expect(await hasTestId(TID_SETTINGS_MEMORY_REFRESH)).toBe(false);
  138. await closeSettings();
  139. await sendV4Prompt(DISABLED_PROMPT);
  140. await waitForV4TimelineContaining(DISABLED_DONE, 90_000);
  141. const initiallyDisabledSessionId = requireSessionId((await getV4PaneSnapshot()).sessionId);
  142. await expectMemoryTelemetry(telemetryFetch, initiallyDisabledSessionId, "0");
  143. await setMemoryEnabled(true, initiallyDisabledSessionId);
  144. await verifyMemorySettingsViewer(initiallyDisabledSessionId);
  145. // 修复原因:Settings 初始化会异步刷新内置 provider,并可能覆盖 case-local replay
  146. // 偏好;Memory 轨迹必须在设置操作结束后重新固定测试 provider 再创建 session。
  147. await prepareV4ConversationE2E();
  148. await ensureToolCrossProductFullAccessMode();
  149. // Memory 开关在 session 创建时冻结;完成默认关闭的初始 session 后新建启用 session。
  150. await startNewV4Draft();
  151. await sendV4Prompt(DEFAULT_BRANCH_PROMPT);
  152. await waitForV4TimelineContaining(DEFAULT_BRANCH_DONE, 90_000);
  153. const projectPane = await waitForV4Pane(
  154. (snapshot) =>
  155. Boolean(snapshot.sessionId) && snapshot.sessionId !== "draft" && !snapshot.canStop,
  156. "Memory default branch 完成后 pane 没有回到 idle",
  157. 90_000,
  158. );
  159. const projectSessionId = requireSessionId(projectPane.sessionId);
  160. await expectMemoryTelemetry(telemetryFetch, projectSessionId, "1");
  161. await waitForUpstreamRequest(
  162. { includes: [DEFAULT_BRANCH_PROMPT, "memory_default_branch_boundary"] },
  163. "Default Memory branch 的 Main continuation 未进入 provider capture",
  164. 60_000,
  165. );
  166. const existingContent = await readFile(EXISTING_FILE, "utf8");
  167. expect(existingContent).not.toContain("originSessionId:");
  168. await sendV4Prompt(EXTRACTION_PROMPT);
  169. await waitForV4TimelineContaining(EXTRACTION_DONE, 90_000);
  170. await waitForUpstreamRequest(
  171. { includes: [EXTRACTION_MARKER, EXTRACTION_PROMPT] },
  172. "Desktop 成功 turn 后未捕获后台 Extraction request",
  173. 60_000,
  174. );
  175. const extractedContent = await waitForFileContaining(EXTRACTED_FILE, EXTRACTION_FILE_MARKER);
  176. expect(extractedContent).toMatch(/^\s*node_type:\s*memory\s*$/mu);
  177. expect(readOriginSessionId(extractedContent)).toBe(projectSessionId);
  178. const updatedIndex = await waitForFileContaining(
  179. PROJECT_MEMORY_INDEX,
  180. PROJECT_MEMORY_UPDATED_POINTER,
  181. );
  182. expect(updatedIndex).toBe(`${PROJECT_MEMORY_UPDATED_INDEX_CONTENT}\n`);
  183. await startNewV4Draft();
  184. await ensureToolCrossProductFullAccessMode();
  185. await sendV4Prompt(EXTRACTED_DEFAULT_PROMPT);
  186. await waitForV4TimelineContaining(EXTRACTED_DEFAULT_DONE, 90_000);
  187. await waitForUpstreamRequest(
  188. {
  189. includes: [EXTRACTED_DEFAULT_PROMPT, "# Memory"],
  190. },
  191. "新 session 的 default Memory Main request 未进入 provider capture",
  192. 60_000,
  193. );
  194. await startNewV4Draft();
  195. await ensureToolCrossProductFullAccessMode();
  196. // 回归:新草稿模型检查曾回收在途预热,首发被误判为草稿切换;只点一次并确认 admission。
  197. await sendV4PromptAndWaitAccepted(
  198. CUSTOM_PROMPT,
  199. "E2E_MEMORY_WDIO_CUSTOM",
  200. "Memory 新草稿首次发送未被接收",
  201. );
  202. await waitForV4TimelineContaining(CUSTOM_DONE, 90_000);
  203. await waitForUpstreamRequest(
  204. {
  205. includes: [
  206. "E2E_MEMORY_WDIO_CUSTOM_CHILD",
  207. CUSTOM_MEMORY_MARKER,
  208. "Keep review findings evidence-first",
  209. ],
  210. },
  211. "custom agent persistent Memory prompt 未进入 provider capture",
  212. 60_000,
  213. );
  214. // 回归:Host 动态 profile 曾绕过 Memory 工具补齐;直接检查 child 最终 wire,不能只看完成文本。
  215. const customRequest = (await readProviderCapture()).records
  216. .slice(providerCaptureStartIndex)
  217. .find((record) => record.replay?.fixtureId === "memory-window-custom-child-write")
  218. ?.requestJson as { tools?: Array<{ name: string }> } | undefined;
  219. const customTools = customRequest?.tools?.map((tool) => tool.name);
  220. expect(customTools).toEqual(expect.arrayContaining(["Grep", "Write", "Edit"]));
  221. expect(customTools).not.toContain("Read");
  222. const customContent = await waitForFileContaining(CUSTOM_MEMORY_FILE, CUSTOM_FILE_MARKER);
  223. expect(customContent).toMatch(/^\s*node_type:\s*memory\s*$/mu);
  224. expect(readOriginSessionId(customContent)).toMatch(/^sess_subagent_/u);
  225. const activeMemorySessionId = requireSessionId((await getV4PaneSnapshot()).sessionId);
  226. await setMemoryEnabled(false, activeMemorySessionId);
  227. expect(await readFile(REFRESHED_FILE, "utf8")).toContain(REFRESHED_MEMORY_FACT_MARKER);
  228. await sendV4Prompt(ACTIVE_AFTER_DISABLE_PROMPT);
  229. await waitForV4TimelineContaining(ACTIVE_AFTER_DISABLE_DONE, 90_000);
  230. await waitForUpstreamRequest(
  231. { includes: [ACTIVE_AFTER_DISABLE_PROMPT, "# Memory"] },
  232. "Settings 关闭后当前 Session 不应热更新 Memory",
  233. 60_000,
  234. );
  235. expect(requireSessionId((await getV4PaneSnapshot()).sessionId)).toBe(activeMemorySessionId);
  236. await startNewV4Draft();
  237. await ensureToolCrossProductFullAccessMode();
  238. await sendV4Prompt(DISABLED_PROMPT);
  239. await waitForV4TimelineContaining(DISABLED_DONE, 90_000);
  240. await waitForV4Pane(
  241. (snapshot) => !snapshot.canStop,
  242. "Memory disabled turn 完成后 pane 没有回到 idle",
  243. 60_000,
  244. );
  245. const providerCapture = await readProviderCapture();
  246. const currentRunRecords = providerCapture.records.slice(providerCaptureStartIndex);
  247. const expectedMainMemory = (await readMainMemoryFixture()).replaceAll(
  248. "<MEMORY_ROOT>",
  249. PROJECT_MEMORY_ROOT,
  250. );
  251. const expectedMainMemoryIndex = (await readMainMemoryIndexFixture()).replaceAll(
  252. "<MEMORY_INDEX_PATH>",
  253. PROJECT_MEMORY_INDEX,
  254. );
  255. const expectedUpdatedMainMemoryIndex = expectedMainMemoryIndex.replace(
  256. PROJECT_MEMORY_INDEX_CONTENT,
  257. PROJECT_MEMORY_UPDATED_INDEX_CONTENT,
  258. );
  259. for (const fixture of MEMORY_ENABLED_MAIN_FIXTURES) {
  260. const matchingRequests = currentRunRecords.filter(
  261. (record) => record.replay?.fixtureId === fixture.id,
  262. );
  263. expect(matchingRequests).toHaveLength(1);
  264. const request = matchingRequests[0]!;
  265. expect(extractMainMemorySection(request.requestJson)).toBe(expectedMainMemory);
  266. expect(extractMainMemoryIndexContext(request.requestJson)).toBe(
  267. fixture.index === "initial" ? expectedMainMemoryIndex : expectedUpdatedMainMemoryIndex,
  268. );
  269. // 指令段不再带 `# agentsMd` 标题;以共享说明开头,见 meta-user-context.md。
  270. expect(countCaptureOccurrences(request.requestJson, "# agentsMd")).toBe(0);
  271. expect(countCaptureOccurrences(request.requestJson, "# claudeMd")).toBe(0);
  272. expect(countCaptureOccurrences(request.requestJson, MAIN_MEMORY_INDEX_POINTER)).toBe(1);
  273. }
  274. expect(
  275. currentRunRecords.some((record) => captureContains(record.requestJson, SELECTOR_MARKER)),
  276. ).toBe(false);
  277. expect(
  278. currentRunRecords.some((record) =>
  279. captureContains(record.requestJson, RELEVANT_MEMORY_MARKER),
  280. ),
  281. ).toBe(false);
  282. const disabledRequests = currentRunRecords.filter((record) =>
  283. captureContains(record.requestJson, DISABLED_PROMPT),
  284. );
  285. expect(
  286. disabledRequests.filter(
  287. (record) => record.replay?.fixtureId === "memory-window-disabled-main",
  288. ),
  289. ).toHaveLength(2);
  290. for (const request of disabledRequests) {
  291. expect(captureContains(request.requestJson, "# Memory")).toBe(false);
  292. expect(captureContains(request.requestJson, MAIN_MEMORY_INDEX_SOURCE)).toBe(false);
  293. expect(captureContains(request.requestJson, SELECTOR_MARKER)).toBe(false);
  294. expect(captureContains(request.requestJson, EXTRACTION_MARKER)).toBe(false);
  295. }
  296. expect(
  297. currentRunRecords.filter((record) => !record.replay?.fixtureId).map((record) => record.id),
  298. ).toEqual([]);
  299. const finalPane = await getV4PaneSnapshot();
  300. expect(finalPane.timelineText).toContain(DISABLED_DONE);
  301. });
  302. });
  303. async function openMemorySettings(): Promise<void> {
  304. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON, {
  305. timeout: 15_000,
  306. timeoutMsg: "没有找到设置入口按钮",
  307. });
  308. await browser.waitUntil(
  309. async () =>
  310. browser.execute(
  311. (settingsPageTestId) =>
  312. Boolean(document.querySelector(`[data-testid="${settingsPageTestId}"]`)),
  313. TID_SETTINGS_PAGE,
  314. ),
  315. { timeout: 15_000, timeoutMsg: "设置页没有打开" },
  316. );
  317. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "memory"), {
  318. timeout: 15_000,
  319. timeoutMsg: "设置页没有 Memory 分区入口",
  320. });
  321. await browser.waitUntil(async () => (await readMemorySwitch()) !== null, {
  322. timeout: 15_000,
  323. timeoutMsg: "Memory 设置没有开关",
  324. });
  325. }
  326. async function verifyMemorySettingsViewer(expectedSessionId: string): Promise<void> {
  327. // Bug 根因:首个 disabled turn 回到 idle 后,标题生成仍可能在后台排队;若此时
  328. // 记录 provider 数量,异步 title request 会被错误归因到 Settings 页面。先等该
  329. // case 自己的 title fixture 完成,再保留“打开 Settings 不发请求”的原断言。
  330. await waitForMemoryTitleRequest();
  331. const requestCountBefore = (await readProviderCapture()).records.length;
  332. await openMemorySettings();
  333. await waitForMemoryFile("MEMORY.md", "默认 Workspace Scope 没有显示 MEMORY.md");
  334. await waitForMemoryFile("database-test-policy.md", "默认 Workspace Scope 没有显示事实文件");
  335. expect(await hasTestId(testId(TID_SETTINGS_MEMORY_FILE, "incident-review-policy.md"))).toBe(
  336. false,
  337. );
  338. const initialScope = await readMemoryScopePresentation();
  339. expect(initialScope.hasFolderIcon).toBe(true);
  340. expect(initialScope.countText).toMatch(/2/u);
  341. const memoryIndex = await readMemoryFilePresentation("MEMORY.md");
  342. expect(memoryIndex.tagName).toBe("DIV");
  343. expect(memoryIndex.role).toBeNull();
  344. expect(memoryIndex.hasFileIcon).toBe(true);
  345. expect(memoryIndex.fileName).toBe("MEMORY.md");
  346. expect(memoryIndex.updatedAt).not.toBe("");
  347. expect(memoryIndex.hasEditorSlot).toBe(true);
  348. await openMemoryScopeMenu();
  349. expect(await countOpenMemoryScopeOptions()).toBe(2);
  350. await clickMemoryWorkspaceOption(SECOND_PROJECT_MEMORY_WORKSPACE_ID);
  351. await waitForMemoryFile("MEMORY.md", "第二个 Workspace Scope 没有显示 MEMORY.md");
  352. await waitForMemoryFile("incident-review-policy.md", "第二个 Workspace Scope 没有显示事实文件");
  353. expect(await hasTestId(testId(TID_SETTINGS_MEMORY_FILE, "database-test-policy.md"))).toBe(false);
  354. const secondScope = await readMemoryScopePresentation();
  355. expect(secondScope.hasFolderIcon).toBe(true);
  356. expect(secondScope.label).toContain(SECOND_PROJECT_MEMORY_WORKSPACE_LABEL);
  357. expect(secondScope.countText).toMatch(/2/u);
  358. await setMemorySearch("INCIDENT-REVIEW");
  359. await waitForMemoryFile(
  360. "incident-review-policy.md",
  361. "Memory 文件名搜索没有忽略大小写命中当前 Scope",
  362. );
  363. await waitForMemoryFileHidden("MEMORY.md", "Memory 文件名搜索没有过滤不匹配文件");
  364. await clearMemorySearch();
  365. await waitForMemoryFile("MEMORY.md", "清空 Memory 搜索后没有恢复完整文件列表");
  366. await writeFile(
  367. REFRESHED_FILE,
  368. `---\nname: manual-refresh\ndescription: Added while Settings is open.\nmetadata:\n type: reference\n---\n\n${REFRESHED_MEMORY_FACT_MARKER}\n`,
  369. "utf8",
  370. );
  371. expect(await hasTestId(testId(TID_SETTINGS_MEMORY_FILE, "manual-refresh.md"))).toBe(false);
  372. await clickTestIdByDom(TID_SETTINGS_MEMORY_REFRESH, {
  373. timeout: 15_000,
  374. timeoutMsg: "Project Memory viewer 没有刷新按钮",
  375. });
  376. await waitForMemoryFile("manual-refresh.md", "手动刷新后没有出现新增事实文件");
  377. expect(await hasTestId(testId(TID_SETTINGS_MEMORY_FILE, "database-test-policy.md"))).toBe(false);
  378. const refreshedScope = await readMemoryScopePresentation();
  379. expect(refreshedScope.label).toContain(SECOND_PROJECT_MEMORY_WORKSPACE_LABEL);
  380. expect(refreshedScope.countText).toMatch(/3/u);
  381. expect((await readProviderCapture()).records).toHaveLength(requestCountBefore);
  382. await closeSettings(expectedSessionId);
  383. }
  384. async function openMemoryScopeMenu(): Promise<void> {
  385. await browser.waitUntil(
  386. async () => {
  387. if ((await countOpenMemoryScopeOptions()) > 0) return true;
  388. await browser.execute((triggerTestId) => {
  389. const trigger = document.querySelector<HTMLElement>(`[data-testid="${triggerTestId}"]`);
  390. if (
  391. !(trigger instanceof HTMLButtonElement) ||
  392. trigger.disabled ||
  393. trigger.getAttribute("aria-expanded") === "true"
  394. ) {
  395. return;
  396. }
  397. // Bug 根因:普通 HTMLElement.click() 不会产生 Radix DropdownMenu 依赖的
  398. // pointerdown,而 WebDriver clickable 在 Linux Electron 容器会误判坐标。
  399. // 直接派发同语义 pointerdown,既绕开坐标又保留真实菜单打开边界。
  400. trigger.dispatchEvent(
  401. new PointerEvent("pointerdown", {
  402. bubbles: true,
  403. button: 0,
  404. buttons: 1,
  405. cancelable: true,
  406. isPrimary: true,
  407. pointerType: "mouse",
  408. }),
  409. );
  410. }, TID_SETTINGS_MEMORY_SCOPE_TRIGGER);
  411. return false;
  412. },
  413. {
  414. interval: 250,
  415. timeout: 15_000,
  416. timeoutMsg: "Project Memory Workspace Scope 菜单没有打开",
  417. },
  418. );
  419. }
  420. async function clickMemoryWorkspaceOption(workspaceId: string): Promise<void> {
  421. const optionTestId = testId(TID_SETTINGS_MEMORY_WORKSPACE, workspaceId);
  422. await clickTestIdByDom(optionTestId, {
  423. timeout: 15_000,
  424. timeoutMsg: `Project Memory Workspace Scope 没有显示 ${workspaceId}`,
  425. });
  426. }
  427. function countOpenMemoryScopeOptions(): Promise<number> {
  428. return browser.execute(
  429. (workspaceTestIdPrefix) =>
  430. document.querySelectorAll(`[data-testid^="${workspaceTestIdPrefix}"]`).length,
  431. TID_SETTINGS_MEMORY_WORKSPACE,
  432. );
  433. }
  434. function readMemoryScopePresentation(): Promise<{
  435. hasFolderIcon: boolean;
  436. label: string;
  437. countText: string;
  438. }> {
  439. return browser.execute(
  440. (scopeTriggerTestId) => {
  441. const trigger = document.querySelector<HTMLElement>(
  442. `[data-testid="${scopeTriggerTestId.trigger}"]`,
  443. );
  444. const count = document.querySelector<HTMLElement>(
  445. `[data-testid="${scopeTriggerTestId.count}"]`,
  446. );
  447. return {
  448. hasFolderIcon: Boolean(
  449. trigger?.querySelector(`[data-testid="${scopeTriggerTestId.icon}"]`),
  450. ),
  451. label: trigger?.textContent?.trim() ?? "",
  452. countText: count?.textContent?.trim() ?? "",
  453. };
  454. },
  455. {
  456. count: TID_SETTINGS_MEMORY_COUNT,
  457. icon: TID_SETTINGS_MEMORY_SCOPE_ICON,
  458. trigger: TID_SETTINGS_MEMORY_SCOPE_TRIGGER,
  459. },
  460. );
  461. }
  462. function readMemoryFilePresentation(fileName: string): Promise<{
  463. tagName: string | null;
  464. role: string | null;
  465. hasFileIcon: boolean;
  466. fileName: string;
  467. updatedAt: string;
  468. hasEditorSlot: boolean;
  469. }> {
  470. return browser.execute(
  471. (fileTestId) => {
  472. const file = document.querySelector<HTMLElement>(`[data-testid="${fileTestId.row}"]`);
  473. const queryChild = (childTestId: string) =>
  474. document.querySelector<HTMLElement>(`[data-testid="${childTestId}"]`);
  475. return {
  476. tagName: file?.tagName ?? null,
  477. role: file?.getAttribute("role") ?? null,
  478. hasFileIcon: Boolean(queryChild(fileTestId.icon)),
  479. fileName: queryChild(fileTestId.name)?.textContent?.trim() ?? "",
  480. updatedAt: queryChild(fileTestId.updatedAt)?.textContent?.trim() ?? "",
  481. hasEditorSlot: Boolean(queryChild(fileTestId.editorActions)),
  482. };
  483. },
  484. {
  485. editorActions: testId(TID_SETTINGS_MEMORY_FILE_EDITOR_ACTIONS, fileName),
  486. icon: testId(TID_SETTINGS_MEMORY_FILE_ICON, fileName),
  487. name: testId(TID_SETTINGS_MEMORY_FILE_NAME, fileName),
  488. row: testId(TID_SETTINGS_MEMORY_FILE, fileName),
  489. updatedAt: testId(TID_SETTINGS_MEMORY_FILE_UPDATED_AT, fileName),
  490. },
  491. );
  492. }
  493. async function setMemorySearch(value: string): Promise<void> {
  494. const applied = await browser.execute(
  495. ({ searchTestId, nextValue }) => {
  496. const search = document.querySelector<HTMLInputElement>(`[data-testid="${searchTestId}"]`);
  497. if (!search) return false;
  498. // 修复原因:WebDriver setValue 在 React 受控 search input 重渲染时偶发丢键;
  499. // 使用原生 value setter 并派发 input 事件,仍由产品 onChange 驱动筛选状态。
  500. const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;
  501. setter?.call(search, nextValue);
  502. search.dispatchEvent(new InputEvent("input", { bubbles: true, data: nextValue }));
  503. return search.value === nextValue;
  504. },
  505. { nextValue: value, searchTestId: TID_SETTINGS_MEMORY_SEARCH_INPUT },
  506. );
  507. expect(applied).toBe(true);
  508. }
  509. async function clearMemorySearch(): Promise<void> {
  510. await clickTestIdByDom(TID_SETTINGS_MEMORY_SEARCH_CLEAR, {
  511. timeout: 5_000,
  512. timeoutMsg: "Memory 文件名搜索没有清空按钮",
  513. });
  514. }
  515. async function waitForMemoryFile(fileName: string, timeoutMsg: string): Promise<void> {
  516. await browser.waitUntil(() => hasTestId(testId(TID_SETTINGS_MEMORY_FILE, fileName)), {
  517. timeout: 15_000,
  518. timeoutMsg,
  519. });
  520. }
  521. async function waitForMemoryFileHidden(fileName: string, timeoutMsg: string): Promise<void> {
  522. await browser.waitUntil(
  523. async () => !(await hasTestId(testId(TID_SETTINGS_MEMORY_FILE, fileName))),
  524. {
  525. timeout: 15_000,
  526. timeoutMsg,
  527. },
  528. );
  529. }
  530. function hasTestId(testIdValue: string): Promise<boolean> {
  531. return browser.execute(
  532. (currentTestId) => Boolean(document.querySelector(`[data-testid="${currentTestId}"]`)),
  533. testIdValue,
  534. );
  535. }
  536. async function closeSettings(expectedSessionId?: string): Promise<void> {
  537. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, {
  538. timeout: 15_000,
  539. timeoutMsg: "设置页返回按钮没有出现",
  540. });
  541. await waitForV4Pane(
  542. (snapshot) =>
  543. expectedSessionId ? snapshot.sessionId === expectedSessionId : snapshot.sessionId !== null,
  544. expectedSessionId
  545. ? `返回工作区后没有恢复 Session ${expectedSessionId}`
  546. : "返回工作区后 V4 pane 没有恢复",
  547. 30_000,
  548. );
  549. }
  550. async function setMemoryEnabled(enabled: boolean, expectedSessionId?: string): Promise<void> {
  551. await openMemorySettings();
  552. if ((await readMemorySwitch()) !== enabled) {
  553. await clickTestIdByDom(TID_SETTINGS_MEMORY_SWITCH, {
  554. timeout: 15_000,
  555. timeoutMsg: "Memory 开关不可点击",
  556. });
  557. }
  558. await browser.waitUntil(
  559. async () => {
  560. const checked = await readMemorySwitch();
  561. const persisted = (await readSettings()).memoryEnabled;
  562. return checked === enabled && persisted === enabled;
  563. },
  564. {
  565. timeout: 15_000,
  566. timeoutMsg: `Memory 设置没有持久化为 ${String(enabled)}`,
  567. },
  568. );
  569. await closeSettings(expectedSessionId);
  570. }
  571. function readMemorySwitch(): Promise<boolean | null> {
  572. return browser.execute((switchTestId) => {
  573. const control = document.querySelector<HTMLElement>(`[data-testid="${switchTestId}"]`);
  574. if (!control) return null;
  575. return (
  576. control.getAttribute("aria-checked") === "true" ||
  577. control.getAttribute("data-state") === "checked"
  578. );
  579. }, TID_SETTINGS_MEMORY_SWITCH);
  580. }
  581. async function seedMemoryFixtures() {
  582. await rm(PROJECT_MEMORY_ROOT, { force: true, recursive: true });
  583. await rm(SECOND_PROJECT_MEMORY_ROOT, { force: true, recursive: true });
  584. await mkdir(PROJECT_MEMORY_ROOT, { recursive: true });
  585. await writeFile(PROJECT_MEMORY_INDEX, `${PROJECT_MEMORY_INDEX_CONTENT}\n`, "utf8");
  586. await writeFile(
  587. EXISTING_FILE,
  588. `---
  589. name: database-test-policy
  590. description: Database tests must use the real database rather than mocks.
  591. metadata:
  592. type: feedback
  593. ---
  594. Use the real database for database tests; mocked database tests are not trusted.
  595. **Why:** A prior mocked test passed while production migration behavior failed.
  596. **How to apply:** Use the real database for database integration tests.
  597. `,
  598. "utf8",
  599. );
  600. await mkdir(SECOND_PROJECT_MEMORY_ROOT, { recursive: true });
  601. await writeFile(SECOND_PROJECT_MEMORY_INDEX, `${SECOND_PROJECT_MEMORY_INDEX_CONTENT}\n`, "utf8");
  602. await writeFile(
  603. SECOND_PROJECT_MEMORY_FACT,
  604. "---\nname: incident-review-policy\ndescription: Preserve original incident evidence.\nmetadata:\n type: reference\n---\n\nKeep the original incident evidence available for review.\n",
  605. "utf8",
  606. );
  607. await mkdir(dirname(PROFILE_FILE), { recursive: true });
  608. await writeFile(
  609. PROFILE_FILE,
  610. `---
  611. name: ${PROFILE_NAME}
  612. description: Maintain durable review conventions.
  613. memory: project
  614. tools: Grep
  615. maxTurns: 4
  616. ---
  617. Review and preserve durable collaboration guidance.
  618. `,
  619. "utf8",
  620. );
  621. await mkdir(CUSTOM_MEMORY_ROOT, { recursive: true });
  622. await writeFile(
  623. join(CUSTOM_MEMORY_ROOT, "MEMORY.md"),
  624. "- [Review convention](review-convention.md): Keep review findings evidence-first.\n",
  625. "utf8",
  626. );
  627. }
  628. function resolveProjectMemoryRoot(workspacePath: string) {
  629. const normalizedWorkspace = resolve(workspacePath);
  630. const key =
  631. process.platform === "win32" ? normalizedWorkspace.toLowerCase() : normalizedWorkspace;
  632. const hash = createHash("sha256").update(key).digest("hex").slice(0, 16);
  633. const slug = basename(normalizedWorkspace)
  634. .toLowerCase()
  635. .replace(/[^a-z0-9._-]+/gu, "-")
  636. .replace(/^-+|-+$/gu, "")
  637. .slice(0, 48);
  638. return join(
  639. getE2EAppDataPaths().storageRoot,
  640. "cli",
  641. "memories",
  642. "projects",
  643. `${slug || "project"}-${hash}`,
  644. "memory",
  645. );
  646. }
  647. async function waitForFileContaining(path: string, marker: string) {
  648. let latest = "";
  649. await browser.waitUntil(
  650. async () => {
  651. latest = await readFile(path, "utf8").catch(() => "");
  652. return latest.includes(marker);
  653. },
  654. {
  655. timeout: 60_000,
  656. timeoutMsg: `Memory 文件未出现 marker ${marker}; path=${path}; latest=${latest}`,
  657. },
  658. );
  659. return latest;
  660. }
  661. function readOriginSessionId(content: string) {
  662. const match = content.match(/^\s*originSessionId:\s*(\S+)\s*$/mu);
  663. if (!match?.[1]) throw new Error(`Memory 文件缺少 originSessionId:\n${content}`);
  664. return match[1];
  665. }
  666. function requireSessionId(sessionId: string | null) {
  667. if (!sessionId || sessionId === "draft") throw new Error(`无效 sessionId: ${sessionId}`);
  668. return sessionId;
  669. }
  670. async function readProviderCapture(): Promise<E2ENetworkCaptureArtifact> {
  671. const capturePath = process.env.E2E_PROVIDER_CAPTURE_PATH?.trim();
  672. if (!capturePath) throw new Error("E2E_PROVIDER_CAPTURE_PATH 未配置");
  673. return JSON.parse(await readFile(capturePath, "utf8")) as E2ENetworkCaptureArtifact;
  674. }
  675. async function waitForMemoryTitleRequest(): Promise<void> {
  676. await browser.waitUntil(
  677. async () => {
  678. const capture = await readProviderCapture();
  679. return capture.records.some(
  680. (record) =>
  681. record.replay?.fixtureId === "memory-window-title" && record.status === "complete",
  682. );
  683. },
  684. {
  685. timeout: 30_000,
  686. timeoutMsg: "Memory 首个 turn 的 title request 没有完成,无法稳定验证 Settings 不发请求",
  687. },
  688. );
  689. }
  690. async function readMainMemoryFixture(): Promise<string> {
  691. const content = normalizeTextFixtureLineEndings(
  692. await readFile(
  693. new URL(
  694. "../../../../../../apps/zcode-cli/packages/core/tests/fixtures/memory/main-memory-default-index.md",
  695. import.meta.url,
  696. ),
  697. "utf8",
  698. ),
  699. );
  700. return content.endsWith("\n") ? content.slice(0, -1) : content;
  701. }
  702. async function readMainMemoryIndexFixture(): Promise<string> {
  703. const content = normalizeTextFixtureLineEndings(
  704. await readFile(
  705. new URL(
  706. "../../../../../../apps/zcode-cli/packages/core/tests/fixtures/memory/main-memory-index.md",
  707. import.meta.url,
  708. ),
  709. "utf8",
  710. ),
  711. );
  712. return content.endsWith("\n") ? content.slice(0, -1) : content;
  713. }
  714. function normalizeTextFixtureLineEndings(content: string): string {
  715. // 修复原因:Windows runner 会把 Markdown fixture checkout 为 CRLF,而 provider-visible
  716. // Memory 由 join("\n") 生成 LF;逐字合同必须比较文本语义,不能把工作树行尾当成产品差异。
  717. return content.replace(/\r\n?/gu, "\n");
  718. }
  719. function extractMainMemorySection(requestJson: unknown): string {
  720. if (!requestJson || typeof requestJson !== "object" || Array.isArray(requestJson)) {
  721. throw new Error("provider request body must be an object");
  722. }
  723. const system = (requestJson as Record<string, unknown>).system;
  724. const dynamicBlock = captureTextValues(system).find((text) => text.includes("# Memory\n\n"));
  725. if (!dynamicBlock) throw new Error("provider request is missing the Main Memory section");
  726. const start = dynamicBlock.indexOf("# Memory\n\n");
  727. // 环境段已移到 user 公告;system 里 Memory 后面紧接 Context management。
  728. const end = dynamicBlock.indexOf("\n\n# Context management", start);
  729. if (end < 0) throw new Error("provider request is missing the Context management boundary");
  730. return dynamicBlock.slice(start, end);
  731. }
  732. function extractMainMemoryIndexContext(requestJson: unknown): string {
  733. if (!requestJson || typeof requestJson !== "object" || Array.isArray(requestJson)) {
  734. throw new Error("provider request body must be an object");
  735. }
  736. const messages = (requestJson as Record<string, unknown>).messages;
  737. const contextBlock = captureTextValues(messages).find((text) =>
  738. text.includes(MAIN_MEMORY_INDEX_SOURCE),
  739. );
  740. if (!contextBlock) throw new Error("provider request is missing the Main MEMORY.md source");
  741. const contextStart = contextBlock.indexOf("Codebase and user instructions are shown below.");
  742. const firstSourceStart = contextBlock.indexOf("\n\nContents of ", contextStart);
  743. const memorySourceStart = contextBlock.indexOf(
  744. `Contents of ${PROJECT_MEMORY_INDEX} (${MAIN_MEMORY_INDEX_SOURCE}):`,
  745. firstSourceStart,
  746. );
  747. // 日期是单独的公告块,指令段在本块的 reminder 结束处收尾。
  748. const contextEnd = contextBlock.indexOf("\n</system-reminder>", memorySourceStart);
  749. if (contextStart < 0 || firstSourceStart < 0 || memorySourceStart < 0 || contextEnd < 0) {
  750. throw new Error("provider request has an invalid Main MEMORY.md context boundary");
  751. }
  752. // 修复原因:Request User Context 可同时承载 AGENTS.md 与 AutoMem;Memory fixture
  753. // 保留共享说明,跳过可选的 AGENTS.md source,再逐字校验 AutoMem source。
  754. return `${contextBlock.slice(contextStart, firstSourceStart)}\n\n${contextBlock.slice(
  755. memorySourceStart,
  756. contextEnd,
  757. )}`;
  758. }
  759. function captureTextValues(value: unknown): string[] {
  760. if (typeof value === "string") return [value];
  761. if (Array.isArray(value)) return value.flatMap(captureTextValues);
  762. if (!value || typeof value !== "object") return [];
  763. return Object.values(value).flatMap(captureTextValues);
  764. }
  765. function captureContains(value: unknown, marker: string): boolean {
  766. if (typeof value === "string") return value.includes(marker);
  767. if (Array.isArray(value)) return value.some((item) => captureContains(item, marker));
  768. if (!value || typeof value !== "object") return false;
  769. return Object.values(value).some((item) => captureContains(item, marker));
  770. }
  771. function countCaptureOccurrences(value: unknown, marker: string): number {
  772. if (typeof value === "string") return value.split(marker).length - 1;
  773. if (Array.isArray(value)) {
  774. return value.reduce((total, item) => total + countCaptureOccurrences(item, marker), 0);
  775. }
  776. if (!value || typeof value !== "object") return 0;
  777. return Object.values(value).reduce(
  778. (total, item) => total + countCaptureOccurrences(item, marker),
  779. 0,
  780. );
  781. }
  782. /** 真实网络上报验证开关维度;后台 Extraction 的结果不影响该值。 */
  783. async function expectMemoryTelemetry(
  784. telemetryFetch: Awaited<ReturnType<typeof browser.electron.mock>>,
  785. sessionId: string,
  786. expected: "0" | "1",
  787. ): Promise<void> {
  788. let reports: Array<{ element_name: string; event_extra_detail: Record<string, unknown> }> = [];
  789. const events = ["send_btn", "message_completion", "agent_step"];
  790. await browser.waitUntil(
  791. async () => {
  792. await telemetryFetch.update();
  793. reports = telemetryFetch.mock.calls.flatMap(([input, init]) => {
  794. if (!String(input).includes("/api/v1/event/report")) return [];
  795. const body = (init as { body?: string } | undefined)?.body;
  796. if (!body) return [];
  797. const report = JSON.parse(body);
  798. return report.talk_id === sessionId && events.includes(report.element_name) ? [report] : [];
  799. });
  800. return events.every((name) => reports.some((report) => report.element_name === name));
  801. },
  802. { timeout: 15_000, timeoutMsg: "Memory 三类埋点未完整上报" },
  803. );
  804. for (const report of reports) expect(report.event_extra_detail.memory_enabled).toBe(expected);
  805. }