conversation-session-total-tokens-reminder.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. // TT01–TT10 token 预算提醒默认关闭(docs/conversation-session-case-catalog.md「token 预算提醒」)。
  2. // 规格见 apps/zcode-cli/docs/design/v2/loop/meta-user-context.md「Total-tokens reminder」。
  3. // 用例沿用覆盖各收集点的流程:轮首、工具批次、输出续写、冷恢复、三种压缩、子 agent、旧快照、
  4. // chat completions。所有断言读取上游请求体:system 与 messages 里都没有 `<total_tokens>`。
  5. import { join } from "node:path";
  6. import { DatabaseSync } from "node:sqlite";
  7. import { TID_V4_COMPOSER_INPUT } from "@zcode/shared/test-ids";
  8. import {
  9. clearAppData,
  10. DEFAULT_WORKSPACE,
  11. setInputValueByTestIdDom,
  12. } from "#e2e/helpers/desktop-app";
  13. import { getUpstreamRequestEvidence } from "#e2e/helpers/conversation-session-network";
  14. import { ensureReadonlyToolFixtureFile } from "#e2e/helpers/conversation-session-readonly-tool";
  15. import { refreshSeededOpenAIProvidersThroughSettings } from "#e2e/helpers/custom-openai-provider";
  16. import { seedCustomOpenAIChatCompletionsProvider } from "#e2e/helpers/custom-openai-provider-store";
  17. import { prepareIncomingMessageCapability } from "#e2e/helpers/incoming-message-capability";
  18. import { restartIntoWorkspacePreservingProfile } from "#e2e/helpers/model-provider-restart-runtime";
  19. import { startDraftFromProject } from "#e2e/helpers/project-sidebar";
  20. import { selectUpstreamProviderModelById } from "#e2e/helpers/upstream-provider";
  21. import {
  22. clickV4Send,
  23. prepareV4ConversationE2E,
  24. selectV4TaskById,
  25. sendV4Prompt,
  26. waitForV4CompactMarker,
  27. waitForV4Pane,
  28. waitForV4TimelineContaining,
  29. } from "#e2e/helpers/v4-conversation";
  30. type Block = Record<string, unknown> & { type?: string };
  31. type Message = { role: string; content: unknown };
  32. type Request = { messages: Message[]; system?: unknown };
  33. const TAG = "<total_tokens>";
  34. // 开关打开时写在 system 末尾的预算行;TT09 用它模拟开关打开时写下的旧快照。
  35. const LINE = "<total_tokens>15000000 tokens left</total_tokens>";
  36. // 开关关闭时,默认 system 的动态段以 `# Memory, notes and feedback` 段结尾。
  37. const SYSTEM_END = "work from the context, not intermediate files.";
  38. describe("TT token 预算提醒默认关闭", () => {
  39. before(async () => {
  40. await ensureReadonlyToolFixtureFile();
  41. });
  42. after(async () => {
  43. await browser.electron.restoreAllMocks();
  44. await clearAppData();
  45. });
  46. for (const mcs of [true, false]) {
  47. const M = mcs ? "MCS" : "PLAIN";
  48. const id = (step: number) => `tt-a${step}-${M.toLowerCase()}`;
  49. it(`TT01–TT04 ${M}:轮首、工具批次、输出续写和冷恢复后都没有提醒`, async function () {
  50. this.timeout(480_000);
  51. await prepareIncomingMessageCapability(mcs);
  52. await runTurn(`E2E_TT_A1_${M} Read the readonly fixture twice.`, `TT_A1_DONE_${M}`);
  53. const sessionId = await idleSessionId("A 第一轮没有完成");
  54. await runTurn(`E2E_TT_A2_${M} Read it once more.`, `TT_A2_DONE_${M}`);
  55. await restartIntoWorkspacePreservingProfile(DEFAULT_WORKSPACE);
  56. await selectV4TaskById(sessionId, 30_000);
  57. await waitForV4TimelineContaining(`TT_A2_DONE_${M}`);
  58. await runTurn(`E2E_TT_A3_${M} Read it after resume.`, `TT_A3_DONE_${M}`);
  59. // tt-a6 是输出续写,tt-a7 起是冷恢复后的请求。
  60. const requests = await requestsByFixture([1, 2, 3, 4, 5, 6, 7, 8].map(id));
  61. expectNoReminder(requests);
  62. });
  63. }
  64. it("TT05–TT07:auto、手动与 reactive compaction 前后都没有提醒", async function () {
  65. this.timeout(480_000);
  66. await prepareIncomingMessageCapability(true);
  67. // 第二个请求的 usage 超过 MCS 模型 1000000 窗口的自动压缩阈值。
  68. await runTurn("E2E_TT_C1 Read the readonly fixture three times.", "TT_C1_DONE");
  69. await waitForV4CompactMarker({ origin: "auto", status: "success" }, 90_000);
  70. await idleSessionId("C 第一轮没有完成");
  71. await setInputValueByTestIdDom(TID_V4_COMPOSER_INPUT, "/compact", {
  72. timeout: 15_000,
  73. timeoutMsg: "composer 输入框没有出现",
  74. });
  75. await clickV4Send();
  76. await waitForV4CompactMarker({ origin: "manual", status: "success" }, 90_000);
  77. await idleSessionId("手动 compact 后没有回到空闲态");
  78. await runTurn("E2E_TT_C2 Read it after the manual compact.", "TT_C2_DONE");
  79. // 工具批次之后的请求返回 prompt is too long,reactive compaction 后重试。
  80. await runTurn("E2E_TT_C3 Read it before the reactive compact.", "TT_C3_DONE");
  81. const requests = await requestsByFixture([
  82. "tt-c1",
  83. "tt-c2",
  84. "tt-c-auto-summary",
  85. "tt-c3",
  86. "tt-c4",
  87. "tt-c-manual-summary",
  88. "tt-c5",
  89. "tt-c6",
  90. "tt-c7",
  91. "tt-c8-too-long",
  92. "tt-c-reactive-summary",
  93. "tt-c9",
  94. "tt-c10",
  95. ]);
  96. expectNoReminder(requests, { summaries: [2, 5, 10] });
  97. });
  98. it("TT08:Explore 子 agent 与父会话的通知轮都没有提醒", async function () {
  99. this.timeout(300_000);
  100. await prepareIncomingMessageCapability(true);
  101. await sendV4Prompt("E2E_TT_S_PARENT Explore the readonly fixture in a subagent.");
  102. await waitForV4TimelineContaining("TT_S_PARENT_DONE", 120_000);
  103. await idleSessionId("S 通知轮没有完成");
  104. const requests = await requestsByFixture([
  105. "tt-s-parent-agent",
  106. "tt-s-child-1",
  107. "tt-s-child-2",
  108. "tt-s-parent-launched",
  109. "tt-s-parent-notified",
  110. ]);
  111. // 子 agent 的 system 以 Notes 结尾,同样没有预算行。
  112. for (const child of [requests[1]!, requests[2]!])
  113. expect(systemText(child).endsWith("this note is about report files.)")).toBe(true);
  114. expectNoReminder(requests, { children: [1, 2] });
  115. });
  116. it("TT09:带预算行的旧快照原样使用到下一次 compaction", async function () {
  117. this.timeout(360_000);
  118. await prepareIncomingMessageCapability(true);
  119. await runTurn("E2E_TT_N1 hello.", "TT_N1_DONE");
  120. const sessionId = await idleSessionId("N 首轮没有完成");
  121. // 应用退出后改写快照:在动态段末尾补上预算行,模拟开关打开时写下的快照。
  122. await restartIntoWorkspacePreservingProfile(DEFAULT_WORKSPACE, {
  123. afterElectronProcessExit: async () => rewriteSnapshotWithLine(sessionId),
  124. });
  125. await selectV4TaskById(sessionId, 30_000);
  126. await waitForV4TimelineContaining("TT_N1_DONE");
  127. await runTurn("E2E_TT_N2 hello again.", "TT_N2_DONE");
  128. await setInputValueByTestIdDom(TID_V4_COMPOSER_INPUT, "/compact", {
  129. timeout: 15_000,
  130. timeoutMsg: "composer 输入框没有出现",
  131. });
  132. await clickV4Send();
  133. await waitForV4CompactMarker({ origin: "manual", status: "success" }, 90_000);
  134. await idleSessionId("N 手动 compact 后没有回到空闲态");
  135. await runTurn("E2E_TT_N3 after compact.", "TT_N3_DONE");
  136. const [n1, n2, n3] = await requestsByFixture(["tt-n1", "tt-n2", "tt-n3"]);
  137. expect(systemText(n1!).endsWith(SYSTEM_END)).toBe(true);
  138. // 旧快照原样使用:system 就是首轮 system 加上预算行,缓存前缀不变;消息里不新增提醒。
  139. expect(systemText(n2!)).toBe(`${systemText(n1!)}\n\n${LINE}`);
  140. expect(messagesText(n2!)).not.toContain(TAG);
  141. // compaction 后按当前代码重建 system,不再带预算行。
  142. expectNoReminder([n1!, n3!]);
  143. });
  144. it("TT10:openai chat completions 的 system 与消息都没有提醒", async function () {
  145. this.timeout(300_000);
  146. await prepareV4ConversationE2E({ skipProvider: true });
  147. await seedCustomOpenAIChatCompletionsProvider({
  148. modelId: OA_MODEL_ID,
  149. providerId: OA_PROVIDER_ID,
  150. providerName: OA_PROVIDER_NAME,
  151. });
  152. await refreshSeededOpenAIProvidersThroughSettings([OA_PROVIDER_NAME], {
  153. workspacePath: DEFAULT_WORKSPACE,
  154. });
  155. await startDraftFromProject(DEFAULT_WORKSPACE);
  156. await selectUpstreamProviderModelById(OA_MODEL_ID, {
  157. includePlainModelFallback: false,
  158. providerId: OA_PROVIDER_ID,
  159. providerName: OA_PROVIDER_NAME,
  160. });
  161. await runTurn("E2E_TT_O1 Read the readonly fixture.", "TT_O1_DONE");
  162. await runTurn("E2E_TT_O2 hello again.", "TT_O2_DONE");
  163. expectNoReminder(await requestsByFixture(["tt-o1", "tt-o2", "tt-o3"]));
  164. });
  165. });
  166. const OA_MODEL_ID = "e2e-tt-openai-model";
  167. const OA_PROVIDER_ID = "e2e-tt-openai-provider";
  168. const OA_PROVIDER_NAME = "Total Tokens Chat Completions";
  169. async function runTurn(prompt: string, done: string) {
  170. await sendV4Prompt(prompt);
  171. await waitForV4TimelineContaining(done, 120_000);
  172. await idleSessionId(`${prompt.split(" ")[0]} 没有完成`);
  173. }
  174. async function idleSessionId(timeoutMsg: string): Promise<string> {
  175. const snapshot = await waitForV4Pane(
  176. (current) => Boolean(current.sessionId && current.sessionId !== "draft") && !current.canStop,
  177. timeoutMsg,
  178. 120_000,
  179. );
  180. return snapshot.sessionId!;
  181. }
  182. /** 按 fixture id 取上游请求;每个 fixture 只匹配一次。 */
  183. async function requestsByFixture(ids: string[]): Promise<Request[]> {
  184. const records = await getUpstreamRequestEvidence({});
  185. return ids.map((fixtureId) => {
  186. const record = records.find((item) => item.fixtureId === fixtureId);
  187. const request = record?.requestJson as Request | undefined;
  188. if (!request || !Array.isArray(request.messages)) throw new Error(`${fixtureId} 没有上游请求`);
  189. return request;
  190. });
  191. }
  192. /**
  193. * 每个请求的 system 与 messages 都没有预算提醒。主会话的 system 以 `# Memory, notes and feedback` 段结尾;
  194. * 摘要请求的 system 是压缩专用提示,子 agent 的 system 以 Notes 结尾,只检查没有提醒。
  195. */
  196. function expectNoReminder(
  197. requests: Request[],
  198. options: { summaries?: number[]; children?: number[] } = {},
  199. ) {
  200. requests.forEach((request, index) => {
  201. expect(systemText(request)).not.toContain(TAG);
  202. expect(messagesText(request)).not.toContain(TAG);
  203. if (options.summaries?.includes(index) || options.children?.includes(index)) return;
  204. expect(systemText(request).endsWith(SYSTEM_END)).toBe(true);
  205. });
  206. }
  207. function systemText(request: Request): string {
  208. if (Array.isArray(request.system)) {
  209. return (request.system as Block[]).map((block) => String(block.text ?? "")).join("\u0000");
  210. }
  211. if (typeof request.system === "string") return request.system;
  212. const first = request.messages[0];
  213. return first?.role === "system" ? blocksText(first.content) : "";
  214. }
  215. /** messages 的全部文本,tool_result 内的块也算;chat completions 的 system 在 messages[0],不算。 */
  216. function messagesText(request: Request): string {
  217. const skipFirst = request.system === undefined && request.messages[0]?.role === "system";
  218. return request.messages
  219. .filter((_, index) => !(skipFirst && index === 0))
  220. .map((message) => blocksText(message.content))
  221. .join("\n");
  222. }
  223. function blocksText(content: unknown): string {
  224. if (typeof content === "string") return content;
  225. if (!Array.isArray(content)) return "";
  226. return (content as Block[])
  227. .map((block) =>
  228. block.type === "tool_result" ? blocksText(block.content) : String(block.text ?? ""),
  229. )
  230. .join("");
  231. }
  232. // 在快照 system 的动态段末尾补上预算行。node:sqlite 只提供同步接口;调用时应用已退出,没有并发写入。
  233. function rewriteSnapshotWithLine(sessionId: string) {
  234. const home = process.env.ZCODE_E2E_HOME_DIR;
  235. if (!home) throw new Error("缺少 ZCODE_E2E_HOME_DIR");
  236. const database = new DatabaseSync(join(home, ".zcode", "cli", "db", "db.sqlite"));
  237. try {
  238. const id = `${sessionId}:runtime-prompt-snapshot`;
  239. const row = database.prepare("select data from session_entry where id = ?").get(id) as
  240. | { data: string }
  241. | undefined;
  242. if (!row) throw new Error(`没有 ${id}`);
  243. // 动态段的 JSON 字符串以 SYSTEM_END 结尾,紧跟收尾引号。
  244. const needle = `${SYSTEM_END}"`;
  245. if (row.data.split(needle).length !== 2) throw new Error("快照里没有唯一的动态段结尾");
  246. if (row.data.includes(TAG)) throw new Error("快照里已有预算行");
  247. const line = JSON.stringify(`\n\n${LINE}`).slice(1, -1);
  248. database
  249. .prepare("update session_entry set data = ? where id = ?")
  250. .run(row.data.replace(needle, `${SYSTEM_END}${line}"`), id);
  251. } finally {
  252. database.close();
  253. }
  254. }