conversation-session-memory.test.ts 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871
  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\n"],
  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\n"] },
  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. // 只看 Memory 段标题;默认 prompt 总带 `# Memory, notes and feedback`,那一段不算 Memory 注入。
  292. expect(captureContains(request.requestJson, "# Memory\n")).toBe(false);
  293. expect(captureContains(request.requestJson, MAIN_MEMORY_INDEX_SOURCE)).toBe(false);
  294. expect(captureContains(request.requestJson, SELECTOR_MARKER)).toBe(false);
  295. expect(captureContains(request.requestJson, EXTRACTION_MARKER)).toBe(false);
  296. }
  297. expect(
  298. currentRunRecords.filter((record) => !record.replay?.fixtureId).map((record) => record.id),
  299. ).toEqual([]);
  300. const finalPane = await getV4PaneSnapshot();
  301. expect(finalPane.timelineText).toContain(DISABLED_DONE);
  302. });
  303. });
  304. async function openMemorySettings(): Promise<void> {
  305. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON, {
  306. timeout: 15_000,
  307. timeoutMsg: "没有找到设置入口按钮",
  308. });
  309. await browser.waitUntil(
  310. async () =>
  311. browser.execute(
  312. (settingsPageTestId) =>
  313. Boolean(document.querySelector(`[data-testid="${settingsPageTestId}"]`)),
  314. TID_SETTINGS_PAGE,
  315. ),
  316. { timeout: 15_000, timeoutMsg: "设置页没有打开" },
  317. );
  318. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "memory"), {
  319. timeout: 15_000,
  320. timeoutMsg: "设置页没有 Memory 分区入口",
  321. });
  322. await browser.waitUntil(async () => (await readMemorySwitch()) !== null, {
  323. timeout: 15_000,
  324. timeoutMsg: "Memory 设置没有开关",
  325. });
  326. }
  327. async function verifyMemorySettingsViewer(expectedSessionId: string): Promise<void> {
  328. // Bug 根因:首个 disabled turn 回到 idle 后,标题生成仍可能在后台排队;若此时
  329. // 记录 provider 数量,异步 title request 会被错误归因到 Settings 页面。先等该
  330. // case 自己的 title fixture 完成,再保留“打开 Settings 不发请求”的原断言。
  331. await waitForMemoryTitleRequest();
  332. const requestCountBefore = (await readProviderCapture()).records.length;
  333. await openMemorySettings();
  334. await waitForMemoryFile("MEMORY.md", "默认 Workspace Scope 没有显示 MEMORY.md");
  335. await waitForMemoryFile("database-test-policy.md", "默认 Workspace Scope 没有显示事实文件");
  336. expect(await hasTestId(testId(TID_SETTINGS_MEMORY_FILE, "incident-review-policy.md"))).toBe(
  337. false,
  338. );
  339. const initialScope = await readMemoryScopePresentation();
  340. expect(initialScope.hasFolderIcon).toBe(true);
  341. expect(initialScope.countText).toMatch(/2/u);
  342. const memoryIndex = await readMemoryFilePresentation("MEMORY.md");
  343. expect(memoryIndex.tagName).toBe("DIV");
  344. expect(memoryIndex.role).toBeNull();
  345. expect(memoryIndex.hasFileIcon).toBe(true);
  346. expect(memoryIndex.fileName).toBe("MEMORY.md");
  347. expect(memoryIndex.updatedAt).not.toBe("");
  348. expect(memoryIndex.hasEditorSlot).toBe(true);
  349. await openMemoryScopeMenu();
  350. expect(await countOpenMemoryScopeOptions()).toBe(2);
  351. await clickMemoryWorkspaceOption(SECOND_PROJECT_MEMORY_WORKSPACE_ID);
  352. await waitForMemoryFile("MEMORY.md", "第二个 Workspace Scope 没有显示 MEMORY.md");
  353. await waitForMemoryFile("incident-review-policy.md", "第二个 Workspace Scope 没有显示事实文件");
  354. expect(await hasTestId(testId(TID_SETTINGS_MEMORY_FILE, "database-test-policy.md"))).toBe(false);
  355. const secondScope = await readMemoryScopePresentation();
  356. expect(secondScope.hasFolderIcon).toBe(true);
  357. expect(secondScope.label).toContain(SECOND_PROJECT_MEMORY_WORKSPACE_LABEL);
  358. expect(secondScope.countText).toMatch(/2/u);
  359. await setMemorySearch("INCIDENT-REVIEW");
  360. await waitForMemoryFile(
  361. "incident-review-policy.md",
  362. "Memory 文件名搜索没有忽略大小写命中当前 Scope",
  363. );
  364. await waitForMemoryFileHidden("MEMORY.md", "Memory 文件名搜索没有过滤不匹配文件");
  365. await clearMemorySearch();
  366. await waitForMemoryFile("MEMORY.md", "清空 Memory 搜索后没有恢复完整文件列表");
  367. await writeFile(
  368. REFRESHED_FILE,
  369. `---\nname: manual-refresh\ndescription: Added while Settings is open.\nmetadata:\n type: reference\n---\n\n${REFRESHED_MEMORY_FACT_MARKER}\n`,
  370. "utf8",
  371. );
  372. expect(await hasTestId(testId(TID_SETTINGS_MEMORY_FILE, "manual-refresh.md"))).toBe(false);
  373. await clickTestIdByDom(TID_SETTINGS_MEMORY_REFRESH, {
  374. timeout: 15_000,
  375. timeoutMsg: "Project Memory viewer 没有刷新按钮",
  376. });
  377. await waitForMemoryFile("manual-refresh.md", "手动刷新后没有出现新增事实文件");
  378. expect(await hasTestId(testId(TID_SETTINGS_MEMORY_FILE, "database-test-policy.md"))).toBe(false);
  379. const refreshedScope = await readMemoryScopePresentation();
  380. expect(refreshedScope.label).toContain(SECOND_PROJECT_MEMORY_WORKSPACE_LABEL);
  381. expect(refreshedScope.countText).toMatch(/3/u);
  382. expect((await readProviderCapture()).records).toHaveLength(requestCountBefore);
  383. await closeSettings(expectedSessionId);
  384. }
  385. async function openMemoryScopeMenu(): Promise<void> {
  386. await browser.waitUntil(
  387. async () => {
  388. if ((await countOpenMemoryScopeOptions()) > 0) return true;
  389. await browser.execute((triggerTestId) => {
  390. const trigger = document.querySelector<HTMLElement>(`[data-testid="${triggerTestId}"]`);
  391. if (
  392. !(trigger instanceof HTMLButtonElement) ||
  393. trigger.disabled ||
  394. trigger.getAttribute("aria-expanded") === "true"
  395. ) {
  396. return;
  397. }
  398. // Bug 根因:普通 HTMLElement.click() 不会产生 Radix DropdownMenu 依赖的
  399. // pointerdown,而 WebDriver clickable 在 Linux Electron 容器会误判坐标。
  400. // 直接派发同语义 pointerdown,既绕开坐标又保留真实菜单打开边界。
  401. trigger.dispatchEvent(
  402. new PointerEvent("pointerdown", {
  403. bubbles: true,
  404. button: 0,
  405. buttons: 1,
  406. cancelable: true,
  407. isPrimary: true,
  408. pointerType: "mouse",
  409. }),
  410. );
  411. }, TID_SETTINGS_MEMORY_SCOPE_TRIGGER);
  412. return false;
  413. },
  414. {
  415. interval: 250,
  416. timeout: 15_000,
  417. timeoutMsg: "Project Memory Workspace Scope 菜单没有打开",
  418. },
  419. );
  420. }
  421. async function clickMemoryWorkspaceOption(workspaceId: string): Promise<void> {
  422. const optionTestId = testId(TID_SETTINGS_MEMORY_WORKSPACE, workspaceId);
  423. await clickTestIdByDom(optionTestId, {
  424. timeout: 15_000,
  425. timeoutMsg: `Project Memory Workspace Scope 没有显示 ${workspaceId}`,
  426. });
  427. }
  428. function countOpenMemoryScopeOptions(): Promise<number> {
  429. return browser.execute(
  430. (workspaceTestIdPrefix) =>
  431. document.querySelectorAll(`[data-testid^="${workspaceTestIdPrefix}"]`).length,
  432. TID_SETTINGS_MEMORY_WORKSPACE,
  433. );
  434. }
  435. function readMemoryScopePresentation(): Promise<{
  436. hasFolderIcon: boolean;
  437. label: string;
  438. countText: string;
  439. }> {
  440. return browser.execute(
  441. (scopeTriggerTestId) => {
  442. const trigger = document.querySelector<HTMLElement>(
  443. `[data-testid="${scopeTriggerTestId.trigger}"]`,
  444. );
  445. const count = document.querySelector<HTMLElement>(
  446. `[data-testid="${scopeTriggerTestId.count}"]`,
  447. );
  448. return {
  449. hasFolderIcon: Boolean(
  450. trigger?.querySelector(`[data-testid="${scopeTriggerTestId.icon}"]`),
  451. ),
  452. label: trigger?.textContent?.trim() ?? "",
  453. countText: count?.textContent?.trim() ?? "",
  454. };
  455. },
  456. {
  457. count: TID_SETTINGS_MEMORY_COUNT,
  458. icon: TID_SETTINGS_MEMORY_SCOPE_ICON,
  459. trigger: TID_SETTINGS_MEMORY_SCOPE_TRIGGER,
  460. },
  461. );
  462. }
  463. function readMemoryFilePresentation(fileName: string): Promise<{
  464. tagName: string | null;
  465. role: string | null;
  466. hasFileIcon: boolean;
  467. fileName: string;
  468. updatedAt: string;
  469. hasEditorSlot: boolean;
  470. }> {
  471. return browser.execute(
  472. (fileTestId) => {
  473. const file = document.querySelector<HTMLElement>(`[data-testid="${fileTestId.row}"]`);
  474. const queryChild = (childTestId: string) =>
  475. document.querySelector<HTMLElement>(`[data-testid="${childTestId}"]`);
  476. return {
  477. tagName: file?.tagName ?? null,
  478. role: file?.getAttribute("role") ?? null,
  479. hasFileIcon: Boolean(queryChild(fileTestId.icon)),
  480. fileName: queryChild(fileTestId.name)?.textContent?.trim() ?? "",
  481. updatedAt: queryChild(fileTestId.updatedAt)?.textContent?.trim() ?? "",
  482. hasEditorSlot: Boolean(queryChild(fileTestId.editorActions)),
  483. };
  484. },
  485. {
  486. editorActions: testId(TID_SETTINGS_MEMORY_FILE_EDITOR_ACTIONS, fileName),
  487. icon: testId(TID_SETTINGS_MEMORY_FILE_ICON, fileName),
  488. name: testId(TID_SETTINGS_MEMORY_FILE_NAME, fileName),
  489. row: testId(TID_SETTINGS_MEMORY_FILE, fileName),
  490. updatedAt: testId(TID_SETTINGS_MEMORY_FILE_UPDATED_AT, fileName),
  491. },
  492. );
  493. }
  494. async function setMemorySearch(value: string): Promise<void> {
  495. const applied = await browser.execute(
  496. ({ searchTestId, nextValue }) => {
  497. const search = document.querySelector<HTMLInputElement>(`[data-testid="${searchTestId}"]`);
  498. if (!search) return false;
  499. // 修复原因:WebDriver setValue 在 React 受控 search input 重渲染时偶发丢键;
  500. // 使用原生 value setter 并派发 input 事件,仍由产品 onChange 驱动筛选状态。
  501. const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;
  502. setter?.call(search, nextValue);
  503. search.dispatchEvent(new InputEvent("input", { bubbles: true, data: nextValue }));
  504. return search.value === nextValue;
  505. },
  506. { nextValue: value, searchTestId: TID_SETTINGS_MEMORY_SEARCH_INPUT },
  507. );
  508. expect(applied).toBe(true);
  509. }
  510. async function clearMemorySearch(): Promise<void> {
  511. await clickTestIdByDom(TID_SETTINGS_MEMORY_SEARCH_CLEAR, {
  512. timeout: 5_000,
  513. timeoutMsg: "Memory 文件名搜索没有清空按钮",
  514. });
  515. }
  516. async function waitForMemoryFile(fileName: string, timeoutMsg: string): Promise<void> {
  517. await browser.waitUntil(() => hasTestId(testId(TID_SETTINGS_MEMORY_FILE, fileName)), {
  518. timeout: 15_000,
  519. timeoutMsg,
  520. });
  521. }
  522. async function waitForMemoryFileHidden(fileName: string, timeoutMsg: string): Promise<void> {
  523. await browser.waitUntil(
  524. async () => !(await hasTestId(testId(TID_SETTINGS_MEMORY_FILE, fileName))),
  525. {
  526. timeout: 15_000,
  527. timeoutMsg,
  528. },
  529. );
  530. }
  531. function hasTestId(testIdValue: string): Promise<boolean> {
  532. return browser.execute(
  533. (currentTestId) => Boolean(document.querySelector(`[data-testid="${currentTestId}"]`)),
  534. testIdValue,
  535. );
  536. }
  537. async function closeSettings(expectedSessionId?: string): Promise<void> {
  538. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, {
  539. timeout: 15_000,
  540. timeoutMsg: "设置页返回按钮没有出现",
  541. });
  542. await waitForV4Pane(
  543. (snapshot) =>
  544. expectedSessionId ? snapshot.sessionId === expectedSessionId : snapshot.sessionId !== null,
  545. expectedSessionId
  546. ? `返回工作区后没有恢复 Session ${expectedSessionId}`
  547. : "返回工作区后 V4 pane 没有恢复",
  548. 30_000,
  549. );
  550. }
  551. async function setMemoryEnabled(enabled: boolean, expectedSessionId?: string): Promise<void> {
  552. await openMemorySettings();
  553. if ((await readMemorySwitch()) !== enabled) {
  554. await clickTestIdByDom(TID_SETTINGS_MEMORY_SWITCH, {
  555. timeout: 15_000,
  556. timeoutMsg: "Memory 开关不可点击",
  557. });
  558. }
  559. await browser.waitUntil(
  560. async () => {
  561. const checked = await readMemorySwitch();
  562. const persisted = (await readSettings()).memoryEnabled;
  563. return checked === enabled && persisted === enabled;
  564. },
  565. {
  566. timeout: 15_000,
  567. timeoutMsg: `Memory 设置没有持久化为 ${String(enabled)}`,
  568. },
  569. );
  570. await closeSettings(expectedSessionId);
  571. }
  572. function readMemorySwitch(): Promise<boolean | null> {
  573. return browser.execute((switchTestId) => {
  574. const control = document.querySelector<HTMLElement>(`[data-testid="${switchTestId}"]`);
  575. if (!control) return null;
  576. return (
  577. control.getAttribute("aria-checked") === "true" ||
  578. control.getAttribute("data-state") === "checked"
  579. );
  580. }, TID_SETTINGS_MEMORY_SWITCH);
  581. }
  582. async function seedMemoryFixtures() {
  583. await rm(PROJECT_MEMORY_ROOT, { force: true, recursive: true });
  584. await rm(SECOND_PROJECT_MEMORY_ROOT, { force: true, recursive: true });
  585. await mkdir(PROJECT_MEMORY_ROOT, { recursive: true });
  586. await writeFile(PROJECT_MEMORY_INDEX, `${PROJECT_MEMORY_INDEX_CONTENT}\n`, "utf8");
  587. await writeFile(
  588. EXISTING_FILE,
  589. `---
  590. name: database-test-policy
  591. description: Database tests must use the real database rather than mocks.
  592. metadata:
  593. type: feedback
  594. ---
  595. Use the real database for database tests; mocked database tests are not trusted.
  596. **Why:** A prior mocked test passed while production migration behavior failed.
  597. **How to apply:** Use the real database for database integration tests.
  598. `,
  599. "utf8",
  600. );
  601. await mkdir(SECOND_PROJECT_MEMORY_ROOT, { recursive: true });
  602. await writeFile(SECOND_PROJECT_MEMORY_INDEX, `${SECOND_PROJECT_MEMORY_INDEX_CONTENT}\n`, "utf8");
  603. await writeFile(
  604. SECOND_PROJECT_MEMORY_FACT,
  605. "---\nname: incident-review-policy\ndescription: Preserve original incident evidence.\nmetadata:\n type: reference\n---\n\nKeep the original incident evidence available for review.\n",
  606. "utf8",
  607. );
  608. await mkdir(dirname(PROFILE_FILE), { recursive: true });
  609. await writeFile(
  610. PROFILE_FILE,
  611. `---
  612. name: ${PROFILE_NAME}
  613. description: Maintain durable review conventions.
  614. memory: project
  615. tools: Grep
  616. maxTurns: 4
  617. ---
  618. Review and preserve durable collaboration guidance.
  619. `,
  620. "utf8",
  621. );
  622. await mkdir(CUSTOM_MEMORY_ROOT, { recursive: true });
  623. await writeFile(
  624. join(CUSTOM_MEMORY_ROOT, "MEMORY.md"),
  625. "- [Review convention](review-convention.md): Keep review findings evidence-first.\n",
  626. "utf8",
  627. );
  628. }
  629. function resolveProjectMemoryRoot(workspacePath: string) {
  630. const normalizedWorkspace = resolve(workspacePath);
  631. const key =
  632. process.platform === "win32" ? normalizedWorkspace.toLowerCase() : normalizedWorkspace;
  633. const hash = createHash("sha256").update(key).digest("hex").slice(0, 16);
  634. const slug = basename(normalizedWorkspace)
  635. .toLowerCase()
  636. .replace(/[^a-z0-9._-]+/gu, "-")
  637. .replace(/^-+|-+$/gu, "")
  638. .slice(0, 48);
  639. return join(
  640. getE2EAppDataPaths().storageRoot,
  641. "cli",
  642. "memories",
  643. "projects",
  644. `${slug || "project"}-${hash}`,
  645. "memory",
  646. );
  647. }
  648. async function waitForFileContaining(path: string, marker: string) {
  649. let latest = "";
  650. await browser.waitUntil(
  651. async () => {
  652. latest = await readFile(path, "utf8").catch(() => "");
  653. return latest.includes(marker);
  654. },
  655. {
  656. timeout: 60_000,
  657. timeoutMsg: `Memory 文件未出现 marker ${marker}; path=${path}; latest=${latest}`,
  658. },
  659. );
  660. return latest;
  661. }
  662. function readOriginSessionId(content: string) {
  663. const match = content.match(/^\s*originSessionId:\s*(\S+)\s*$/mu);
  664. if (!match?.[1]) throw new Error(`Memory 文件缺少 originSessionId:\n${content}`);
  665. return match[1];
  666. }
  667. function requireSessionId(sessionId: string | null) {
  668. if (!sessionId || sessionId === "draft") throw new Error(`无效 sessionId: ${sessionId}`);
  669. return sessionId;
  670. }
  671. async function readProviderCapture(): Promise<E2ENetworkCaptureArtifact> {
  672. const capturePath = process.env.E2E_PROVIDER_CAPTURE_PATH?.trim();
  673. if (!capturePath) throw new Error("E2E_PROVIDER_CAPTURE_PATH 未配置");
  674. return JSON.parse(await readFile(capturePath, "utf8")) as E2ENetworkCaptureArtifact;
  675. }
  676. async function waitForMemoryTitleRequest(): Promise<void> {
  677. await browser.waitUntil(
  678. async () => {
  679. const capture = await readProviderCapture();
  680. return capture.records.some(
  681. (record) =>
  682. record.replay?.fixtureId === "memory-window-title" && record.status === "complete",
  683. );
  684. },
  685. {
  686. timeout: 30_000,
  687. timeoutMsg: "Memory 首个 turn 的 title request 没有完成,无法稳定验证 Settings 不发请求",
  688. },
  689. );
  690. }
  691. async function readMainMemoryFixture(): Promise<string> {
  692. const content = normalizeTextFixtureLineEndings(
  693. await readFile(
  694. new URL(
  695. "../../../../../../apps/zcode-cli/packages/core/tests/fixtures/memory/main-memory-default-index.md",
  696. import.meta.url,
  697. ),
  698. "utf8",
  699. ),
  700. );
  701. return content.endsWith("\n") ? content.slice(0, -1) : content;
  702. }
  703. async function readMainMemoryIndexFixture(): Promise<string> {
  704. const content = normalizeTextFixtureLineEndings(
  705. await readFile(
  706. new URL(
  707. "../../../../../../apps/zcode-cli/packages/core/tests/fixtures/memory/main-memory-index.md",
  708. import.meta.url,
  709. ),
  710. "utf8",
  711. ),
  712. );
  713. return content.endsWith("\n") ? content.slice(0, -1) : content;
  714. }
  715. function normalizeTextFixtureLineEndings(content: string): string {
  716. // 修复原因:Windows runner 会把 Markdown fixture checkout 为 CRLF,而 provider-visible
  717. // Memory 由 join("\n") 生成 LF;逐字合同必须比较文本语义,不能把工作树行尾当成产品差异。
  718. return content.replace(/\r\n?/gu, "\n");
  719. }
  720. function extractMainMemorySection(requestJson: unknown): string {
  721. if (!requestJson || typeof requestJson !== "object" || Array.isArray(requestJson)) {
  722. throw new Error("provider request body must be an object");
  723. }
  724. const system = (requestJson as Record<string, unknown>).system;
  725. const dynamicBlock = captureTextValues(system).find((text) => text.includes("# Memory\n\n"));
  726. if (!dynamicBlock) throw new Error("provider request is missing the Main Memory section");
  727. const start = dynamicBlock.indexOf("# Memory\n\n");
  728. // 环境段已移到 user 公告;system 里 Memory 后面紧接 Context management。
  729. const end = dynamicBlock.indexOf("\n\n# Context management", start);
  730. if (end < 0) throw new Error("provider request is missing the Context management boundary");
  731. return dynamicBlock.slice(start, end);
  732. }
  733. function extractMainMemoryIndexContext(requestJson: unknown): string {
  734. if (!requestJson || typeof requestJson !== "object" || Array.isArray(requestJson)) {
  735. throw new Error("provider request body must be an object");
  736. }
  737. const messages = (requestJson as Record<string, unknown>).messages;
  738. const contextBlock = captureTextValues(messages).find((text) =>
  739. text.includes(MAIN_MEMORY_INDEX_SOURCE),
  740. );
  741. if (!contextBlock) throw new Error("provider request is missing the Main MEMORY.md source");
  742. const contextStart = contextBlock.indexOf("Codebase and user instructions are shown below.");
  743. const firstSourceStart = contextBlock.indexOf("\n\nContents of ", contextStart);
  744. const memorySourceStart = contextBlock.indexOf(
  745. `Contents of ${PROJECT_MEMORY_INDEX} (${MAIN_MEMORY_INDEX_SOURCE}):`,
  746. firstSourceStart,
  747. );
  748. // 日期是单独的公告块,指令段在本块的 reminder 结束处收尾。
  749. const contextEnd = contextBlock.indexOf("\n</system-reminder>", memorySourceStart);
  750. if (contextStart < 0 || firstSourceStart < 0 || memorySourceStart < 0 || contextEnd < 0) {
  751. throw new Error("provider request has an invalid Main MEMORY.md context boundary");
  752. }
  753. // 修复原因:Request User Context 可同时承载 AGENTS.md 与 AutoMem;Memory fixture
  754. // 保留共享说明,跳过可选的 AGENTS.md source,再逐字校验 AutoMem source。
  755. return `${contextBlock.slice(contextStart, firstSourceStart)}\n\n${contextBlock.slice(
  756. memorySourceStart,
  757. contextEnd,
  758. )}`;
  759. }
  760. function captureTextValues(value: unknown): string[] {
  761. if (typeof value === "string") return [value];
  762. if (Array.isArray(value)) return value.flatMap(captureTextValues);
  763. if (!value || typeof value !== "object") return [];
  764. return Object.values(value).flatMap(captureTextValues);
  765. }
  766. function captureContains(value: unknown, marker: string): boolean {
  767. if (typeof value === "string") return value.includes(marker);
  768. if (Array.isArray(value)) return value.some((item) => captureContains(item, marker));
  769. if (!value || typeof value !== "object") return false;
  770. return Object.values(value).some((item) => captureContains(item, marker));
  771. }
  772. function countCaptureOccurrences(value: unknown, marker: string): number {
  773. if (typeof value === "string") return value.split(marker).length - 1;
  774. if (Array.isArray(value)) {
  775. return value.reduce((total, item) => total + countCaptureOccurrences(item, marker), 0);
  776. }
  777. if (!value || typeof value !== "object") return 0;
  778. return Object.values(value).reduce(
  779. (total, item) => total + countCaptureOccurrences(item, marker),
  780. 0,
  781. );
  782. }
  783. /** 真实网络上报验证开关维度;后台 Extraction 的结果不影响该值。 */
  784. async function expectMemoryTelemetry(
  785. telemetryFetch: Awaited<ReturnType<typeof browser.electron.mock>>,
  786. sessionId: string,
  787. expected: "0" | "1",
  788. ): Promise<void> {
  789. let reports: Array<{ element_name: string; event_extra_detail: Record<string, unknown> }> = [];
  790. const events = ["send_btn", "message_completion", "agent_step"];
  791. await browser.waitUntil(
  792. async () => {
  793. await telemetryFetch.update();
  794. reports = telemetryFetch.mock.calls.flatMap(([input, init]) => {
  795. if (!String(input).includes("/api/v1/event/report")) return [];
  796. const body = (init as { body?: string } | undefined)?.body;
  797. if (!body) return [];
  798. const report = JSON.parse(body);
  799. return report.talk_id === sessionId && events.includes(report.element_name) ? [report] : [];
  800. });
  801. return events.every((name) => reports.some((report) => report.element_name === name));
  802. },
  803. { timeout: 15_000, timeoutMsg: "Memory 三类埋点未完整上报" },
  804. );
  805. for (const report of reports) expect(report.event_extra_detail.memory_enabled).toBe(expected);
  806. }