session-model-selection-migration.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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 { afterEach, beforeEach, describe, expect, it } from "vitest";
  6. import { SESSION_ENTRY_MODEL_SELECTION, createProjectId, createSessionId } from "@zcode/contracts";
  7. import { createSqliteSessionStore } from "../src/storage/session-store/sqlite-session-store.js";
  8. const sessionID = createSessionId("legacy-selection");
  9. const oldProvider = "builtin:bigmodel-coding-plan";
  10. const newProvider = "account:bigmodel-individual-coding-plan";
  11. const current = {
  12. providerId: newProvider,
  13. modelId: "GLM-5.3",
  14. options: { reasoningLevel: "high" },
  15. };
  16. describe("旧 Session 当前选择的单次迁移", () => {
  17. let root: string;
  18. let store: Awaited<ReturnType<typeof createSqliteSessionStore>>;
  19. let db: DatabaseSync;
  20. let opened = false;
  21. beforeEach(async () => {
  22. root = await mkdtemp(join(tmpdir(), "zcode-selection-migration-"));
  23. const dbPath = join(root, "session.sqlite");
  24. store = await createSqliteSessionStore({ dbPath });
  25. opened = true;
  26. db = new DatabaseSync(dbPath);
  27. await store.createSession({
  28. id: sessionID,
  29. projectID: createProjectId("migration"),
  30. directory: root,
  31. slug: "migration",
  32. title: "Old history",
  33. version: "old",
  34. });
  35. // 此夹具只用新版建空表;删除尚未播种数据的 0020 记录,模拟升级前库。
  36. db.prepare("DELETE FROM schema_migration WHERE id = ?").run("0020_provider_model_selection");
  37. });
  38. const migrate = async (_input: { sessionID: typeof sessionID }) => {
  39. if (opened) store.close();
  40. opened = false;
  41. store = await createSqliteSessionStore({ dbPath: join(root, "session.sqlite") });
  42. opened = true;
  43. };
  44. afterEach(async () => {
  45. db.close();
  46. if (opened) store.close();
  47. await rm(root, { recursive: true, force: true });
  48. });
  49. const entry = async (data: unknown) =>
  50. store.saveSessionEntry({
  51. id: `${sessionID}:runtime-model-selection`,
  52. sessionID,
  53. type: SESSION_ENTRY_MODEL_SELECTION,
  54. touchSession: false,
  55. time: { created: 1, updated: 1 },
  56. data,
  57. });
  58. // 已发布 fixture 直接写磁盘;不能经过新版 writer 后假装是升级前数据。
  59. const legacyEntry = (data: unknown) => {
  60. db.prepare(
  61. "insert into session_entry(id, session_id, type, time_created, time_updated, data) values(?,?,?,?,?,?)",
  62. ).run(
  63. `${sessionID}:runtime-model-selection`,
  64. sessionID,
  65. SESSION_ENTRY_MODEL_SELECTION,
  66. 1,
  67. 1,
  68. JSON.stringify(data),
  69. );
  70. };
  71. const rawEntry = () =>
  72. JSON.parse(
  73. String(
  74. db
  75. .prepare("select data from session_entry where type = ?")
  76. .get(SESSION_ENTRY_MODEL_SELECTION)?.data,
  77. ),
  78. );
  79. const message = (data: unknown, id = "old-message", sequence = 1) => {
  80. db.prepare(
  81. "insert into message(id, session_id, sequence, time_created, time_updated, data) values(?,?,?,?,?,?)",
  82. ).run(id, sessionID, sequence, sequence, sequence, JSON.stringify(data));
  83. };
  84. const oldMessage = () =>
  85. message({
  86. role: "user",
  87. agent: "zcode-agent",
  88. time: { created: 1 },
  89. model: { providerID: oldProvider, modelID: "GLM-5.3", variant: "high" },
  90. });
  91. const read = async () =>
  92. (await store.sessionEntries({ sessionID, type: SESSION_ENTRY_MODEL_SELECTION })).at(-1)?.data;
  93. it("离线迁移旧消息并固定同域个人身份;消息旧成员和任务活动时间不变", async () => {
  94. oldMessage();
  95. const before = db.prepare("select data from message").get();
  96. const sessionBefore = await store.getSession(sessionID);
  97. await migrate({ sessionID });
  98. expect(await read()).toEqual(current);
  99. expect(rawEntry()).toEqual({ modelSelection: current });
  100. expect(JSON.parse(String(db.prepare("select data from message").get()?.data))).toMatchObject(
  101. JSON.parse(String(before?.data)),
  102. );
  103. expect((await store.getSession(sessionID))?.time).toEqual(sessionBefore?.time);
  104. await migrate({ sessionID });
  105. expect(await read()).toEqual(current);
  106. });
  107. it.each([{}, { providerId: "current" }, current])(
  108. "已有当前 entry %j 不从旧消息补值",
  109. async (data) => {
  110. oldMessage();
  111. await entry(data);
  112. await migrate({ sessionID });
  113. expect(await read()).toEqual(data);
  114. },
  115. );
  116. it("旧消息身份的损坏 options 不丢失可确定的模型身份", async () => {
  117. const selection = {
  118. providerId: oldProvider,
  119. modelId: "GLM-5.3",
  120. options: { reasoningLevel: 42 },
  121. };
  122. message({
  123. role: "user",
  124. modelSelection: selection,
  125. model: { providerID: "other", modelID: "other", variant: "high" },
  126. });
  127. await migrate({
  128. sessionID,
  129. });
  130. expect(await read()).toEqual({ providerId: newProvider, modelId: "GLM-5.3" });
  131. });
  132. it("重复打开幂等,新保存的选择不被后续启动覆盖", async () => {
  133. oldMessage();
  134. await Promise.all([migrate({ sessionID }), migrate({ sessionID })]);
  135. expect(await read()).toEqual(current);
  136. expect(
  137. db
  138. .prepare("select count(*) as count from session_entry where type = ?")
  139. .get(SESSION_ENTRY_MODEL_SELECTION)?.count,
  140. ).toBe(1);
  141. const userSelection = {
  142. providerId: "custom",
  143. modelId: "user-chosen",
  144. options: { reasoningLevel: "low" },
  145. };
  146. await entry(userSelection);
  147. await migrate({ sessionID });
  148. expect(await read()).toEqual(userSelection);
  149. });
  150. it("最近消息已有当前结构,不向更老的消息寻找替代选择", async () => {
  151. oldMessage();
  152. message({ role: "user", modelSelection: {} }, "current-message", 2);
  153. await migrate({ sessionID });
  154. expect(await read()).toBeUndefined();
  155. });
  156. it("未知退役身份不猜默认绑定,旧记录保持不变", async () => {
  157. legacyEntry({ providerId: "builtin:unknown", modelId: "old-model", thoughtLevel: "high" });
  158. const before = db.prepare("select data from session_entry").get();
  159. await migrate({ sessionID });
  160. expect(db.prepare("select data from session_entry").get()).toEqual(before);
  161. });
  162. it("真正旧 entry 的 thoughtLevel 仅在单向迁移时搬入 options", async () => {
  163. legacyEntry({ providerId: "custom", modelId: "old-model", thoughtLevel: "low" });
  164. await migrate({ sessionID });
  165. const row = db
  166. .prepare("select data from session_entry where type = ?")
  167. .get(SESSION_ENTRY_MODEL_SELECTION);
  168. expect(JSON.parse(String(row?.data))).toEqual({
  169. providerId: "custom",
  170. modelId: "old-model",
  171. thoughtLevel: "low",
  172. modelSelection: {
  173. providerId: "custom",
  174. modelId: "old-model",
  175. options: { reasoningLevel: "low" },
  176. },
  177. });
  178. });
  179. it.each([undefined, "high"])(
  180. "保留旧身份/档位和其他字段,普通更新只改新成员:%s",
  181. async (thoughtLevel) => {
  182. const legacy = {
  183. providerId: oldProvider,
  184. modelId: "GLM-5.3",
  185. ...(thoughtLevel ? { thoughtLevel } : {}),
  186. note: { preserve: true },
  187. };
  188. legacyEntry(legacy);
  189. expect(await read()).toBeUndefined();
  190. await migrate({ sessionID });
  191. const migrated = {
  192. providerId: newProvider,
  193. modelId: "GLM-5.3",
  194. ...(thoughtLevel ? { options: { reasoningLevel: thoughtLevel } } : {}),
  195. };
  196. expect(rawEntry()).toEqual({ ...legacy, modelSelection: migrated });
  197. expect(await read()).toEqual(migrated);
  198. const next = { providerId: "custom", modelId: "next-model" };
  199. await entry(next);
  200. await migrate({ sessionID });
  201. expect(rawEntry()).toEqual({ ...legacy, modelSelection: next });
  202. // 来源:790884b1ce server-operations.ts:3931-3953 的旧 reader 纯字段投影。
  203. // 不代表已启动旧 App;用该投影检查真实 JSON 仍恢复旧身份及 variant。
  204. const oldReader = (candidate: Record<string, unknown>) => {
  205. const modelId = typeof candidate.modelId === "string" ? candidate.modelId.trim() : "";
  206. const providerId =
  207. typeof candidate.providerId === "string" ? candidate.providerId.trim() : "";
  208. if (!modelId || !providerId) return undefined;
  209. const thoughtLevel =
  210. typeof candidate.thoughtLevel === "string" ? candidate.thoughtLevel.trim() : "";
  211. return {
  212. model: { modelId, providerId, ...(thoughtLevel ? { variant: thoughtLevel } : {}) },
  213. ...(thoughtLevel ? { thoughtLevel } : {}),
  214. };
  215. };
  216. expect(oldReader(rawEntry())).toEqual(oldReader(legacy));
  217. store.close();
  218. store = await createSqliteSessionStore({ dbPath: join(root, "session.sqlite") });
  219. expect(await read()).toEqual(next);
  220. },
  221. );
  222. it("无旧档位的自定义模型也只迁一次", async () => {
  223. const legacy = { providerId: "custom-provider", modelId: "custom/model" };
  224. legacyEntry(legacy);
  225. await migrate({ sessionID });
  226. expect(rawEntry()).toEqual({ ...legacy, modelSelection: legacy });
  227. const before = db.prepare("select * from session_entry").get();
  228. await migrate({ sessionID });
  229. expect(db.prepare("select * from session_entry").get()).toEqual(before);
  230. });
  231. it.each([null, {}, { providerId: "new" }])(
  232. "新选择 %j 不复活保留的旧字段/旧消息",
  233. async (selection) => {
  234. const legacy = { providerId: oldProvider, modelId: "GLM-5.3", thoughtLevel: "high" };
  235. legacyEntry(legacy);
  236. oldMessage();
  237. await migrate({ sessionID });
  238. await entry(selection);
  239. store.close();
  240. store = await createSqliteSessionStore({ dbPath: join(root, "session.sqlite") });
  241. await migrate({ sessionID });
  242. expect(rawEntry()).toEqual({ ...legacy, modelSelection: selection });
  243. expect(await read()).toEqual(selection);
  244. },
  245. );
  246. it("数据库写失败不损坏旧快照或留下部分迁移", async () => {
  247. legacyEntry({ providerId: oldProvider, modelId: "GLM-5.3", thoughtLevel: "high" });
  248. const before = db.prepare("select * from session_entry").get();
  249. db.exec(
  250. "create trigger block_selection_update before update on session_entry begin select raise(abort, 'fixture write failure'); end",
  251. );
  252. await expect(migrate({ sessionID })).rejects.toMatchObject({
  253. cause: expect.objectContaining({ message: "fixture write failure" }),
  254. });
  255. expect(db.prepare("select * from session_entry").get()).toEqual(before);
  256. db.exec("drop trigger block_selection_update");
  257. await migrate({ sessionID });
  258. expect(await read()).toEqual(current);
  259. });
  260. });