conversation-session-read-session-context-timeout.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. import { mkdir, readFile } from "node:fs/promises";
  2. import { homedir } from "node:os";
  3. import { dirname, join } from "node:path";
  4. import { DatabaseSync } from "node:sqlite";
  5. import { clearAppData, DEFAULT_WORKSPACE } from "../helpers/desktop-app.js";
  6. import {
  7. clickV4Stop,
  8. getV4ConversationState,
  9. prepareV4ConversationE2E,
  10. sendV4Prompt,
  11. waitForV4AssistantMessageContaining,
  12. waitForV4ConversationState,
  13. waitForV4ComposerText,
  14. waitForV4UserMessageContaining,
  15. } from "#e2e/helpers/v4-conversation";
  16. import { waitForUpstreamRequest } from "#e2e/helpers/conversation-session-network";
  17. import { waitForToolCallBlockByToolName } from "#e2e/helpers/conversation-session-tool";
  18. import { UPSTREAM_MODEL } from "../helpers/upstream-provider.js";
  19. const CASE_NAME = "conversation-session-read-session-context-timeout";
  20. const SOURCE_SESSION_ID = "sess_e2e_read_session_context_timeout_source";
  21. const SOURCE_SESSION_TITLE = "E2E ReadSessionContext Timeout Source";
  22. const SOURCE_PROJECT_ID = "proj_e2e_read_session_context_timeout";
  23. const SOURCE_TRACE_ID = "trace_e2e_read_session_context_timeout";
  24. const SOURCE_USER_MESSAGE_ID = "msg_e2e_rsc_timeout_source_user";
  25. const SOURCE_ASSISTANT_MESSAGE_ID = "msg_e2e_rsc_timeout_source_assistant";
  26. const SOURCE_USER_PART_ID = "part_e2e_rsc_timeout_source_user_text";
  27. const SOURCE_ASSISTANT_PART_ID = "part_e2e_rsc_timeout_source_assistant_text";
  28. const PROVIDER_ID = "e2e-upstream";
  29. const MODEL_ID = UPSTREAM_MODEL;
  30. const SOURCE_MARKER = "E2E_RSC_TIMEOUT_SOURCE_DECISION";
  31. const TARGET_MARKER = "E2E_RSC_TIMEOUT_TARGET";
  32. const LITE_QUERY_MARKER = "E2E_RSC_TIMEOUT_QUERY";
  33. const FINAL_MARKER = "E2E_RSC_TIMEOUT_FINAL_OK";
  34. const READ_SESSION_CONTEXT_TOOL_NAME = "ReadSessionContext";
  35. const LITE_FIXTURE_ID = "upstream-read-session-context-timeout-lite-extraction";
  36. const LITE_DELAY_MS = 55_000;
  37. const STILL_RUNNING_ASSERTION_DELAY_MS = 46_000;
  38. describe("会话区 ReadSessionContext 超时边界 E2E", () => {
  39. afterEach(async () => {
  40. await stopRunningTurnIfNeeded();
  41. });
  42. after(async () => {
  43. await browser.electron.restoreAllMocks();
  44. await clearAppData();
  45. });
  46. it("O07: ReadSessionContext 内部 lite 抽取超过 45 秒仍应完成当前 turn", async function () {
  47. this.timeout(180000);
  48. await prepareV4ConversationE2E();
  49. await seedReadSessionContextSourceSession();
  50. const prompt = [
  51. `${TARGET_MARKER}_${Date.now()}:`,
  52. `Use #${SOURCE_SESSION_ID} with ${READ_SESSION_CONTEXT_TOOL_NAME}.`,
  53. `Ask for ${LITE_QUERY_MARKER}.`,
  54. `Then reply with exactly "${FINAL_MARKER}" and no other text.`,
  55. ].join(" ");
  56. await sendV4Prompt(prompt);
  57. await waitForV4ComposerText("", "ReadSessionContext timeout prompt 发送后输入框没有清空");
  58. await waitForV4UserMessageContaining(TARGET_MARKER);
  59. await waitForV4UserMessageContaining(SOURCE_SESSION_ID);
  60. await waitForV4UserMessageContaining(LITE_QUERY_MARKER);
  61. await waitForToolCallBlockByToolName(READ_SESSION_CONTEXT_TOOL_NAME, 30000);
  62. await waitForUpstreamRequest(
  63. {
  64. excludes: ["Generate a concise title"],
  65. includes: [
  66. "You are the extraction model for the ReadSessionContext tool.",
  67. LITE_QUERY_MARKER,
  68. SOURCE_MARKER,
  69. ],
  70. },
  71. "没有捕获到 ReadSessionContext 内部 lite 抽取请求",
  72. 30000,
  73. );
  74. // 修复原因:这个 case 专门防止历史 30 秒协议请求判断或旧 45 秒工具 timeout
  75. // 把 ReadSessionContext 的长耗时内部抽取误判失败。第 46 秒仍应保持当前 turn running。
  76. await browser.pause(STILL_RUNNING_ASSERTION_DELAY_MS);
  77. const midRunSnapshot = await getV4ConversationState();
  78. expect(midRunSnapshot.state).toBe("streaming");
  79. expect(midRunSnapshot.queueCount).toBe(0);
  80. await waitForUpstreamRequest(
  81. {
  82. excludes: ["Generate a concise title"],
  83. includes: [TARGET_MARKER, SOURCE_MARKER],
  84. },
  85. "ReadSessionContext 工具结果没有进入后续主模型请求",
  86. 120000,
  87. );
  88. await waitForV4AssistantMessageContaining(FINAL_MARKER);
  89. await waitForV4ConversationState(
  90. (snapshot) => snapshot.state === "idle" && snapshot.queueCount === 0,
  91. "ReadSessionContext timeout case 完成后没有回到 idle",
  92. 120000,
  93. );
  94. const toolBlock = await waitForToolCallBlockByToolName(READ_SESSION_CONTEXT_TOOL_NAME, 30000);
  95. expect(toolBlock.exists).toBe(true);
  96. const liteRecord = await waitForReplayRecordByFixtureId(LITE_FIXTURE_ID);
  97. expect(liteRecord.status).toBe("complete");
  98. expect(liteRecord.durationMs ?? 0).toBeGreaterThanOrEqual(LITE_DELAY_MS - 1000);
  99. });
  100. });
  101. async function seedReadSessionContextSourceSession() {
  102. await mkdir(DEFAULT_WORKSPACE, { recursive: true });
  103. const dbPath = join(homedir(), ".zcode", "cli", "db", "db.sqlite");
  104. await mkdir(dirname(dbPath), { recursive: true });
  105. const db = new DatabaseSync(dbPath);
  106. const now = Date.now() - 10_000;
  107. try {
  108. db.exec("pragma foreign_keys = on; pragma busy_timeout = 5000;");
  109. // 修复原因:该 E2E 需要一个稳定的被引用历史 session;先让 app 初始化 sqlite schema,
  110. // 再按 session-store 的持久化格式写入最小 rows,避免测试包依赖 agent adapters 构建链路。
  111. db.prepare(
  112. `
  113. insert into session (
  114. id, project_id, workspace_id, parent_id, trace_id, task_type, slug, directory, path,
  115. title, title_source, title_message_id, version,
  116. share_url, summary_additions, summary_deletions, summary_files, summary_diffs,
  117. revert, permission, time_created, time_updated, time_title_updated,
  118. time_compacting, time_archived
  119. ) values (?, ?, null, null, ?, 'interactive', ?, ?, ?, ?, 'custom', null, 'e2e',
  120. null, null, null, null, null, null, ?, ?, ?, ?, null, null)
  121. on conflict(id) do update set
  122. project_id = excluded.project_id,
  123. trace_id = excluded.trace_id,
  124. task_type = excluded.task_type,
  125. slug = excluded.slug,
  126. directory = excluded.directory,
  127. path = excluded.path,
  128. title = excluded.title,
  129. title_source = excluded.title_source,
  130. version = excluded.version,
  131. permission = excluded.permission,
  132. time_title_updated = excluded.time_title_updated,
  133. time_updated = excluded.time_updated
  134. `,
  135. ).run(
  136. SOURCE_SESSION_ID,
  137. SOURCE_PROJECT_ID,
  138. SOURCE_TRACE_ID,
  139. "e2e-read-session-context-timeout-source",
  140. DEFAULT_WORKSPACE,
  141. DEFAULT_WORKSPACE,
  142. SOURCE_SESSION_TITLE,
  143. JSON.stringify({ mode: "build" }),
  144. now,
  145. now + 2,
  146. now + 2,
  147. );
  148. saveMessageRow(db, SOURCE_USER_MESSAGE_ID, now, now, {
  149. role: "user",
  150. time: { created: now },
  151. agent: "zcode-agent",
  152. model: { providerID: PROVIDER_ID, modelID: MODEL_ID },
  153. metadata: { e2eCase: CASE_NAME },
  154. });
  155. savePartRow(db, SOURCE_USER_PART_ID, SOURCE_USER_MESSAGE_ID, now, now, {
  156. type: "text",
  157. text: `${SOURCE_MARKER}: record the protocol timeout investigation and keep this context readable.`,
  158. time: { start: now, end: now },
  159. metadata: { e2eCase: CASE_NAME },
  160. });
  161. saveMessageRow(db, SOURCE_ASSISTANT_MESSAGE_ID, now + 1, now + 1, {
  162. role: "assistant",
  163. parentID: SOURCE_USER_MESSAGE_ID,
  164. time: { created: now + 1, completed: now + 1 },
  165. modelID: MODEL_ID,
  166. providerID: PROVIDER_ID,
  167. mode: "build",
  168. agent: "zcode-agent",
  169. path: { cwd: DEFAULT_WORKSPACE, root: DEFAULT_WORKSPACE },
  170. cost: 0,
  171. tokens: {
  172. input: 0,
  173. output: 0,
  174. reasoning: 0,
  175. cache: { read: 0, write: 0 },
  176. },
  177. finish: "stop",
  178. });
  179. savePartRow(db, SOURCE_ASSISTANT_PART_ID, SOURCE_ASSISTANT_MESSAGE_ID, now + 1, now + 1, {
  180. type: "text",
  181. text: `${SOURCE_MARKER}: ReadSessionContext must survive a lite extraction that lasts longer than the historical 45 second tool timeout.`,
  182. time: { start: now + 1, end: now + 1 },
  183. metadata: { e2eCase: CASE_NAME },
  184. });
  185. } finally {
  186. db.close();
  187. }
  188. }
  189. function saveMessageRow(
  190. db: DatabaseSync,
  191. messageId: string,
  192. timeCreated: number,
  193. timeUpdated: number,
  194. data: Record<string, unknown>,
  195. ) {
  196. db.prepare(
  197. `
  198. insert into message (id, session_id, time_created, time_updated, data)
  199. values (?, ?, ?, ?, ?)
  200. on conflict(id) do update set
  201. session_id = excluded.session_id,
  202. time_updated = excluded.time_updated,
  203. data = excluded.data
  204. `,
  205. ).run(messageId, SOURCE_SESSION_ID, timeCreated, timeUpdated, JSON.stringify(data));
  206. touchSourceSession(db, timeUpdated);
  207. }
  208. function savePartRow(
  209. db: DatabaseSync,
  210. partId: string,
  211. messageId: string,
  212. timeCreated: number,
  213. timeUpdated: number,
  214. data: Record<string, unknown>,
  215. ) {
  216. db.prepare(
  217. `
  218. insert into part (id, message_id, session_id, time_created, time_updated, data)
  219. values (?, ?, ?, ?, ?, ?)
  220. on conflict(id) do update set
  221. message_id = excluded.message_id,
  222. session_id = excluded.session_id,
  223. time_updated = excluded.time_updated,
  224. data = excluded.data
  225. `,
  226. ).run(partId, messageId, SOURCE_SESSION_ID, timeCreated, timeUpdated, JSON.stringify(data));
  227. touchSourceSession(db, timeUpdated);
  228. }
  229. function touchSourceSession(db: DatabaseSync, timeUpdated: number) {
  230. db.prepare("update session set time_updated = max(time_updated, ?) where id = ?").run(
  231. timeUpdated,
  232. SOURCE_SESSION_ID,
  233. );
  234. }
  235. async function stopRunningTurnIfNeeded() {
  236. const snapshot = await getV4ConversationState().catch(() => null);
  237. if (!snapshot || snapshot.state !== "streaming") {
  238. return;
  239. }
  240. await clickV4Stop();
  241. await waitForV4ConversationState(
  242. (nextSnapshot) => nextSnapshot.state !== "streaming",
  243. "ReadSessionContext timeout case 收尾后没有退出 streaming",
  244. 30000,
  245. );
  246. }
  247. async function waitForReplayRecordByFixtureId(fixtureId: string) {
  248. let latest: ReplayRecord | null = null;
  249. await browser.waitUntil(
  250. async () => {
  251. latest =
  252. (await readReplayRecords()).find((record) => record.replay?.fixtureId === fixtureId) ??
  253. null;
  254. return latest?.status === "complete";
  255. },
  256. {
  257. timeout: 30000,
  258. timeoutMsg: `没有等到 replay fixture 完成: ${fixtureId}; latest=${JSON.stringify(latest)}`,
  259. },
  260. );
  261. return latest!;
  262. }
  263. async function readReplayRecords(): Promise<ReplayRecord[]> {
  264. const capturePath = process.env.E2E_PROVIDER_CAPTURE_PATH?.trim();
  265. if (!capturePath) {
  266. return [];
  267. }
  268. const artifact = JSON.parse(await readFile(capturePath, "utf-8")) as {
  269. records?: ReplayRecord[];
  270. };
  271. return artifact.records ?? [];
  272. }
  273. interface ReplayRecord {
  274. durationMs?: number;
  275. replay?: {
  276. fixtureId?: string;
  277. };
  278. status: "complete" | "error" | "pending";
  279. }