conversation-session-memory.test.ts 34 KB

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