runtime-reasoning-provider-replay.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. import { mkdtemp, rm } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { DatabaseSync } from "node:sqlite";
  5. import { describe, expect, it, vi } from "vitest";
  6. import {
  7. InMemorySessionEventStore,
  8. SESSION_ENTRY_MODEL_SELECTION,
  9. createMessageId,
  10. createModelId,
  11. createModelProviderId,
  12. createPartId,
  13. createProjectId,
  14. createSessionId,
  15. parseModelSelectionValue,
  16. type Model,
  17. type ModelRequest,
  18. type SessionId,
  19. } from "@zcode/contracts";
  20. import {
  21. createRegistryModelConfig,
  22. createRegistryProviderConfig,
  23. parseModelConfig,
  24. parseProviderConfig,
  25. } from "@zcode/provider";
  26. import { createSqliteSessionStore } from "../src/storage/session-store/sqlite-session-store.js";
  27. import { AiSdkModelAdapter } from "../src/model/runner.js";
  28. import { createTestModelProperties } from "./test-model-format.js";
  29. import { AgentRuntime } from "../../core/src/runtime.js";
  30. const MODEL_ID = createModelId("GLM-5.3");
  31. const USER_ID = createMessageId("old-user");
  32. const ASSISTANT_ID = createMessageId("old-assistant");
  33. const SIGNATURE = "fixture-signature\nopaque ";
  34. const REDACTED_DATA = "fixture-redacted-opaque";
  35. const HISTORICAL_CONTENT = [
  36. { type: "thinking", thinking: "Historical thinking", signature: SIGNATURE },
  37. { type: "redacted_thinking", data: REDACTED_DATA },
  38. { type: "text", text: "Inspecting report" },
  39. { type: "tool_use", id: "old-read", name: "Read", input: { file_path: "report.txt" } },
  40. ];
  41. const cases = ["zai", "bigmodel"].flatMap((family) => {
  42. const legacy = `builtin:${family}-coding-plan`;
  43. const individual = `account:${family}-individual-coding-plan`;
  44. const team = `account:${family}-team-coding-plan`;
  45. return [
  46. [legacy, individual],
  47. [legacy, team],
  48. [individual, team],
  49. [team, individual],
  50. ] as const;
  51. });
  52. describe.each(["off", "on"] as const)(
  53. "Runtime reasoning replay (streaming=%s)",
  54. (modelStreaming) => {
  55. it.each(cases)(
  56. "restores %s and replays into %s without changing old bytes",
  57. async (source, target) => {
  58. const root = await mkdtemp(join(tmpdir(), "zcode-reasoning-replay-"));
  59. const sessionID = createSessionId("reasoning-replay");
  60. let store = createSqliteSessionStore({ dbPath: join(root, "session.sqlite") });
  61. const db = new DatabaseSync(join(root, "session.sqlite"));
  62. let runtime: AgentRuntime | undefined;
  63. try {
  64. // 合并修复:空库建表后移除尚未播种的迁移记录,模拟升级前数据;只操作临时夹具。
  65. db.prepare("DELETE FROM schema_migration WHERE id = ?").run(
  66. "0020_provider_model_selection",
  67. );
  68. await seedHistory({ db, store, root, sessionID, providerId: source });
  69. const snapshot = () => ({
  70. messages: db
  71. .prepare("select data from message where id in (?, ?) order by id")
  72. .all(USER_ID, ASSISTANT_ID),
  73. parts: db
  74. .prepare("select data from part where message_id in (?, ?) order by id")
  75. .all(USER_ID, ASSISTANT_ID),
  76. });
  77. const before = snapshot();
  78. // Todo109 已将迁移收进数据库启动;不能恢复已删除的逐 Session 迁移接口。
  79. store.close();
  80. store = createSqliteSessionStore({ dbPath: join(root, "session.sqlite") });
  81. const migrated = snapshot();
  82. expect(migrated.messages).toHaveLength(before.messages.length);
  83. for (const [index, row] of before.messages.entries()) {
  84. expect(JSON.parse(String(migrated.messages[index]!.data))).toMatchObject(
  85. JSON.parse(String(row.data)),
  86. );
  87. }
  88. expect(migrated.parts).toEqual(before.parts);
  89. const entries = await store.sessionEntries({
  90. sessionID,
  91. type: SESSION_ENTRY_MODEL_SELECTION,
  92. });
  93. const selection = parseModelSelectionValue(entries.at(-1)?.data);
  94. if (!selection) throw new Error("Missing restored model selection");
  95. expect(selection.providerId).toBe(
  96. source.startsWith("builtin:")
  97. ? source
  98. .replace("builtin:", "account:")
  99. .replace("-coding-plan", "-individual-coding-plan")
  100. : source,
  101. );
  102. const decoded = (await store.messages({ sessionID })).find(
  103. (message) => message.info.id === ASSISTANT_ID,
  104. );
  105. expect(decoded?.info).toMatchObject({ providerId: source, modelId: MODEL_ID });
  106. const bodies: Array<{ messages: Array<{ role: string; content: unknown[] }> }> = [];
  107. vi.stubGlobal("fetch", async (input: RequestInfo | URL, init?: RequestInit) => {
  108. const request = new Request(input, init);
  109. expect(request.url).toBe("https://reasoning.invalid/v1/messages");
  110. bodies.push(await request.json());
  111. return modelResponse(modelStreaming === "on");
  112. });
  113. const provider = createRegistryProviderConfig(
  114. parseProviderConfig({
  115. group: "standard-personal",
  116. access: { type: "api-key", apiKey: "fixture-key" },
  117. api: { type: "anthropic-messages", baseUrl: "https://reasoning.invalid/v1" },
  118. }),
  119. );
  120. const model = createRegistryModelConfig(
  121. parseModelConfig({
  122. enabled: true,
  123. properties: createTestModelProperties(),
  124. optionSpecs: {
  125. reasoningLevel: { values: ["disabled"], map: "{}" },
  126. maxOutputTokens: { max: 32_000, map: '{"max_tokens": maxOutputTokens}' },
  127. },
  128. }),
  129. );
  130. if (!provider.ok || !model.ok) throw new Error("Invalid model fixture config");
  131. const adapter = new AiSdkModelAdapter({
  132. env: {},
  133. retry: { maxAttempts: 1 },
  134. });
  135. const requests: ModelRequest[] = [];
  136. runtime = new AgentRuntime(
  137. sessionID,
  138. {
  139. mode: "build",
  140. modelStreaming,
  141. workingDirectory: root,
  142. modelSelection: selection,
  143. memory: { enabled: false },
  144. compact: { enabled: false },
  145. },
  146. {
  147. sessionStore: store,
  148. eventStore: new InMemorySessionEventStore({ retention: "unbounded" }),
  149. modelFactory: ({ selection }) =>
  150. observeModel(
  151. adapter.createModel({
  152. providerId: selection.providerId,
  153. modelId: selection.modelId,
  154. providerConfig: provider.config,
  155. modelConfig: model.config,
  156. options: { maxOutputTokens: 32_000, ...selection.options },
  157. }),
  158. requests,
  159. ),
  160. },
  161. );
  162. await runtime.resumeFromStore();
  163. runtime.setSessionModelSelection({
  164. ...selection,
  165. providerId: createModelProviderId(target),
  166. });
  167. await runtime.executeTurn("Continue after restart");
  168. expect(bodies).toHaveLength(1);
  169. const assistant = bodies[0]!.messages.find((message) => message.role === "assistant");
  170. expect(assistant?.content).toEqual(HISTORICAL_CONTENT);
  171. expect(bodies[0]!.messages).toContainEqual(
  172. expect.objectContaining({
  173. role: "user",
  174. content: expect.arrayContaining([
  175. expect.objectContaining({
  176. type: "tool_result",
  177. tool_use_id: "old-read",
  178. content: "Report content",
  179. }),
  180. ]),
  181. }),
  182. );
  183. await runtime.executeTurn("Continue the same task again");
  184. expect(bodies).toHaveLength(2);
  185. expect(
  186. bodies[1]!.messages.find((message) => message.role === "assistant")?.content,
  187. ).toEqual(assistant?.content);
  188. const canonical = requests[0]!.messages.find((message) => message.role === "assistant");
  189. expect(canonical).toMatchObject({ providerId: source, modelId: MODEL_ID });
  190. expect(canonical?.content).toEqual(
  191. expect.arrayContaining([
  192. {
  193. type: "reasoning",
  194. text: "Historical thinking",
  195. providerOptions: { anthropic: { signature: SIGNATURE } },
  196. },
  197. {
  198. type: "reasoning",
  199. text: "",
  200. providerOptions: { anthropic: { redactedData: REDACTED_DATA } },
  201. },
  202. ]),
  203. );
  204. expect(snapshot()).toEqual(migrated);
  205. } finally {
  206. runtime?.beginShutdown();
  207. vi.unstubAllGlobals();
  208. db.close();
  209. store.close();
  210. await rm(root, { recursive: true, force: true });
  211. }
  212. },
  213. );
  214. },
  215. );
  216. function observeModel(model: Model, requests: ModelRequest[]): Model {
  217. return {
  218. ...model,
  219. bind: (options) => observeModel(model.bind(options), requests),
  220. generateText(request) {
  221. requests.push(request);
  222. return model.generateText(request);
  223. },
  224. streamText(request) {
  225. requests.push(request);
  226. return model.streamText(request);
  227. },
  228. };
  229. }
  230. async function seedHistory(input: {
  231. db: DatabaseSync;
  232. store: ReturnType<typeof createSqliteSessionStore>;
  233. root: string;
  234. sessionID: SessionId;
  235. providerId: string;
  236. }) {
  237. const { db, store, root, sessionID, providerId } = input;
  238. const legacy = providerId.startsWith("builtin:");
  239. await store.createSession({
  240. id: sessionID,
  241. projectID: createProjectId("reasoning-replay"),
  242. directory: root,
  243. slug: "replay",
  244. title: "Replay",
  245. version: "old",
  246. });
  247. const modelSelection = { providerId, modelId: MODEL_ID, options: { reasoningLevel: "disabled" } };
  248. // 已发布旧格式直接写入 SQLite,避免用新版 writer 生成伪旧数据。
  249. const insert = db.prepare(
  250. "insert into message(id,session_id,sequence,time_created,time_updated,data) values(?,?,?,?,?,?)",
  251. );
  252. insert.run(
  253. USER_ID,
  254. sessionID,
  255. 1,
  256. 1,
  257. 1,
  258. JSON.stringify({
  259. role: "user",
  260. agent: "zcode-agent",
  261. time: { created: 1 },
  262. ...(legacy
  263. ? { model: { providerID: providerId, modelID: MODEL_ID, variant: "disabled" } }
  264. : { modelSelection }),
  265. }),
  266. );
  267. insert.run(
  268. ASSISTANT_ID,
  269. sessionID,
  270. 2,
  271. 2,
  272. 3,
  273. JSON.stringify({
  274. role: "assistant",
  275. time: { created: 2, completed: 3 },
  276. parentID: USER_ID,
  277. ...(legacy
  278. ? { providerID: providerId, modelID: MODEL_ID, variant: "disabled" }
  279. : { providerId, modelId: MODEL_ID, reasoningLevel: "disabled" }),
  280. mode: "build",
  281. agent: "zcode-agent",
  282. path: { cwd: root, root },
  283. cost: 0,
  284. tokens: { input: 20, output: 5, reasoning: 2, cache: { read: 0, write: 0 } },
  285. finish: "tool-calls",
  286. }),
  287. );
  288. db.prepare(
  289. "insert into session_entry(id,session_id,type,time_created,time_updated,data) values(?,?,?,?,?,?)",
  290. ).run(
  291. `${sessionID}:runtime-model-selection`,
  292. sessionID,
  293. SESSION_ENTRY_MODEL_SELECTION,
  294. 1,
  295. 1,
  296. JSON.stringify(
  297. legacy ? { providerId, modelId: MODEL_ID, thoughtLevel: "disabled" } : { modelSelection },
  298. ),
  299. );
  300. for (const [id, text, metadata] of [
  301. ["signed", "Historical thinking", { anthropic: { signature: SIGNATURE } }],
  302. ["redacted", "", { anthropic: { redactedData: REDACTED_DATA } }],
  303. ] as const) {
  304. await store.savePart({
  305. id: createPartId(id),
  306. sessionID,
  307. messageID: ASSISTANT_ID,
  308. type: "reasoning",
  309. text,
  310. metadata,
  311. time: { start: 2, end: 3 },
  312. });
  313. }
  314. for (const [messageID, text] of [
  315. [USER_ID, "Inspect report"],
  316. [ASSISTANT_ID, "Inspecting report"],
  317. ] as const) {
  318. await store.savePart({
  319. id: createPartId(`${messageID}-text`),
  320. sessionID,
  321. messageID,
  322. type: "text",
  323. text,
  324. time: { start: 1, end: 3 },
  325. });
  326. }
  327. await store.savePart({
  328. id: createPartId("read"),
  329. sessionID,
  330. messageID: ASSISTANT_ID,
  331. type: "tool",
  332. tool: "Read",
  333. callID: "old-read",
  334. state: {
  335. status: "completed",
  336. input: { file_path: "report.txt" },
  337. output: "Report content",
  338. title: "Report",
  339. metadata: {},
  340. time: { start: 2, end: 3 },
  341. },
  342. });
  343. }
  344. function modelResponse(streaming: boolean): Response {
  345. const message = {
  346. id: "msg_replay",
  347. model: MODEL_ID,
  348. role: "assistant",
  349. type: "message",
  350. stop_reason: "end_turn",
  351. stop_sequence: null,
  352. usage: { input_tokens: 20, output_tokens: 1 },
  353. content: [{ type: "text", text: "done" }],
  354. };
  355. if (!streaming)
  356. return new Response(JSON.stringify(message), {
  357. headers: { "content-type": "application/json" },
  358. });
  359. const events = [
  360. {
  361. type: "message_start",
  362. message: {
  363. ...message,
  364. content: [],
  365. stop_reason: null,
  366. usage: { input_tokens: 20, output_tokens: 0 },
  367. },
  368. },
  369. { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
  370. { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "done" } },
  371. { type: "content_block_stop", index: 0 },
  372. {
  373. type: "message_delta",
  374. delta: { stop_reason: "end_turn", stop_sequence: null },
  375. usage: { output_tokens: 1 },
  376. },
  377. { type: "message_stop" },
  378. ];
  379. return new Response(
  380. events.map((event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(""),
  381. { headers: { "content-type": "text/event-stream" } },
  382. );
  383. }