zcodeSessionRestore.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. ZCODE_PROTOCOL_NAME,
  4. ZCODE_PROTOCOL_VERSION,
  5. type ZCodeMessageWithParts,
  6. type ZCodeSessionStateSnapshot,
  7. type ZCodeTaskSnapshot,
  8. } from "@zcode/shared";
  9. import {
  10. readDesktopContinuousSessionRestoreSnapshot,
  11. readWebRemoteReplayableSessionConfigOptions,
  12. } from "../src/lib/zcodeSessionRestore.js";
  13. const workspace = {
  14. workspacePath: "/workspace/app",
  15. workspaceIdentity: "ssh://dev/workspace/app",
  16. workspaceKey: "ssh://dev/workspace/app",
  17. };
  18. const model = { providerId: "glm", modelId: "glm-4.6" };
  19. function createSnapshot(params: {
  20. title?: string;
  21. messages?: ZCodeMessageWithParts[];
  22. } = {}): ZCodeSessionStateSnapshot {
  23. return {
  24. protocol: {
  25. name: ZCODE_PROTOCOL_NAME,
  26. version: ZCODE_PROTOCOL_VERSION,
  27. },
  28. session: {
  29. sessionId: "sess_1",
  30. workspace,
  31. sessionKind: "interactive",
  32. title: params.title ?? "Existing session",
  33. mode: "build",
  34. status: "idle",
  35. model,
  36. createdAt: 1,
  37. updatedAt: 2,
  38. },
  39. settings: {
  40. model: {
  41. current: model,
  42. available: [{ ref: model, label: "GLM 4.6" }],
  43. },
  44. thoughtLevel: {
  45. enabled: false,
  46. available: [],
  47. },
  48. mode: {
  49. current: "build",
  50. },
  51. },
  52. projection: {
  53. sessionId: "sess_1",
  54. status: "idle",
  55. mode: "build",
  56. turnCount: 0,
  57. totalTokenCount: 0,
  58. contextUsed: 0,
  59. contextWindow: 128000,
  60. pendingPermissions: [],
  61. activeToolCalls: [],
  62. backgroundJobs: [],
  63. },
  64. runtime: {
  65. eventSeq: 0,
  66. stateRevision: 1,
  67. deliveryKind: "desktop-continuous",
  68. pendingRequestIds: [],
  69. },
  70. messages: params.messages ?? [],
  71. };
  72. }
  73. function createLegacyTaskSnapshot(): ZCodeTaskSnapshot {
  74. return {
  75. meta: {
  76. taskId: "sess_1",
  77. traceId: "trace-legacy",
  78. title: "Legacy task",
  79. workspacePath: workspace.workspacePath,
  80. workspaceIdentity: workspace.workspaceIdentity,
  81. createdAt: 1,
  82. updatedAt: 2,
  83. mode: "build",
  84. provider: "glm",
  85. status: "completed",
  86. },
  87. messages: [
  88. {
  89. role: "user",
  90. content: "old prompt",
  91. timestamp: 1,
  92. },
  93. ],
  94. };
  95. }
  96. describe("readDesktopContinuousSessionRestoreSnapshot", () => {
  97. it("resumes historical desktop session before reading the limited snapshot", async () => {
  98. const calls: string[] = [];
  99. let active = false;
  100. const zcodeSessionService = {
  101. resumeSession: vi.fn(async () => {
  102. calls.push("resume");
  103. active = true;
  104. return createSnapshot({ title: "Resumed session" });
  105. }),
  106. readSession: vi.fn(async () => {
  107. calls.push("read");
  108. if (!active) {
  109. throw new Error("Session is not active: sess_1");
  110. }
  111. return createSnapshot({ title: "Read session" });
  112. }),
  113. };
  114. const restoreParams: Parameters<typeof readDesktopContinuousSessionRestoreSnapshot>[0] = {
  115. zcodeSessionService,
  116. workspacePath: workspace.workspacePath,
  117. workspaceIdentity: workspace.workspaceIdentity,
  118. sessionId: "sess_1",
  119. messageLimit: 30,
  120. model: { providerId: "custom-openai", modelId: "deepseek-v4-flash" },
  121. thoughtLevel: "high",
  122. };
  123. const result = await readDesktopContinuousSessionRestoreSnapshot(restoreParams);
  124. expect(calls).toEqual(["resume", "read"]);
  125. expect(zcodeSessionService.resumeSession).toHaveBeenCalledWith({
  126. workspacePath: workspace.workspacePath,
  127. workspaceIdentity: workspace.workspaceIdentity,
  128. sessionId: "sess_1",
  129. model: { providerId: "custom-openai", modelId: "deepseek-v4-flash" },
  130. thoughtLevel: "high",
  131. });
  132. expect(zcodeSessionService.readSession).toHaveBeenCalledWith({
  133. workspacePath: workspace.workspacePath,
  134. workspaceIdentity: workspace.workspaceIdentity,
  135. sessionId: "sess_1",
  136. deliveryKind: "desktop-continuous",
  137. messageLimit: 30,
  138. });
  139. expect(result.resumedSessionSnapshot?.session.title).toBe("Resumed session");
  140. expect(result.snapshot.meta.title).toBe("Read session");
  141. });
  142. it("falls back to legacy task snapshot when the protocol session is missing", async () => {
  143. const legacySnapshot = createLegacyTaskSnapshot();
  144. const zcodeSessionService = {
  145. resumeSession: vi.fn(async () => {
  146. throw new Error("Session not found: sess_1");
  147. }),
  148. readSession: vi.fn(async () => createSnapshot()),
  149. };
  150. const zcodeTaskService = {
  151. getTaskSnapshot: vi.fn(async () => legacySnapshot),
  152. };
  153. const result = await readDesktopContinuousSessionRestoreSnapshot({
  154. zcodeSessionService,
  155. zcodeTaskService,
  156. workspacePath: workspace.workspacePath,
  157. workspaceIdentity: workspace.workspaceIdentity,
  158. sessionId: "sess_1",
  159. messageLimit: 30,
  160. });
  161. expect(result.usedLegacySnapshot).toBe(true);
  162. expect(result.resumedSessionSnapshot).toBeUndefined();
  163. expect(result.snapshot.meta.title).toBe("Legacy task");
  164. expect(zcodeSessionService.readSession).not.toHaveBeenCalled();
  165. expect(zcodeTaskService.getTaskSnapshot).toHaveBeenCalledWith({
  166. taskId: "sess_1",
  167. workspacePath: workspace.workspacePath,
  168. workspaceIdentity: workspace.workspaceIdentity,
  169. messageLimit: 30,
  170. clientMode: "desktop-continuous",
  171. });
  172. });
  173. it("falls back to task snapshot when the historical runtime model is unavailable", async () => {
  174. const legacySnapshot = createLegacyTaskSnapshot();
  175. const unavailableModelError = Object.assign(
  176. new Error("历史任务使用的模型已不可用,请选择当前可用模型后继续。"),
  177. { code: "ZCODE_RUNTIME_MODEL_UNAVAILABLE" },
  178. );
  179. const zcodeSessionService = {
  180. resumeSession: vi.fn(async () => {
  181. throw unavailableModelError;
  182. }),
  183. readSession: vi.fn(async () => createSnapshot()),
  184. };
  185. const zcodeTaskService = {
  186. getTaskSnapshot: vi.fn(async () => legacySnapshot),
  187. };
  188. const result = await readDesktopContinuousSessionRestoreSnapshot({
  189. zcodeSessionService,
  190. zcodeTaskService,
  191. workspacePath: workspace.workspacePath,
  192. workspaceIdentity: workspace.workspaceIdentity,
  193. sessionId: "sess_1",
  194. messageLimit: 30,
  195. model: { providerId: "removed-provider", modelId: "removed-model" },
  196. });
  197. expect(result.usedLegacySnapshot).toBe(true);
  198. expect(result.resumedSessionSnapshot).toBeUndefined();
  199. expect(result.restoreWarning).toMatchObject({
  200. code: "ZCODE_RUNTIME_MODEL_UNAVAILABLE",
  201. message: "历史任务使用的模型已不可用,请选择当前可用模型后继续。",
  202. taskId: "sess_1",
  203. });
  204. expect(result.snapshot.meta.title).toBe("Legacy task");
  205. expect(zcodeSessionService.readSession).not.toHaveBeenCalled();
  206. expect(zcodeTaskService.getTaskSnapshot).toHaveBeenCalledWith({
  207. taskId: "sess_1",
  208. workspacePath: workspace.workspacePath,
  209. workspaceIdentity: workspace.workspaceIdentity,
  210. messageLimit: 30,
  211. clientMode: "desktop-continuous",
  212. });
  213. });
  214. });
  215. describe("readWebRemoteReplayableSessionConfigOptions", () => {
  216. it("resumes with the historical model before reading active mobile task toolbar settings", async () => {
  217. const calls: string[] = [];
  218. const historicalModel = {
  219. providerId: "china-llm-zcode-dev:demo",
  220. modelId: "deepseek-v4-flash",
  221. };
  222. const zcodeSessionService = {
  223. resumeSession: vi.fn(async () => {
  224. calls.push("resume");
  225. return createSnapshot({ title: "Mobile resumed session" });
  226. }),
  227. readSession: vi.fn(async () => {
  228. calls.push("read");
  229. return createSnapshot({
  230. title: "Mobile session",
  231. });
  232. }),
  233. };
  234. const restoreParams: Parameters<typeof readWebRemoteReplayableSessionConfigOptions>[0] = {
  235. zcodeSessionService,
  236. workspacePath: workspace.workspacePath,
  237. workspaceIdentity: workspace.workspaceIdentity,
  238. sessionId: "sess_1",
  239. model: historicalModel,
  240. thoughtLevel: "high",
  241. };
  242. const configOptions = await readWebRemoteReplayableSessionConfigOptions(restoreParams);
  243. expect(calls).toEqual(["resume", "read"]);
  244. expect(zcodeSessionService.resumeSession).toHaveBeenCalledWith({
  245. workspacePath: workspace.workspacePath,
  246. workspaceIdentity: workspace.workspaceIdentity,
  247. sessionId: "sess_1",
  248. model: historicalModel,
  249. thoughtLevel: "high",
  250. });
  251. expect(zcodeSessionService.readSession).toHaveBeenCalledWith({
  252. workspacePath: workspace.workspacePath,
  253. workspaceIdentity: workspace.workspaceIdentity,
  254. sessionId: "sess_1",
  255. deliveryKind: "web-remote-replayable",
  256. messageLimit: 1,
  257. });
  258. expect(configOptions?.map((option) => option.category)).toEqual([
  259. "model",
  260. "mode",
  261. ]);
  262. });
  263. it("includes thought level from replayable session settings when enabled", async () => {
  264. const snapshot = createSnapshot();
  265. const zcodeSessionService = {
  266. readSession: vi.fn(async () => ({
  267. ...snapshot,
  268. settings: {
  269. ...snapshot.settings,
  270. thoughtLevel: {
  271. enabled: true,
  272. current: "high",
  273. available: [
  274. { value: "low", label: "Low" },
  275. { value: "high", label: "High" },
  276. ],
  277. },
  278. },
  279. })),
  280. resumeSession: vi.fn(),
  281. };
  282. const configOptions = await readWebRemoteReplayableSessionConfigOptions({
  283. zcodeSessionService,
  284. workspacePath: workspace.workspacePath,
  285. workspaceIdentity: workspace.workspaceIdentity,
  286. sessionId: "sess_1",
  287. });
  288. expect(configOptions?.map((option) => option.category)).toEqual([
  289. "model",
  290. "mode",
  291. "thought_level",
  292. ]);
  293. expect(
  294. configOptions?.find((option) => option.category === "thought_level")
  295. ?.currentValue,
  296. ).toBe("high");
  297. });
  298. it("returns null for legacy tasks without an active protocol session", async () => {
  299. const zcodeSessionService = {
  300. readSession: vi.fn(async () => {
  301. throw new Error("Session not found: sess_1");
  302. }),
  303. resumeSession: vi.fn(),
  304. };
  305. await expect(
  306. readWebRemoteReplayableSessionConfigOptions({
  307. zcodeSessionService,
  308. workspacePath: workspace.workspacePath,
  309. workspaceIdentity: workspace.workspaceIdentity,
  310. sessionId: "sess_1",
  311. }),
  312. ).resolves.toBeNull();
  313. });
  314. });