conversation-session-context-window-cold-resume.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. import { DEFAULT_WORKSPACE } from "#e2e/helpers/desktop-app";
  2. import { openWorkspaceDraftFromSidebar } from "#e2e/helpers/workspace-agent-warmup";
  3. import { readdir, readFile } from "node:fs/promises";
  4. import { join } from "node:path";
  5. import { DatabaseSync } from "node:sqlite";
  6. import { restartIntoWorkspacePreservingProfile as restartWithFixture } from "#e2e/helpers/model-provider-restart-runtime";
  7. import {
  8. TID_V4_COMPOSER_INPUT,
  9. TID_V4_MODEL_CONFIG,
  10. TID_V4_SESSION_PANE,
  11. testId,
  12. } from "@zcode/shared/test-ids";
  13. import {
  14. clearAppData,
  15. getE2EAppDataPaths,
  16. setInputValueByTestIdDom,
  17. waitForDefaultWorkspaceReady,
  18. } from "#e2e/helpers/desktop-app";
  19. import {
  20. restartIntoWorkspacePreservingProfile,
  21. waitForSelectedModel,
  22. } from "#e2e/helpers/model-provider-restart";
  23. import {
  24. CONTEXT_WINDOW_COLD_RESUME_MAX_TOKENS,
  25. CONTEXT_WINDOW_COLD_RESUME_MAX_OUTPUT_TOKENS,
  26. CONTEXT_WINDOW_COLD_RESUME_MODEL_ID,
  27. CONTEXT_WINDOW_COLD_RESUME_PROVIDER_ID,
  28. } from "#e2e/helpers/provider-readiness-history-fixture";
  29. import {
  30. clickV4Send,
  31. getV4CompactMarkers,
  32. getV4ConfigProjection,
  33. selectV4TaskById,
  34. sendV4Prompt,
  35. V4_MAIN_PANE_ID,
  36. waitForV4CompactMarker,
  37. waitForV4Pane,
  38. waitForV4TimelineContaining,
  39. } from "#e2e/helpers/v4-conversation";
  40. const PROVIDER_ID = CONTEXT_WINDOW_COLD_RESUME_PROVIDER_ID;
  41. const MODEL_ID = CONTEXT_WINDOW_COLD_RESUME_MODEL_ID;
  42. const CONTEXT_WINDOW = CONTEXT_WINDOW_COLD_RESUME_MAX_TOKENS;
  43. const MAX_OUTPUT_TOKENS = CONTEXT_WINDOW_COLD_RESUME_MAX_OUTPUT_TOKENS;
  44. const HIGH_USAGE_INPUT_TOKENS = 157_762;
  45. const TOOL_CALL_ID = "call_cw_pwd";
  46. const CREATE_HISTORY_MARKER = "E2E_CW_CREATE_HISTORY";
  47. const CREATE_HISTORY_REPLY = "cw-history-created-ok";
  48. const PARKING_MARKER = "E2E_CW_PARKING";
  49. const PARKING_REPLY = "cw-parking-ok";
  50. const HIGH_USAGE_MARKER = "E2E_CW_HIGH_USAGE_TOOL";
  51. const TOOL_FOLLOWUP_REPLY = "cw-tool-followup-ok";
  52. const CONTINUE_REPLY = "cw-continue-ok";
  53. const paths = getE2EAppDataPaths();
  54. describe("上下文窗口与输出预算冷恢复 E2E", () => {
  55. after(async () => {
  56. await browser.electron.restoreAllMocks();
  57. await clearAppData();
  58. });
  59. it("CW01-CW04: 1M/64K 会话冷恢复 limits 正确,compact 后重启保持压缩后水位", async function () {
  60. this.timeout(360_000);
  61. await waitForDefaultWorkspaceReady(30_000);
  62. await waitForSelectedModel(PROVIDER_ID, MODEL_ID);
  63. // 先通过真实 UI/协议创建并完成 1M 会话;再创建一个 parking 会话保持选中,
  64. // 这样重启后目标会话尚未 resume,可在点击前安装首投影记录器。
  65. // 启动夹具已经是目标目录的空草稿,直接首发,避免无意义地替换预热中的草稿。
  66. await sendV4Prompt(CREATE_HISTORY_MARKER);
  67. await waitForV4TimelineContaining(CREATE_HISTORY_REPLY);
  68. const targetSessionId = await waitForBoundSession("真实 1M 历史会话没有创建成功");
  69. // 冷恢复夹具固定在项目目录;全局新建会创建独立 cwd,不能复用该目录的记录器。
  70. await openWorkspaceDraftFromSidebar(DEFAULT_WORKSPACE);
  71. await sendV4Prompt(PARKING_MARKER);
  72. await waitForV4TimelineContaining(PARKING_REPLY);
  73. const parkingSessionId = await waitForBoundSession("parking 会话没有创建成功");
  74. expect(parkingSessionId).not.toBe(targetSessionId);
  75. await restartIntoWorkspacePreservingProfile();
  76. await waitForV4Pane(
  77. (snapshot) => snapshot.sessionId !== targetSessionId,
  78. "重启后目标会话在记录器安装前已被提前打开",
  79. );
  80. await installContextWindowProjectionRecorder(paths.workspace, targetSessionId);
  81. await selectV4TaskById(targetSessionId);
  82. await waitForV4TimelineContaining(CREATE_HISTORY_MARKER);
  83. await waitForV4TimelineContaining(CREATE_HISTORY_REPLY);
  84. await waitForV4Pane(
  85. (snapshot) => snapshot.sessionId === targetSessionId,
  86. "1M 历史 session 没有完成冷恢复",
  87. );
  88. const coldProjection = await waitForConfigProjection(
  89. (projection) => projection.usageUsed > 0 && projection.usageMax === CONTEXT_WINDOW,
  90. "已配置 1M provider 的历史 session 首投影没有使用 1M",
  91. );
  92. expect(coldProjection.usageMax).toBe(CONTEXT_WINDOW);
  93. const observedContextWindows = await readContextWindowProjectionRecorder();
  94. const nonZeroContextWindows = observedContextWindows.filter((value) => value > 0);
  95. // Bug 根因:旧 E2E 直接伪造 sqlite 历史,没有走真实 create/request/restart;
  96. // 这里从点击冷会话之前记录 Zustand + DOM,锁住用户能看到的第一份投影。
  97. expect(observedContextWindows).not.toContain(200_000);
  98. expect(nonZeroContextWindows[0]).toBe(CONTEXT_WINDOW);
  99. expect(new Set(nonZeroContextWindows)).toEqual(new Set([CONTEXT_WINDOW]));
  100. const highUsagePrompt =
  101. `${HIGH_USAGE_MARKER}: run readonly Bash pwd, then reply with ` + `"${TOOL_FOLLOWUP_REPLY}".`;
  102. await sendV4Prompt(highUsagePrompt);
  103. await waitForV4TimelineContaining(TOOL_FOLLOWUP_REPLY);
  104. await waitForV4Pane(
  105. (snapshot) => snapshot.sessionId === targetSessionId && !snapshot.canStop,
  106. "高 usage 工具续轮没有完成",
  107. 90_000,
  108. );
  109. const highUsageProjection = await waitForConfigProjection(
  110. (projection) =>
  111. projection.usageMax === CONTEXT_WINDOW && projection.usageUsed >= HIGH_USAGE_INPUT_TOKENS,
  112. "provider usage 没有更新到同一 1M session 的状态投影",
  113. );
  114. expect(highUsageProjection.usageUsed).toBeGreaterThanOrEqual(HIGH_USAGE_INPUT_TOKENS);
  115. const afterTool = await waitForModelIoSequence(targetSessionId, 3);
  116. expect(afterTool.filter((record) => record.querySource === "compact")).toHaveLength(0);
  117. const afterToolMainTurns = afterTool.filter((record) => record.querySource === "main_turn");
  118. expect(afterToolMainTurns).toHaveLength(3);
  119. expect(
  120. afterToolMainTurns.every((record) => record.body.max_completion_tokens === MAX_OUTPUT_TOKENS),
  121. ).toBe(true);
  122. // 修复原因:compact.auto.skipped 是异步落盘的 debug 诊断事件,不能作为 formal gate;
  123. // 这里用真实 provider 请求序列和 fail-closed fixture 证明 1M 会话没有误发 compact。
  124. expect(afterTool.every((record) => record.modelId === MODEL_ID)).toBe(true);
  125. expect(JSON.stringify(afterToolMainTurns[2]?.body)).toContain(TOOL_CALL_ID);
  126. expect(await getV4CompactMarkers()).toHaveLength(0);
  127. await sendV4Prompt("继续");
  128. await waitForV4TimelineContaining(CONTINUE_REPLY);
  129. await waitForV4Pane(
  130. (snapshot) => snapshot.sessionId === targetSessionId && !snapshot.canStop,
  131. "“继续”轮没有完成",
  132. 90_000,
  133. );
  134. const finalRequests = await waitForModelIoSequence(targetSessionId, 4);
  135. expect(finalRequests.filter((record) => record.querySource === "compact")).toHaveLength(0);
  136. const finalMainTurns = finalRequests.filter((record) => record.querySource === "main_turn");
  137. expect(finalMainTurns).toHaveLength(4);
  138. expect(
  139. finalMainTurns.every((record) => record.body.max_completion_tokens === MAX_OUTPUT_TOKENS),
  140. ).toBe(true);
  141. expect(finalRequests.every((record) => record.modelId === MODEL_ID)).toBe(true);
  142. expect(JSON.stringify(finalMainTurns[3]?.body)).toContain("继续");
  143. expect(await getV4CompactMarkers()).toHaveLength(0);
  144. expect((await getV4ConfigProjection()).usageMax).toBe(CONTEXT_WINDOW);
  145. const preCompactProjection = await getV4ConfigProjection();
  146. expect(preCompactProjection.usageUsed).toBeGreaterThanOrEqual(HIGH_USAGE_INPUT_TOKENS);
  147. await setInputValueByTestIdDom(TID_V4_COMPOSER_INPUT, "/compact", {
  148. timeout: 15_000,
  149. timeoutMsg: "CW04 手动 compact 前 composer 输入框没有出现",
  150. });
  151. await clickV4Send();
  152. await waitForV4CompactMarker({ origin: "manual", status: "success" }, 90_000);
  153. await waitForV4Pane(
  154. (snapshot) => snapshot.sessionId === targetSessionId && !snapshot.canStop,
  155. "CW04 手动 compact 完成后没有回到 idle",
  156. 90_000,
  157. );
  158. const postCompactProjection = await waitForConfigProjection(
  159. (projection) =>
  160. projection.usageMax === CONTEXT_WINDOW &&
  161. projection.usageUsed > 0 &&
  162. projection.usageUsed < preCompactProjection.usageUsed,
  163. "CW04 热态 meter 没有下降到 post-compact 水位",
  164. );
  165. // Bug 根因:compact 后水位持久化在 user summary boundary;冷恢复如果继续只看
  166. // assistant tokens,会越过 boundary 并把 meter 恢复到 compact 前的旧值。
  167. await selectV4TaskById(parkingSessionId);
  168. // Bug 根因:只等 pane sessionId 会早于 parking 会话的 initial snapshot;此时立即
  169. // 重启会中断在途 subscribe,让旧窗口短暂显示“重新连接”错误页。
  170. await waitForV4TimelineContaining(PARKING_REPLY);
  171. await waitForV4Pane(
  172. (snapshot) => snapshot.sessionId === parkingSessionId && !snapshot.canStop,
  173. "CW04 重启前没有切回 parking session",
  174. );
  175. await restartIntoWorkspacePreservingProfile();
  176. await waitForV4Pane(
  177. (snapshot) => snapshot.sessionId !== targetSessionId,
  178. "CW04 第二次重启后目标 session 被提前打开",
  179. );
  180. await selectV4TaskById(targetSessionId);
  181. await waitForV4Pane(
  182. (snapshot) => snapshot.sessionId === targetSessionId && !snapshot.canStop,
  183. "CW04 compact 历史 session 没有完成冷恢复",
  184. 90_000,
  185. );
  186. await waitForV4CompactMarker({ origin: "manual", status: "success" }, 90_000);
  187. await waitForSelectedModel(PROVIDER_ID, MODEL_ID);
  188. const coldPostCompactProjection = await waitForConfigProjection(
  189. (projection) => projection.usageMax === CONTEXT_WINDOW && projection.usageUsed > 0,
  190. "CW04 冷恢复后没有发布 context usage",
  191. );
  192. expect(coldPostCompactProjection.usageUsed).toBe(postCompactProjection.usageUsed);
  193. expect(coldPostCompactProjection.usageUsed).toBeLessThan(preCompactProjection.usageUsed);
  194. // Todo123:只在隔离 E2E 进程退出屏障后改这条真实创建的会话,模拟旧选择缺档位。
  195. // transcript、compact 水位和旧字段均不改;不构造假的聊天正文来替代恢复。
  196. await selectV4TaskById(parkingSessionId);
  197. await restartWithFixture(paths.workspace, {
  198. afterElectronProcessExit: () => patchFixtureSelection(targetSessionId, false),
  199. });
  200. await installContextWindowProjectionRecorder(paths.workspace, targetSessionId);
  201. await selectV4TaskById(targetSessionId);
  202. await waitForV4TimelineContaining(CREATE_HISTORY_REPLY);
  203. const missingReasoning = await waitForConfigProjection(
  204. (projection) => projection.usageMax === CONTEXT_WINDOW && projection.usageUsed > 0,
  205. "CW05 缺档位历史选择未保留真实容量与用量",
  206. );
  207. expect(missingReasoning.usageUsed).toBe(coldPostCompactProjection.usageUsed);
  208. expect(await readContextWindowProjectionRecorder()).not.toContain(200_000);
  209. await selectV4TaskById(parkingSessionId);
  210. await restartWithFixture(paths.workspace, {
  211. afterElectronProcessExit: () => patchFixtureSelection(targetSessionId, true),
  212. });
  213. await selectV4TaskById(targetSessionId);
  214. await waitForV4TimelineContaining(CREATE_HISTORY_REPLY);
  215. await waitForV4Pane(
  216. (snapshot) => snapshot.sessionId === targetSessionId && !snapshot.canStop,
  217. "CW06 未知模型会话应可打开",
  218. );
  219. await waitForConfigProjection(
  220. (projection) => projection.usageMax === 0,
  221. "CW06 未知模型不应显示伪造容量",
  222. );
  223. });
  224. });
  225. function patchFixtureSelection(sessionId: string, unknownModel: boolean): void {
  226. // node:sqlite 仅有同步 API;这里只写测试专属库中指定 session 的新字段。
  227. const database = new DatabaseSync(join(paths.homeDir, ".zcode", "cli", "db", "db.sqlite"));
  228. try {
  229. const result = database
  230. .prepare(`UPDATE session_entry
  231. SET data=json_set(data, '$.modelSelection', json(?))
  232. WHERE session_id=? AND type='runtime/model_selection'`)
  233. .run(
  234. JSON.stringify({
  235. providerId: PROVIDER_ID,
  236. modelId: unknownModel ? "missing-cw-model" : MODEL_ID,
  237. }),
  238. sessionId,
  239. );
  240. expect(Number(result.changes)).toBeGreaterThan(0);
  241. } finally {
  242. database.close();
  243. }
  244. }
  245. async function waitForBoundSession(timeoutMsg: string): Promise<string> {
  246. const snapshot = await waitForV4Pane(
  247. (current) => Boolean(current.sessionId && current.sessionId !== "draft" && !current.canStop),
  248. timeoutMsg,
  249. 90_000,
  250. );
  251. if (!snapshot.sessionId || snapshot.sessionId === "draft") {
  252. throw new Error(`${timeoutMsg}; sessionId=${snapshot.sessionId}`);
  253. }
  254. return snapshot.sessionId;
  255. }
  256. interface ConfigProjection {
  257. mode: string | null;
  258. usageMax: number;
  259. usageUsed: number;
  260. }
  261. async function waitForConfigProjection(
  262. predicate: (projection: ConfigProjection) => boolean,
  263. timeoutMsg: string,
  264. ): Promise<ConfigProjection> {
  265. let latest: ConfigProjection = await getV4ConfigProjection();
  266. await browser.waitUntil(
  267. async () => {
  268. latest = await getV4ConfigProjection();
  269. return predicate(latest);
  270. },
  271. {
  272. interval: 100,
  273. timeout: 30_000,
  274. timeoutMsg: `${timeoutMsg}; latest=${JSON.stringify(latest)}`,
  275. },
  276. );
  277. return latest;
  278. }
  279. interface ContextWindowProjectionRecorder {
  280. dom: number[];
  281. store: number[];
  282. }
  283. async function installContextWindowProjectionRecorder(
  284. workspacePath: string,
  285. sessionId: string,
  286. ): Promise<void> {
  287. const paneTestId = testId(TID_V4_SESSION_PANE, V4_MAIN_PANE_ID);
  288. await browser.execute(
  289. (targetWorkspacePath, targetSessionId, targetPaneTestId, modelConfigTestId) => {
  290. interface SessionStoreState {
  291. getWorkspaceState: (workspace: string) => {
  292. taskRuntimeByTaskId: Record<
  293. string,
  294. {
  295. contextWindow?: number | null;
  296. usage?: { size?: number } | null;
  297. }
  298. >;
  299. };
  300. }
  301. interface SessionStoreBridge {
  302. getState: () => SessionStoreState;
  303. subscribe: (listener: (state: SessionStoreState) => void) => () => void;
  304. }
  305. interface RecorderHost {
  306. __zcodeContextWindowColdResumeE2E?: {
  307. dom: number[];
  308. observer: MutationObserver;
  309. store: number[];
  310. unsubscribe: () => void;
  311. };
  312. __zcodeSessionStoreE2E?: SessionStoreBridge;
  313. }
  314. const host = window as unknown as RecorderHost;
  315. host.__zcodeContextWindowColdResumeE2E?.observer.disconnect();
  316. host.__zcodeContextWindowColdResumeE2E?.unsubscribe();
  317. const dom: number[] = [];
  318. const store: number[] = [];
  319. const append = (target: number[], value: unknown) => {
  320. const numeric = Number(value);
  321. if (Number.isFinite(numeric) && target[target.length - 1] !== numeric) {
  322. target.push(numeric);
  323. }
  324. };
  325. const recordDom = () => {
  326. const pane = document.querySelector<HTMLElement>(`[data-testid="${targetPaneTestId}"]`);
  327. if (pane?.getAttribute("data-session-id") !== targetSessionId) {
  328. return;
  329. }
  330. const modelConfig = pane.querySelector<HTMLElement>(`[data-testid="${modelConfigTestId}"]`);
  331. append(dom, modelConfig?.getAttribute("data-usage-max"));
  332. };
  333. const observer = new MutationObserver(recordDom);
  334. observer.observe(document.body, {
  335. attributeFilter: ["data-session-id", "data-usage-max"],
  336. attributes: true,
  337. childList: true,
  338. subtree: true,
  339. });
  340. const bridge = host.__zcodeSessionStoreE2E;
  341. if (!bridge) {
  342. throw new Error("ZCode session E2E store bridge 未注册");
  343. }
  344. const recordStore = (state: SessionStoreState) => {
  345. const runtime =
  346. state.getWorkspaceState(targetWorkspacePath).taskRuntimeByTaskId[targetSessionId];
  347. append(store, runtime?.usage?.size ?? runtime?.contextWindow);
  348. };
  349. const unsubscribe = bridge.subscribe(recordStore);
  350. recordStore(bridge.getState());
  351. recordDom();
  352. host.__zcodeContextWindowColdResumeE2E = {
  353. dom,
  354. observer,
  355. store,
  356. unsubscribe,
  357. };
  358. },
  359. workspacePath,
  360. sessionId,
  361. paneTestId,
  362. TID_V4_MODEL_CONFIG,
  363. );
  364. }
  365. async function readContextWindowProjectionRecorder(): Promise<number[]> {
  366. const recorder = await browser.execute(() => {
  367. const value = (
  368. window as unknown as {
  369. __zcodeContextWindowColdResumeE2E?: ContextWindowProjectionRecorder;
  370. }
  371. ).__zcodeContextWindowColdResumeE2E;
  372. return value ? { dom: [...value.dom], store: [...value.store] } : null;
  373. });
  374. if (!recorder) {
  375. throw new Error("1M context 冷恢复投影记录器意外丢失");
  376. }
  377. return [...recorder.store, ...recorder.dom];
  378. }
  379. interface ModelIoRecord {
  380. error?: unknown;
  381. model?: { modelId?: string };
  382. querySource?: string;
  383. request?: { body?: unknown };
  384. response?: unknown;
  385. sessionId?: string;
  386. }
  387. interface ModelIoMatch {
  388. body: Record<string, unknown>;
  389. modelId: string | undefined;
  390. querySource: string;
  391. }
  392. async function waitForModelIoSequence(
  393. sessionId: string,
  394. expectedMainTurnCount: number,
  395. ): Promise<ModelIoMatch[]> {
  396. let matched: ModelIoMatch[] = [];
  397. await browser.waitUntil(
  398. async () => {
  399. matched = await readSuccessfulModelIo(sessionId);
  400. return (
  401. matched.filter((record) => record.querySource === "main_turn").length >=
  402. expectedMainTurnCount
  403. );
  404. },
  405. {
  406. interval: 100,
  407. timeout: 30_000,
  408. timeoutMsg:
  409. `model-io 没有达到 ${expectedMainTurnCount} 个 main_turn; ` +
  410. `latest=${JSON.stringify(matched.map((record) => record.querySource))}`,
  411. },
  412. );
  413. return matched;
  414. }
  415. async function readSuccessfulModelIo(sessionId: string): Promise<ModelIoMatch[]> {
  416. const debugDir = join(paths.homeDir, ".zcode", "cli", "debug");
  417. const files = (await readdir(debugDir).catch(() => []))
  418. .filter((name) => name.startsWith("model-io-") && name.endsWith(".jsonl"))
  419. .sort();
  420. const matched: ModelIoMatch[] = [];
  421. for (const file of files) {
  422. const content = await readFile(join(debugDir, file), "utf-8").catch(() => "");
  423. for (const line of content.split("\n")) {
  424. const record = parseJsonObject(line) as ModelIoRecord | null;
  425. if (
  426. !record ||
  427. record.error !== undefined ||
  428. record.response === undefined ||
  429. record.sessionId !== sessionId ||
  430. typeof record.querySource !== "string"
  431. ) {
  432. continue;
  433. }
  434. const body = parseJsonObject(record.request?.body);
  435. if (!body || body.bodySource === "ai_sdk_options") {
  436. continue;
  437. }
  438. matched.push({
  439. body,
  440. modelId: record.model?.modelId,
  441. querySource: record.querySource,
  442. });
  443. }
  444. }
  445. return matched;
  446. }
  447. function parseJsonObject(value: unknown): Record<string, unknown> | null {
  448. if (typeof value === "string") {
  449. try {
  450. return parseJsonObject(JSON.parse(value));
  451. } catch {
  452. return null;
  453. }
  454. }
  455. return value && typeof value === "object" && !Array.isArray(value)
  456. ? (value as Record<string, unknown>)
  457. : null;
  458. }