zcodeSessionService.test.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942
  1. import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { dirname, join } from "node:path";
  4. import { afterEach, describe, expect, it, vi } from "vitest";
  5. import type { IZCodeAgentService } from "@zcode/services";
  6. import type { ZCodeAgentMcpServer, ZCodeSessionStateSnapshot } from "@zcode/shared";
  7. import { createZCodeSessionService } from "@zcode/services/node";
  8. import type { ZCodeTaskIndexSyncer } from "../src/zcode-agent/zcodeTaskIndexSyncer.js";
  9. import { getLegacyTaskSessionSnapshotPath, setDataBaseDir } from "../src/paths.js";
  10. const tempDirs: string[] = [];
  11. afterEach(() => {
  12. setDataBaseDir(null);
  13. while (tempDirs.length > 0) {
  14. const dir = tempDirs.pop();
  15. if (dir) {
  16. rmSync(dir, { recursive: true, force: true });
  17. }
  18. }
  19. });
  20. function useTempDataBaseDir(): string {
  21. const dir = mkdtempSync(join(tmpdir(), "zcode-session-service-"));
  22. tempDirs.push(dir);
  23. setDataBaseDir(dir);
  24. return dir;
  25. }
  26. describe("createZCodeSessionService", () => {
  27. it("injects product CUA helper broker config before desktop-continuous session creation", async () => {
  28. const snapshot = {
  29. session: {
  30. sessionId: "session-cua",
  31. workspace: {
  32. workspacePath: "/workspace/app",
  33. workspaceIdentity: undefined,
  34. },
  35. },
  36. runtime: { eventSeq: 1, stateRevision: 1, pendingRequestIds: [] },
  37. settings: {},
  38. messages: [],
  39. } as unknown as ZCodeSessionStateSnapshot;
  40. const agentService = {
  41. createSession: vi.fn(async () => snapshot),
  42. } as unknown as IZCodeAgentService;
  43. // services 只负责建会话前把 MCP 配置交给 producer 的 resolver;改写细节由 producer 自己的测试覆盖。
  44. // 这里用测试自己的 resolver,不依赖私有 producer 的注入实现(开源占位包不改写配置)。
  45. const resolver = {
  46. resolveMcpServers: vi.fn(async (servers: ZCodeAgentMcpServer[] | undefined) =>
  47. servers?.map((server) =>
  48. "command" in server
  49. ? {
  50. ...server,
  51. args: [
  52. ...(server.args ?? []),
  53. "--permission-broker-socket",
  54. "/tmp/zcode-cua/helper.sock",
  55. ],
  56. }
  57. : server,
  58. ),
  59. ),
  60. };
  61. const service = createZCodeSessionService({
  62. agentService,
  63. cuaProductMcpServerResolver: resolver,
  64. });
  65. await service.createSession({
  66. workspacePath: "/workspace/app",
  67. mcpServers: [
  68. {
  69. name: "plugin:computer-use:computer-use",
  70. command: "uvx",
  71. args: ["zcode-cua"],
  72. env: [
  73. { name: "ZCODE_PLUGIN_ID", value: "computer-use@zcode-plugins-official" },
  74. {
  75. name: "ZCODE_CUA_PLUGIN_AUTHORITY",
  76. value: "dev.zcode.cua-helper/dev",
  77. },
  78. ],
  79. },
  80. ],
  81. });
  82. const createParams = vi.mocked(agentService.createSession).mock.calls[0]?.[0];
  83. const server = createParams?.mcpServers?.[0];
  84. expect(resolver.resolveMcpServers).toHaveBeenCalledTimes(1);
  85. expect(server && "command" in server ? server.args : []).toEqual([
  86. "zcode-cua",
  87. "--permission-broker-socket",
  88. "/tmp/zcode-cua/helper.sock",
  89. ]);
  90. });
  91. it("does not sync deferred draft sessions into the task index", async () => {
  92. const snapshot = {
  93. session: {
  94. sessionId: "draft-1",
  95. workspace: {
  96. workspacePath: "/workspace/app",
  97. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  98. },
  99. },
  100. };
  101. const agentService = {
  102. createSession: vi.fn(async () => snapshot),
  103. } as unknown as IZCodeAgentService;
  104. const taskIndexSyncer = {
  105. ensureSessionSubscription: vi.fn(),
  106. syncSnapshotAndBroadcast: vi.fn(),
  107. };
  108. const service = createZCodeSessionService({
  109. agentService,
  110. taskIndexSyncer: taskIndexSyncer as never,
  111. });
  112. await expect(
  113. service.createSession({
  114. workspacePath: "/workspace/app",
  115. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  116. persistence: "deferred",
  117. }),
  118. ).resolves.toBe(snapshot);
  119. // Bugfix: zcodeSessionService 会为 createSession 补 sessionTraceId 贯穿日志链路。
  120. // 这个 deferred draft 用例只验证草稿不进入 task index,因此需要显式接受并校验 trace 字段。
  121. expect(agentService.createSession).toHaveBeenCalledWith({
  122. workspacePath: "/workspace/app",
  123. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  124. persistence: "deferred",
  125. sessionTraceId: expect.any(String),
  126. });
  127. expect(taskIndexSyncer.ensureSessionSubscription).not.toHaveBeenCalled();
  128. expect(taskIndexSyncer.syncSnapshotAndBroadcast).not.toHaveBeenCalled();
  129. });
  130. it("does not sync deferred draft session model changes into the task index", async () => {
  131. const snapshot = {
  132. session: {
  133. sessionId: "draft-1",
  134. workspace: {
  135. workspacePath: "/workspace/app",
  136. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  137. },
  138. },
  139. } as unknown as ZCodeSessionStateSnapshot;
  140. const agentService = {
  141. createSession: vi.fn(async () => snapshot),
  142. setModel: vi.fn(async () => snapshot),
  143. } as unknown as IZCodeAgentService;
  144. const taskIndexSyncer = {
  145. ensureSessionSubscription: vi.fn(),
  146. syncSnapshotAndBroadcast: vi.fn(),
  147. } as unknown as ZCodeTaskIndexSyncer;
  148. const service = createZCodeSessionService({ agentService, taskIndexSyncer });
  149. await service.createSession({
  150. workspacePath: "/workspace/app",
  151. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  152. persistence: "deferred",
  153. });
  154. await expect(
  155. service.setModel({
  156. workspacePath: "/workspace/app",
  157. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  158. sessionId: "draft-1",
  159. model: { providerId: "current-provider", modelId: "current-model" },
  160. }),
  161. ).resolves.toBe(snapshot);
  162. expect(agentService.setModel).toHaveBeenCalledWith({
  163. workspacePath: "/workspace/app",
  164. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  165. sessionId: "draft-1",
  166. model: { providerId: "current-provider", modelId: "current-model" },
  167. });
  168. expect(taskIndexSyncer.ensureSessionSubscription).not.toHaveBeenCalled();
  169. expect(taskIndexSyncer.syncSnapshotAndBroadcast).not.toHaveBeenCalled();
  170. });
  171. it("promotes deferred draft sessions before replayable task facade owns them", async () => {
  172. const snapshot = {
  173. session: {
  174. sessionId: "draft-1",
  175. workspace: {
  176. workspacePath: "/workspace/app",
  177. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  178. },
  179. },
  180. } as unknown as ZCodeSessionStateSnapshot;
  181. const agentService = {
  182. createSession: vi.fn(async () => snapshot),
  183. setModel: vi.fn(async () => snapshot),
  184. } as unknown as IZCodeAgentService;
  185. const taskIndexSyncer = {
  186. ensureSessionSubscription: vi.fn(),
  187. syncSnapshotAndBroadcast: vi.fn(),
  188. } as unknown as ZCodeTaskIndexSyncer;
  189. const service = createZCodeSessionService({ agentService, taskIndexSyncer });
  190. await service.createSession({
  191. workspacePath: "/workspace/app",
  192. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  193. persistence: "deferred",
  194. });
  195. await service.promoteDeferredDraftSession({
  196. workspacePath: "/workspace/app",
  197. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  198. sessionId: "draft-1",
  199. });
  200. vi.mocked(taskIndexSyncer.ensureSessionSubscription).mockClear();
  201. vi.mocked(taskIndexSyncer.syncSnapshotAndBroadcast).mockClear();
  202. await expect(
  203. service.setModel({
  204. workspacePath: "/workspace/app",
  205. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  206. sessionId: "draft-1",
  207. model: { providerId: "current-provider", modelId: "current-model" },
  208. }),
  209. ).resolves.toBe(snapshot);
  210. expect(taskIndexSyncer.ensureSessionSubscription).toHaveBeenCalledWith({
  211. workspacePath: "/workspace/app",
  212. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  213. sessionId: "draft-1",
  214. });
  215. expect(taskIndexSyncer.syncSnapshotAndBroadcast).toHaveBeenCalledWith(snapshot, {
  216. modelOverride: "current-provider/current-model",
  217. broadcastReason: "task_model_changed",
  218. });
  219. });
  220. it("uses a conditional stale-draft close after a remote session is promoted", async () => {
  221. const snapshot = {
  222. session: {
  223. sessionId: "remote-task-1",
  224. workspace: {
  225. workspacePath: "/workspace/app",
  226. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  227. },
  228. },
  229. } as unknown as ZCodeSessionStateSnapshot;
  230. let persistence: "deferred" | "immediate" = "deferred";
  231. const closeSession: IZCodeAgentService["closeSession"] = vi.fn(async (params) => {
  232. if (params.expectedPersistence && params.expectedPersistence !== persistence) {
  233. return false;
  234. }
  235. return true;
  236. });
  237. const agentService = {
  238. closeSession,
  239. createSession: vi.fn(async () => snapshot),
  240. } as unknown as IZCodeAgentService;
  241. const taskIndexSyncer = {
  242. ensureSessionSubscription: vi.fn(),
  243. syncSnapshotAndBroadcast: vi.fn(),
  244. } as unknown as ZCodeTaskIndexSyncer;
  245. const service = createZCodeSessionService({ agentService, taskIndexSyncer });
  246. const target = {
  247. workspacePath: "/workspace/app",
  248. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  249. sessionId: "remote-task-1",
  250. };
  251. await service.createSession({
  252. workspacePath: target.workspacePath,
  253. workspaceIdentity: target.workspaceIdentity,
  254. persistence: "deferred",
  255. });
  256. // 远程端首发会把同一个 session 原地提升;设置页异步闭包仍可能持有旧 draftSessionId。
  257. persistence = "immediate";
  258. await service.promoteDeferredDraftSession(target);
  259. await expect(service.closeDeferredDraftSession(target)).resolves.toBe(false);
  260. expect(closeSession).toHaveBeenCalledWith({
  261. ...target,
  262. expectedPersistence: "deferred",
  263. });
  264. expect(taskIndexSyncer.ensureSessionSubscription).toHaveBeenCalledWith(target);
  265. });
  266. it("only closes a draft when the Agent confirms it is still deferred", async () => {
  267. const closeSession = vi.fn(async () => false);
  268. const agentService = { closeSession } as unknown as IZCodeAgentService;
  269. const service = createZCodeSessionService({ agentService });
  270. await expect(
  271. service.closeDeferredDraftSession({
  272. workspacePath: "/workspace/app",
  273. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  274. sessionId: "draft-promoted-elsewhere",
  275. }),
  276. ).resolves.toBe(false);
  277. expect(closeSession).toHaveBeenCalledWith({
  278. workspacePath: "/workspace/app",
  279. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  280. sessionId: "draft-promoted-elsewhere",
  281. expectedPersistence: "deferred",
  282. });
  283. });
  284. it("does not fall back to unconditional close when an older Agent rejects conditional close", async () => {
  285. const closeSession = vi.fn(async () => {
  286. throw new Error("Invalid params: expectedPersistence");
  287. });
  288. const agentService = { closeSession } as unknown as IZCodeAgentService;
  289. const service = createZCodeSessionService({ agentService });
  290. await expect(
  291. service.closeDeferredDraftSession({
  292. workspacePath: "/workspace/app",
  293. sessionId: "draft-on-old-agent",
  294. }),
  295. ).resolves.toBe(false);
  296. expect(closeSession).toHaveBeenCalledTimes(1);
  297. });
  298. it("delegates workspace initialization and read paths to the agent service", async () => {
  299. const agentService = {
  300. initialize: vi.fn(async () => ({
  301. available: true,
  302. workspaceKey: "remote:ssh:dev:/workspace/app",
  303. protocolName: "ZCode Protocol",
  304. protocolVersion: 1,
  305. transportKind: "stdio",
  306. })),
  307. readSessionMessages: vi.fn(async () => []),
  308. readSessionEvents: vi.fn(async () => []),
  309. } as unknown as IZCodeAgentService;
  310. const service = createZCodeSessionService({ agentService });
  311. await expect(
  312. service.initializeWorkspace({
  313. workspacePath: "/workspace/app",
  314. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  315. }),
  316. ).resolves.toMatchObject({
  317. available: true,
  318. workspaceKey: "remote:ssh:dev:/workspace/app",
  319. });
  320. await service.readSessionMessages({
  321. workspacePath: "/workspace/app",
  322. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  323. sessionId: "session-1",
  324. limit: 20,
  325. });
  326. await service.readSessionEvents({
  327. workspacePath: "/workspace/app",
  328. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  329. sessionId: "session-1",
  330. afterSeq: 4,
  331. });
  332. expect(agentService.initialize).toHaveBeenCalledWith({
  333. workspacePath: "/workspace/app",
  334. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  335. });
  336. expect(agentService.readSessionMessages).toHaveBeenCalledWith({
  337. workspacePath: "/workspace/app",
  338. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  339. sessionId: "session-1",
  340. limit: 20,
  341. });
  342. expect(agentService.readSessionEvents).toHaveBeenCalledWith({
  343. workspacePath: "/workspace/app",
  344. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  345. sessionId: "session-1",
  346. afterSeq: 4,
  347. });
  348. });
  349. it("repairs empty imported Claude protocol sessions from legacy snapshots", async () => {
  350. useTempDataBaseDir();
  351. const workspacePath = "/workspace/imported";
  352. const sessionId = "claude-import-empty";
  353. const legacyPath = getLegacyTaskSessionSnapshotPath(workspacePath, sessionId);
  354. mkdirSync(dirname(legacyPath), { recursive: true });
  355. writeFileSync(
  356. legacyPath,
  357. JSON.stringify({
  358. meta: {
  359. taskId: sessionId,
  360. traceId: "trace_imported",
  361. title: "Imported Claude",
  362. workspacePath,
  363. createdAt: 10,
  364. updatedAt: 20,
  365. migrationSource: "claudeCode",
  366. },
  367. messages: [
  368. { role: "user", content: "旧问题", timestamp: 10 },
  369. { role: "assistant", content: "旧回答", timestamp: 20 },
  370. ],
  371. }),
  372. "utf-8",
  373. );
  374. const emptySnapshot = {
  375. session: {
  376. sessionId,
  377. mode: "build",
  378. status: "idle",
  379. workspace: {
  380. workspacePath,
  381. workspaceKey: workspacePath,
  382. },
  383. },
  384. settings: {
  385. model: {
  386. current: { providerId: "glm", modelId: "glm-4.6" },
  387. available: [],
  388. },
  389. thoughtLevel: { enabled: true, current: "think", available: [] },
  390. mode: { current: "build" },
  391. },
  392. runtime: {
  393. eventSeq: 1,
  394. stateRevision: 2,
  395. pendingRequestIds: [],
  396. },
  397. messages: [],
  398. } as unknown as ZCodeSessionStateSnapshot;
  399. const repairedSnapshot = {
  400. ...emptySnapshot,
  401. messages: [
  402. { info: { role: "user" }, parts: [{ type: "text", text: "旧问题" }] },
  403. { info: { role: "assistant" }, parts: [{ type: "text", text: "旧回答" }] },
  404. ],
  405. } as unknown as ZCodeSessionStateSnapshot;
  406. const agentService = {
  407. resumeSession: vi.fn(async () => emptySnapshot),
  408. createSession: vi.fn(async () => repairedSnapshot),
  409. } as unknown as IZCodeAgentService;
  410. const taskIndexSyncer = {
  411. ensureSessionSubscription: vi.fn(),
  412. syncSnapshotAndBroadcast: vi.fn(),
  413. } as unknown as ZCodeTaskIndexSyncer;
  414. const service = createZCodeSessionService({ agentService, taskIndexSyncer });
  415. await expect(service.resumeSession({ workspacePath, sessionId })).resolves.toBe(
  416. repairedSnapshot,
  417. );
  418. expect(agentService.createSession).toHaveBeenCalledWith({
  419. workspacePath,
  420. workspaceIdentity: undefined,
  421. sessionId,
  422. mode: "build",
  423. model: { providerId: "glm", modelId: "glm-4.6" },
  424. thoughtLevel: "think",
  425. persistence: "immediate",
  426. importedHistory: {
  427. source: "claudeCode",
  428. title: "Imported Claude",
  429. createdAt: 10,
  430. updatedAt: 20,
  431. messages: [
  432. { role: "user", content: "旧问题", timestamp: 10 },
  433. { role: "assistant", content: "旧回答", timestamp: 20 },
  434. ],
  435. },
  436. });
  437. expect(taskIndexSyncer.syncSnapshotAndBroadcast).toHaveBeenCalledWith(
  438. repairedSnapshot,
  439. // Bugfix: resume 收敛是状态同步,广播 reason 改为 task_status_changed,避免全局 membership 重拉。
  440. { broadcastReason: "task_status_changed" },
  441. );
  442. });
  443. it("repairs imported Claude protocol sessions with legacy fixed message ids", async () => {
  444. useTempDataBaseDir();
  445. const workspacePath = "/workspace/imported";
  446. const sessionId = "claude-import-corrupted-order";
  447. const legacyPath = getLegacyTaskSessionSnapshotPath(workspacePath, sessionId);
  448. mkdirSync(dirname(legacyPath), { recursive: true });
  449. writeFileSync(
  450. legacyPath,
  451. JSON.stringify({
  452. meta: {
  453. taskId: sessionId,
  454. traceId: "trace_imported_corrupted",
  455. title: "Imported Claude Corrupted",
  456. workspacePath,
  457. createdAt: 10,
  458. updatedAt: 20,
  459. migrationSource: "claudeCode",
  460. },
  461. messages: [
  462. { role: "user", content: "正确问题", timestamp: 10 },
  463. { role: "assistant", content: "正确回答", timestamp: 20 },
  464. ],
  465. }),
  466. "utf-8",
  467. );
  468. const corruptedSnapshot = {
  469. session: {
  470. sessionId,
  471. mode: "build",
  472. status: "idle",
  473. workspace: {
  474. workspacePath,
  475. workspaceKey: workspacePath,
  476. },
  477. },
  478. settings: {
  479. model: {
  480. current: { providerId: "glm", modelId: "glm-4.6" },
  481. available: [],
  482. },
  483. thoughtLevel: { enabled: true, current: "think", available: [] },
  484. mode: { current: "build" },
  485. },
  486. runtime: {
  487. eventSeq: 1,
  488. stateRevision: 2,
  489. pendingRequestIds: [],
  490. },
  491. messages: [
  492. { info: { messageId: "msg_import_1", role: "assistant" }, parts: [] },
  493. { info: { messageId: "msg_import_0", role: "user" }, parts: [] },
  494. ],
  495. } as unknown as ZCodeSessionStateSnapshot;
  496. const repairedSnapshot = {
  497. ...corruptedSnapshot,
  498. messages: [
  499. {
  500. info: { messageId: "msg_repaired_0", role: "user" },
  501. parts: [{ type: "text", text: "正确问题" }],
  502. },
  503. {
  504. info: { messageId: "msg_repaired_1", role: "assistant" },
  505. parts: [{ type: "text", text: "正确回答" }],
  506. },
  507. ],
  508. } as unknown as ZCodeSessionStateSnapshot;
  509. const agentService = {
  510. resumeSession: vi.fn(async () => corruptedSnapshot),
  511. createSession: vi.fn(async () => repairedSnapshot),
  512. } as unknown as IZCodeAgentService;
  513. const service = createZCodeSessionService({ agentService });
  514. await expect(service.resumeSession({ workspacePath, sessionId })).resolves.toBe(
  515. repairedSnapshot,
  516. );
  517. expect(agentService.createSession).toHaveBeenCalledWith(
  518. expect.objectContaining({
  519. workspacePath,
  520. sessionId,
  521. importedHistory: expect.objectContaining({
  522. messages: [
  523. { role: "user", content: "正确问题", timestamp: 10 },
  524. { role: "assistant", content: "正确回答", timestamp: 20 },
  525. ],
  526. }),
  527. }),
  528. );
  529. });
  530. it("does not repair ordinary user-only sessions from accidental Claude legacy files", async () => {
  531. useTempDataBaseDir();
  532. const workspacePath = "/workspace/ordinary";
  533. const sessionId = "ordinary-user-only-session";
  534. const legacyPath = getLegacyTaskSessionSnapshotPath(workspacePath, sessionId);
  535. mkdirSync(dirname(legacyPath), { recursive: true });
  536. writeFileSync(
  537. legacyPath,
  538. JSON.stringify({
  539. meta: {
  540. taskId: sessionId,
  541. traceId: "trace_accidental_legacy",
  542. title: "Accidental Claude backup",
  543. workspacePath,
  544. createdAt: 10,
  545. updatedAt: 20,
  546. migrationSource: "claudeCode",
  547. },
  548. messages: [
  549. { role: "user", content: "不应该回填的问题", timestamp: 10 },
  550. { role: "assistant", content: "不应该回填的回答", timestamp: 20 },
  551. ],
  552. }),
  553. "utf-8",
  554. );
  555. const ordinarySnapshot = {
  556. session: {
  557. sessionId,
  558. mode: "build",
  559. status: "idle",
  560. workspace: {
  561. workspacePath,
  562. workspaceKey: workspacePath,
  563. },
  564. },
  565. settings: {
  566. model: {
  567. current: { providerId: "glm", modelId: "glm-4.6" },
  568. available: [],
  569. },
  570. thoughtLevel: { enabled: true, current: "think", available: [] },
  571. mode: { current: "build" },
  572. },
  573. runtime: {
  574. eventSeq: 1,
  575. stateRevision: 2,
  576. pendingRequestIds: [],
  577. },
  578. messages: [{ info: { messageId: "msg_ordinary_0", role: "user" }, parts: [] }],
  579. } as unknown as ZCodeSessionStateSnapshot;
  580. const agentService = {
  581. resumeSession: vi.fn(async () => ordinarySnapshot),
  582. createSession: vi.fn(),
  583. } as unknown as IZCodeAgentService;
  584. const service = createZCodeSessionService({ agentService });
  585. await expect(service.resumeSession({ workspacePath, sessionId })).resolves.toBe(
  586. ordinarySnapshot,
  587. );
  588. expect(agentService.createSession).not.toHaveBeenCalled();
  589. });
  590. it("asks the task index syncer to place desktop-created sessions at the grouped top", async () => {
  591. const snapshot = {
  592. session: {
  593. sessionId: "session-1",
  594. workspace: {
  595. workspacePath: "/workspace/app",
  596. workspaceKey: "/workspace/app",
  597. },
  598. },
  599. };
  600. const agentService = {
  601. createSession: vi.fn(async () => snapshot),
  602. } as unknown as IZCodeAgentService;
  603. const taskIndexSyncer = {
  604. ensureSessionSubscription: vi.fn(),
  605. syncSnapshotAndBroadcast: vi.fn(async () => ({
  606. taskId: "session-1",
  607. traceId: "trace-session-1",
  608. title: "New session",
  609. workspacePath: "/workspace/app",
  610. createdAt: 1,
  611. updatedAt: 1,
  612. mode: "build",
  613. status: "running",
  614. })),
  615. } as unknown as ZCodeTaskIndexSyncer;
  616. const service = createZCodeSessionService({ agentService, taskIndexSyncer });
  617. await service.createSession({ workspacePath: "/workspace/app" });
  618. expect(taskIndexSyncer.ensureSessionSubscription).toHaveBeenCalledWith({
  619. workspacePath: "/workspace/app",
  620. workspaceIdentity: undefined,
  621. sessionId: "session-1",
  622. });
  623. expect(taskIndexSyncer.syncSnapshotAndBroadcast).toHaveBeenCalledWith(snapshot, {
  624. moveGroupedTaskToTop: true,
  625. broadcastReason: "task_meta_changed",
  626. });
  627. });
  628. it("syncs resume model override into the task index", async () => {
  629. const snapshot = {
  630. protocol: { name: "ZCode Protocol", version: 1 },
  631. session: {
  632. sessionId: "session-1",
  633. mode: "build",
  634. status: "idle",
  635. createdAt: 1,
  636. updatedAt: 2,
  637. workspace: {
  638. workspacePath: "/workspace/app",
  639. workspaceKey: "/workspace/app",
  640. },
  641. },
  642. settings: {
  643. model: {
  644. current: { providerId: "current-provider", modelId: "current-model" },
  645. available: [],
  646. },
  647. thoughtLevel: { enabled: false, available: [] },
  648. mode: { current: "build" },
  649. },
  650. runtime: { eventSeq: 1, stateRevision: 1, pendingRequestIds: [] },
  651. projection: {},
  652. messages: [],
  653. } as unknown as ZCodeSessionStateSnapshot;
  654. const agentService = {
  655. resumeSession: vi.fn(async () => snapshot),
  656. } as unknown as IZCodeAgentService;
  657. const taskIndexSyncer = {
  658. ensureSessionSubscription: vi.fn(),
  659. syncSnapshotAndBroadcast: vi.fn(),
  660. } as unknown as ZCodeTaskIndexSyncer;
  661. const service = createZCodeSessionService({ agentService, taskIndexSyncer });
  662. await service.resumeSession({
  663. workspacePath: "/workspace/app",
  664. sessionId: "session-1",
  665. model: { providerId: "current-provider", modelId: "current-model" },
  666. });
  667. expect(taskIndexSyncer.syncSnapshotAndBroadcast).toHaveBeenCalledWith(snapshot, {
  668. modelOverride: "current-provider/current-model",
  669. broadcastReason: "task_status_changed",
  670. });
  671. });
  672. it("replays requested thought level before broadcasting resume snapshot", async () => {
  673. const makeSnapshot = (thoughtLevel: string) =>
  674. ({
  675. protocol: { name: "ZCode Protocol", version: 1 },
  676. session: {
  677. sessionId: "session-1",
  678. mode: "build",
  679. status: "idle",
  680. createdAt: 1,
  681. updatedAt: 2,
  682. workspace: {
  683. workspacePath: "/workspace/app",
  684. workspaceKey: "/workspace/app",
  685. },
  686. },
  687. settings: {
  688. model: {
  689. current: { providerId: "bigmodel-api", modelId: "GLM-5.2" },
  690. available: [],
  691. },
  692. thoughtLevel: { enabled: true, current: thoughtLevel, available: ["high", "max"] },
  693. mode: { current: "build" },
  694. },
  695. runtime: {
  696. activeTurnId: undefined,
  697. eventSeq: 1,
  698. stateRevision: 1,
  699. pendingRequestIds: [],
  700. },
  701. projection: { target: null, lastError: null, pendingPermissions: [] },
  702. messages: [],
  703. }) as unknown as ZCodeSessionStateSnapshot;
  704. const pollutedSnapshot = makeSnapshot("high");
  705. const correctedSnapshot = makeSnapshot("max");
  706. const agentService = {
  707. resumeSession: vi.fn(async () => pollutedSnapshot),
  708. setThoughtLevel: vi.fn(async () => correctedSnapshot),
  709. } as unknown as IZCodeAgentService;
  710. const taskIndexSyncer = {
  711. ensureSessionSubscription: vi.fn(),
  712. syncSnapshotAndBroadcast: vi.fn(),
  713. } as unknown as ZCodeTaskIndexSyncer;
  714. const service = createZCodeSessionService({ agentService, taskIndexSyncer });
  715. await expect(
  716. service.resumeSession({
  717. workspacePath: "/workspace/app",
  718. sessionId: "session-1",
  719. model: { providerId: "bigmodel-api", modelId: "GLM-5.2" },
  720. thoughtLevel: "max",
  721. }),
  722. ).resolves.toBe(correctedSnapshot);
  723. expect(agentService.setThoughtLevel).toHaveBeenCalledWith({
  724. workspacePath: "/workspace/app",
  725. workspaceIdentity: undefined,
  726. sessionId: "session-1",
  727. thoughtLevel: "max",
  728. });
  729. expect(taskIndexSyncer.syncSnapshotAndBroadcast).toHaveBeenCalledWith(correctedSnapshot, {
  730. modelOverride: "bigmodel-api/GLM-5.2",
  731. thoughtLevelOverride: "max",
  732. broadcastReason: "task_status_changed",
  733. });
  734. });
  735. it("skips resume thought replay when the restored model does not support the requested level", async () => {
  736. const snapshot = {
  737. protocol: { name: "ZCode Protocol", version: 1 },
  738. session: {
  739. sessionId: "session-1",
  740. mode: "build",
  741. status: "idle",
  742. createdAt: 1,
  743. updatedAt: 2,
  744. workspace: {
  745. workspacePath: "/workspace/app",
  746. workspaceKey: "/workspace/app",
  747. },
  748. },
  749. settings: {
  750. model: {
  751. current: {
  752. providerId: "account:bigmodel-individual-coding-plan",
  753. modelId: "GLM-5-Turbo",
  754. },
  755. available: [],
  756. },
  757. thoughtLevel: {
  758. enabled: true,
  759. current: "enabled",
  760. available: [
  761. { value: "enabled", label: "Enabled" },
  762. { value: "off", label: "Off" },
  763. ],
  764. },
  765. mode: { current: "build" },
  766. },
  767. runtime: {
  768. activeTurnId: undefined,
  769. eventSeq: 1,
  770. stateRevision: 1,
  771. pendingRequestIds: [],
  772. },
  773. projection: { target: null, lastError: null, pendingPermissions: [] },
  774. messages: [],
  775. } as unknown as ZCodeSessionStateSnapshot;
  776. const agentService = {
  777. resumeSession: vi.fn(async () => snapshot),
  778. setThoughtLevel: vi.fn(async () => {
  779. throw new Error("setThoughtLevel should not be called");
  780. }),
  781. } as unknown as IZCodeAgentService;
  782. const taskIndexSyncer = {
  783. ensureSessionSubscription: vi.fn(),
  784. syncSnapshotAndBroadcast: vi.fn(),
  785. } as unknown as ZCodeTaskIndexSyncer;
  786. const service = createZCodeSessionService({ agentService, taskIndexSyncer });
  787. await expect(
  788. service.resumeSession({
  789. workspacePath: "/workspace/app",
  790. sessionId: "session-1",
  791. model: { providerId: "account:bigmodel-individual-coding-plan", modelId: "GLM-5-Turbo" },
  792. thoughtLevel: "max",
  793. }),
  794. ).resolves.toBe(snapshot);
  795. expect(agentService.setThoughtLevel).not.toHaveBeenCalled();
  796. expect(taskIndexSyncer.syncSnapshotAndBroadcast).toHaveBeenCalledWith(snapshot, {
  797. modelOverride: "account:bigmodel-individual-coding-plan/GLM-5-Turbo",
  798. broadcastReason: "task_status_changed",
  799. });
  800. });
  801. it("updates only task model when resume snapshot broadcast is disabled", async () => {
  802. const snapshot = {
  803. protocol: { name: "ZCode Protocol", version: 1 },
  804. session: {
  805. sessionId: "session-1",
  806. mode: "build",
  807. status: "idle",
  808. createdAt: 1,
  809. updatedAt: 2,
  810. workspace: {
  811. workspacePath: "/workspace/app",
  812. workspaceKey: "/workspace/app",
  813. },
  814. },
  815. settings: {
  816. model: {
  817. current: { providerId: "current-provider", modelId: "current-model" },
  818. available: [],
  819. },
  820. thoughtLevel: { enabled: false, available: [] },
  821. mode: { current: "build" },
  822. },
  823. runtime: { eventSeq: 1, stateRevision: 1, pendingRequestIds: [] },
  824. projection: {},
  825. messages: [],
  826. } as unknown as ZCodeSessionStateSnapshot;
  827. const agentService = {
  828. resumeSession: vi.fn(async () => snapshot),
  829. } as unknown as IZCodeAgentService;
  830. const taskIndexSyncer = {
  831. ensureSessionSubscription: vi.fn(),
  832. syncSnapshotAndBroadcast: vi.fn(),
  833. syncTaskModel: vi.fn(),
  834. } as unknown as ZCodeTaskIndexSyncer;
  835. const service = createZCodeSessionService({ agentService, taskIndexSyncer });
  836. await service.resumeSession({
  837. workspacePath: "/workspace/app",
  838. sessionId: "session-1",
  839. model: { providerId: "current-provider", modelId: "current-model" },
  840. broadcastSnapshot: false,
  841. });
  842. expect(taskIndexSyncer.syncSnapshotAndBroadcast).not.toHaveBeenCalled();
  843. expect(taskIndexSyncer.syncTaskModel).toHaveBeenCalledWith(
  844. {
  845. workspacePath: "/workspace/app",
  846. workspaceIdentity: undefined,
  847. sessionId: "session-1",
  848. },
  849. "current-provider/current-model",
  850. );
  851. });
  852. it("syncs explicit setModel snapshots into the task index", async () => {
  853. const snapshot = {
  854. session: {
  855. sessionId: "session-1",
  856. workspace: {
  857. workspacePath: "/workspace/app",
  858. workspaceKey: "/workspace/app",
  859. },
  860. },
  861. } as unknown as ZCodeSessionStateSnapshot;
  862. const agentService = {
  863. setModel: vi.fn(async () => snapshot),
  864. } as unknown as IZCodeAgentService;
  865. const taskIndexSyncer = {
  866. ensureSessionSubscription: vi.fn(),
  867. syncSnapshotAndBroadcast: vi.fn(),
  868. } as unknown as ZCodeTaskIndexSyncer;
  869. const service = createZCodeSessionService({ agentService, taskIndexSyncer });
  870. await expect(
  871. service.setModel({
  872. workspacePath: "/workspace/app",
  873. sessionId: "session-1",
  874. model: { providerId: "current-provider", modelId: "current-model" },
  875. }),
  876. ).resolves.toBe(snapshot);
  877. expect(taskIndexSyncer.ensureSessionSubscription).toHaveBeenCalledWith({
  878. workspacePath: "/workspace/app",
  879. workspaceIdentity: undefined,
  880. sessionId: "session-1",
  881. });
  882. expect(taskIndexSyncer.syncSnapshotAndBroadcast).toHaveBeenCalledWith(snapshot, {
  883. modelOverride: "current-provider/current-model",
  884. broadcastReason: "task_model_changed",
  885. });
  886. });
  887. });