zcodeSessionService.test.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951
  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. {
  212. workspacePath: "/workspace/app",
  213. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  214. sessionId: "draft-1",
  215. },
  216. undefined,
  217. );
  218. expect(taskIndexSyncer.syncSnapshotAndBroadcast).toHaveBeenCalledWith(snapshot, {
  219. modelOverride: "current-provider/current-model",
  220. broadcastReason: "task_model_changed",
  221. });
  222. });
  223. it("uses a conditional stale-draft close after a remote session is promoted", async () => {
  224. const snapshot = {
  225. session: {
  226. sessionId: "remote-task-1",
  227. workspace: {
  228. workspacePath: "/workspace/app",
  229. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  230. },
  231. },
  232. } as unknown as ZCodeSessionStateSnapshot;
  233. let persistence: "deferred" | "immediate" = "deferred";
  234. const closeSession: IZCodeAgentService["closeSession"] = vi.fn(async (params) => {
  235. if (params.expectedPersistence && params.expectedPersistence !== persistence) {
  236. return false;
  237. }
  238. return true;
  239. });
  240. const agentService = {
  241. closeSession,
  242. createSession: vi.fn(async () => snapshot),
  243. } as unknown as IZCodeAgentService;
  244. const taskIndexSyncer = {
  245. ensureSessionSubscription: vi.fn(),
  246. syncSnapshotAndBroadcast: vi.fn(),
  247. } as unknown as ZCodeTaskIndexSyncer;
  248. const service = createZCodeSessionService({ agentService, taskIndexSyncer });
  249. const target = {
  250. workspacePath: "/workspace/app",
  251. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  252. sessionId: "remote-task-1",
  253. };
  254. await service.createSession({
  255. workspacePath: target.workspacePath,
  256. workspaceIdentity: target.workspaceIdentity,
  257. persistence: "deferred",
  258. });
  259. // 远程端首发会把同一个 session 原地提升;设置页异步闭包仍可能持有旧 draftSessionId。
  260. persistence = "immediate";
  261. await service.promoteDeferredDraftSession(target);
  262. await expect(service.closeDeferredDraftSession(target)).resolves.toBe(false);
  263. expect(closeSession).toHaveBeenCalledWith({
  264. ...target,
  265. expectedPersistence: "deferred",
  266. });
  267. expect(taskIndexSyncer.ensureSessionSubscription).toHaveBeenCalledWith(target, undefined);
  268. });
  269. it("only closes a draft when the Agent confirms it is still deferred", async () => {
  270. const closeSession = vi.fn(async () => false);
  271. const agentService = { closeSession } as unknown as IZCodeAgentService;
  272. const service = createZCodeSessionService({ agentService });
  273. await expect(
  274. service.closeDeferredDraftSession({
  275. workspacePath: "/workspace/app",
  276. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  277. sessionId: "draft-promoted-elsewhere",
  278. }),
  279. ).resolves.toBe(false);
  280. expect(closeSession).toHaveBeenCalledWith({
  281. workspacePath: "/workspace/app",
  282. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  283. sessionId: "draft-promoted-elsewhere",
  284. expectedPersistence: "deferred",
  285. });
  286. });
  287. it("does not fall back to unconditional close when an older Agent rejects conditional close", async () => {
  288. const closeSession = vi.fn(async () => {
  289. throw new Error("Invalid params: expectedPersistence");
  290. });
  291. const agentService = { closeSession } as unknown as IZCodeAgentService;
  292. const service = createZCodeSessionService({ agentService });
  293. await expect(
  294. service.closeDeferredDraftSession({
  295. workspacePath: "/workspace/app",
  296. sessionId: "draft-on-old-agent",
  297. }),
  298. ).resolves.toBe(false);
  299. expect(closeSession).toHaveBeenCalledTimes(1);
  300. });
  301. it("delegates workspace initialization and read paths to the agent service", async () => {
  302. const agentService = {
  303. initialize: vi.fn(async () => ({
  304. available: true,
  305. workspaceKey: "remote:ssh:dev:/workspace/app",
  306. protocolName: "ZCode Protocol",
  307. protocolVersion: 1,
  308. transportKind: "stdio",
  309. })),
  310. readSessionMessages: vi.fn(async () => []),
  311. readSessionEvents: vi.fn(async () => []),
  312. } as unknown as IZCodeAgentService;
  313. const service = createZCodeSessionService({ agentService });
  314. await expect(
  315. service.initializeWorkspace({
  316. workspacePath: "/workspace/app",
  317. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  318. }),
  319. ).resolves.toMatchObject({
  320. available: true,
  321. workspaceKey: "remote:ssh:dev:/workspace/app",
  322. });
  323. await service.readSessionMessages({
  324. workspacePath: "/workspace/app",
  325. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  326. sessionId: "session-1",
  327. limit: 20,
  328. });
  329. await service.readSessionEvents({
  330. workspacePath: "/workspace/app",
  331. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  332. sessionId: "session-1",
  333. afterSeq: 4,
  334. });
  335. expect(agentService.initialize).toHaveBeenCalledWith({
  336. workspacePath: "/workspace/app",
  337. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  338. });
  339. expect(agentService.readSessionMessages).toHaveBeenCalledWith({
  340. workspacePath: "/workspace/app",
  341. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  342. sessionId: "session-1",
  343. limit: 20,
  344. });
  345. expect(agentService.readSessionEvents).toHaveBeenCalledWith({
  346. workspacePath: "/workspace/app",
  347. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  348. sessionId: "session-1",
  349. afterSeq: 4,
  350. });
  351. });
  352. it("repairs empty imported Claude protocol sessions from legacy snapshots", async () => {
  353. useTempDataBaseDir();
  354. const workspacePath = "/workspace/imported";
  355. const sessionId = "claude-import-empty";
  356. const legacyPath = getLegacyTaskSessionSnapshotPath(workspacePath, sessionId);
  357. mkdirSync(dirname(legacyPath), { recursive: true });
  358. writeFileSync(
  359. legacyPath,
  360. JSON.stringify({
  361. meta: {
  362. taskId: sessionId,
  363. traceId: "trace_imported",
  364. title: "Imported Claude",
  365. workspacePath,
  366. createdAt: 10,
  367. updatedAt: 20,
  368. migrationSource: "claudeCode",
  369. },
  370. messages: [
  371. { role: "user", content: "旧问题", timestamp: 10 },
  372. { role: "assistant", content: "旧回答", timestamp: 20 },
  373. ],
  374. }),
  375. "utf-8",
  376. );
  377. const emptySnapshot = {
  378. session: {
  379. sessionId,
  380. mode: "build",
  381. status: "idle",
  382. workspace: {
  383. workspacePath,
  384. workspaceKey: workspacePath,
  385. },
  386. },
  387. settings: {
  388. model: {
  389. current: { providerId: "glm", modelId: "glm-4.6" },
  390. available: [],
  391. },
  392. thoughtLevel: { enabled: true, current: "think", available: [] },
  393. mode: { current: "build" },
  394. },
  395. runtime: {
  396. eventSeq: 1,
  397. stateRevision: 2,
  398. pendingRequestIds: [],
  399. },
  400. messages: [],
  401. } as unknown as ZCodeSessionStateSnapshot;
  402. const repairedSnapshot = {
  403. ...emptySnapshot,
  404. messages: [
  405. { info: { role: "user" }, parts: [{ type: "text", text: "旧问题" }] },
  406. { info: { role: "assistant" }, parts: [{ type: "text", text: "旧回答" }] },
  407. ],
  408. } as unknown as ZCodeSessionStateSnapshot;
  409. const agentService = {
  410. resumeSession: vi.fn(async () => emptySnapshot),
  411. createSession: vi.fn(async () => repairedSnapshot),
  412. } as unknown as IZCodeAgentService;
  413. const taskIndexSyncer = {
  414. ensureSessionSubscription: vi.fn(),
  415. syncSnapshotAndBroadcast: vi.fn(),
  416. } as unknown as ZCodeTaskIndexSyncer;
  417. const service = createZCodeSessionService({ agentService, taskIndexSyncer });
  418. await expect(service.resumeSession({ workspacePath, sessionId })).resolves.toBe(
  419. repairedSnapshot,
  420. );
  421. expect(agentService.createSession).toHaveBeenCalledWith({
  422. workspacePath,
  423. workspaceIdentity: undefined,
  424. sessionId,
  425. mode: "build",
  426. model: { providerId: "glm", modelId: "glm-4.6" },
  427. thoughtLevel: "think",
  428. persistence: "immediate",
  429. importedHistory: {
  430. source: "claudeCode",
  431. title: "Imported Claude",
  432. createdAt: 10,
  433. updatedAt: 20,
  434. messages: [
  435. { role: "user", content: "旧问题", timestamp: 10 },
  436. { role: "assistant", content: "旧回答", timestamp: 20 },
  437. ],
  438. },
  439. });
  440. expect(taskIndexSyncer.syncSnapshotAndBroadcast).toHaveBeenCalledWith(
  441. repairedSnapshot,
  442. // Bugfix: resume 收敛是状态同步,广播 reason 改为 task_status_changed,避免全局 membership 重拉。
  443. { broadcastReason: "task_status_changed" },
  444. );
  445. });
  446. it("repairs imported Claude protocol sessions with legacy fixed message ids", async () => {
  447. useTempDataBaseDir();
  448. const workspacePath = "/workspace/imported";
  449. const sessionId = "claude-import-corrupted-order";
  450. const legacyPath = getLegacyTaskSessionSnapshotPath(workspacePath, sessionId);
  451. mkdirSync(dirname(legacyPath), { recursive: true });
  452. writeFileSync(
  453. legacyPath,
  454. JSON.stringify({
  455. meta: {
  456. taskId: sessionId,
  457. traceId: "trace_imported_corrupted",
  458. title: "Imported Claude Corrupted",
  459. workspacePath,
  460. createdAt: 10,
  461. updatedAt: 20,
  462. migrationSource: "claudeCode",
  463. },
  464. messages: [
  465. { role: "user", content: "正确问题", timestamp: 10 },
  466. { role: "assistant", content: "正确回答", timestamp: 20 },
  467. ],
  468. }),
  469. "utf-8",
  470. );
  471. const corruptedSnapshot = {
  472. session: {
  473. sessionId,
  474. mode: "build",
  475. status: "idle",
  476. workspace: {
  477. workspacePath,
  478. workspaceKey: workspacePath,
  479. },
  480. },
  481. settings: {
  482. model: {
  483. current: { providerId: "glm", modelId: "glm-4.6" },
  484. available: [],
  485. },
  486. thoughtLevel: { enabled: true, current: "think", available: [] },
  487. mode: { current: "build" },
  488. },
  489. runtime: {
  490. eventSeq: 1,
  491. stateRevision: 2,
  492. pendingRequestIds: [],
  493. },
  494. messages: [
  495. { info: { messageId: "msg_import_1", role: "assistant" }, parts: [] },
  496. { info: { messageId: "msg_import_0", role: "user" }, parts: [] },
  497. ],
  498. } as unknown as ZCodeSessionStateSnapshot;
  499. const repairedSnapshot = {
  500. ...corruptedSnapshot,
  501. messages: [
  502. {
  503. info: { messageId: "msg_repaired_0", role: "user" },
  504. parts: [{ type: "text", text: "正确问题" }],
  505. },
  506. {
  507. info: { messageId: "msg_repaired_1", role: "assistant" },
  508. parts: [{ type: "text", text: "正确回答" }],
  509. },
  510. ],
  511. } as unknown as ZCodeSessionStateSnapshot;
  512. const agentService = {
  513. resumeSession: vi.fn(async () => corruptedSnapshot),
  514. createSession: vi.fn(async () => repairedSnapshot),
  515. } as unknown as IZCodeAgentService;
  516. const service = createZCodeSessionService({ agentService });
  517. await expect(service.resumeSession({ workspacePath, sessionId })).resolves.toBe(
  518. repairedSnapshot,
  519. );
  520. expect(agentService.createSession).toHaveBeenCalledWith(
  521. expect.objectContaining({
  522. workspacePath,
  523. sessionId,
  524. importedHistory: expect.objectContaining({
  525. messages: [
  526. { role: "user", content: "正确问题", timestamp: 10 },
  527. { role: "assistant", content: "正确回答", timestamp: 20 },
  528. ],
  529. }),
  530. }),
  531. );
  532. });
  533. it("does not repair ordinary user-only sessions from accidental Claude legacy files", async () => {
  534. useTempDataBaseDir();
  535. const workspacePath = "/workspace/ordinary";
  536. const sessionId = "ordinary-user-only-session";
  537. const legacyPath = getLegacyTaskSessionSnapshotPath(workspacePath, sessionId);
  538. mkdirSync(dirname(legacyPath), { recursive: true });
  539. writeFileSync(
  540. legacyPath,
  541. JSON.stringify({
  542. meta: {
  543. taskId: sessionId,
  544. traceId: "trace_accidental_legacy",
  545. title: "Accidental Claude backup",
  546. workspacePath,
  547. createdAt: 10,
  548. updatedAt: 20,
  549. migrationSource: "claudeCode",
  550. },
  551. messages: [
  552. { role: "user", content: "不应该回填的问题", timestamp: 10 },
  553. { role: "assistant", content: "不应该回填的回答", timestamp: 20 },
  554. ],
  555. }),
  556. "utf-8",
  557. );
  558. const ordinarySnapshot = {
  559. session: {
  560. sessionId,
  561. mode: "build",
  562. status: "idle",
  563. workspace: {
  564. workspacePath,
  565. workspaceKey: workspacePath,
  566. },
  567. },
  568. settings: {
  569. model: {
  570. current: { providerId: "glm", modelId: "glm-4.6" },
  571. available: [],
  572. },
  573. thoughtLevel: { enabled: true, current: "think", available: [] },
  574. mode: { current: "build" },
  575. },
  576. runtime: {
  577. eventSeq: 1,
  578. stateRevision: 2,
  579. pendingRequestIds: [],
  580. },
  581. messages: [{ info: { messageId: "msg_ordinary_0", role: "user" }, parts: [] }],
  582. } as unknown as ZCodeSessionStateSnapshot;
  583. const agentService = {
  584. resumeSession: vi.fn(async () => ordinarySnapshot),
  585. createSession: vi.fn(),
  586. } as unknown as IZCodeAgentService;
  587. const service = createZCodeSessionService({ agentService });
  588. await expect(service.resumeSession({ workspacePath, sessionId })).resolves.toBe(
  589. ordinarySnapshot,
  590. );
  591. expect(agentService.createSession).not.toHaveBeenCalled();
  592. });
  593. it("asks the task index syncer to place desktop-created sessions at the grouped top", async () => {
  594. const snapshot = {
  595. session: {
  596. sessionId: "session-1",
  597. workspace: {
  598. workspacePath: "/workspace/app",
  599. workspaceKey: "/workspace/app",
  600. },
  601. },
  602. };
  603. const agentService = {
  604. createSession: vi.fn(async () => snapshot),
  605. } as unknown as IZCodeAgentService;
  606. const taskIndexSyncer = {
  607. ensureSessionSubscription: vi.fn(),
  608. syncSnapshotAndBroadcast: vi.fn(async () => ({
  609. taskId: "session-1",
  610. traceId: "trace-session-1",
  611. title: "New session",
  612. workspacePath: "/workspace/app",
  613. createdAt: 1,
  614. updatedAt: 1,
  615. mode: "build",
  616. status: "running",
  617. })),
  618. } as unknown as ZCodeTaskIndexSyncer;
  619. const service = createZCodeSessionService({ agentService, taskIndexSyncer });
  620. await service.createSession({ workspacePath: "/workspace/app" });
  621. expect(taskIndexSyncer.ensureSessionSubscription).toHaveBeenCalledWith(
  622. {
  623. workspacePath: "/workspace/app",
  624. workspaceIdentity: undefined,
  625. sessionId: "session-1",
  626. },
  627. undefined,
  628. );
  629. expect(taskIndexSyncer.syncSnapshotAndBroadcast).toHaveBeenCalledWith(snapshot, {
  630. moveGroupedTaskToTop: true,
  631. broadcastReason: "task_meta_changed",
  632. });
  633. });
  634. it("syncs resume model override into the task index", async () => {
  635. const snapshot = {
  636. protocol: { name: "ZCode Protocol", version: 1 },
  637. session: {
  638. sessionId: "session-1",
  639. mode: "build",
  640. status: "idle",
  641. createdAt: 1,
  642. updatedAt: 2,
  643. workspace: {
  644. workspacePath: "/workspace/app",
  645. workspaceKey: "/workspace/app",
  646. },
  647. },
  648. settings: {
  649. model: {
  650. current: { providerId: "current-provider", modelId: "current-model" },
  651. available: [],
  652. },
  653. thoughtLevel: { enabled: false, available: [] },
  654. mode: { current: "build" },
  655. },
  656. runtime: { eventSeq: 1, stateRevision: 1, pendingRequestIds: [] },
  657. projection: {},
  658. messages: [],
  659. } as unknown as ZCodeSessionStateSnapshot;
  660. const agentService = {
  661. resumeSession: vi.fn(async () => snapshot),
  662. } as unknown as IZCodeAgentService;
  663. const taskIndexSyncer = {
  664. ensureSessionSubscription: vi.fn(),
  665. syncSnapshotAndBroadcast: vi.fn(),
  666. } as unknown as ZCodeTaskIndexSyncer;
  667. const service = createZCodeSessionService({ agentService, taskIndexSyncer });
  668. await service.resumeSession({
  669. workspacePath: "/workspace/app",
  670. sessionId: "session-1",
  671. model: { providerId: "current-provider", modelId: "current-model" },
  672. });
  673. expect(taskIndexSyncer.syncSnapshotAndBroadcast).toHaveBeenCalledWith(snapshot, {
  674. modelOverride: "current-provider/current-model",
  675. broadcastReason: "task_status_changed",
  676. });
  677. });
  678. it("replays requested thought level before broadcasting resume snapshot", async () => {
  679. const makeSnapshot = (thoughtLevel: string) =>
  680. ({
  681. protocol: { name: "ZCode Protocol", version: 1 },
  682. session: {
  683. sessionId: "session-1",
  684. mode: "build",
  685. status: "idle",
  686. createdAt: 1,
  687. updatedAt: 2,
  688. workspace: {
  689. workspacePath: "/workspace/app",
  690. workspaceKey: "/workspace/app",
  691. },
  692. },
  693. settings: {
  694. model: {
  695. current: { providerId: "bigmodel-api", modelId: "GLM-5.2" },
  696. available: [],
  697. },
  698. thoughtLevel: { enabled: true, current: thoughtLevel, available: ["high", "max"] },
  699. mode: { current: "build" },
  700. },
  701. runtime: {
  702. activeTurnId: undefined,
  703. eventSeq: 1,
  704. stateRevision: 1,
  705. pendingRequestIds: [],
  706. },
  707. projection: { target: null, lastError: null, pendingPermissions: [] },
  708. messages: [],
  709. }) as unknown as ZCodeSessionStateSnapshot;
  710. const pollutedSnapshot = makeSnapshot("high");
  711. const correctedSnapshot = makeSnapshot("max");
  712. const agentService = {
  713. resumeSession: vi.fn(async () => pollutedSnapshot),
  714. setThoughtLevel: vi.fn(async () => correctedSnapshot),
  715. } as unknown as IZCodeAgentService;
  716. const taskIndexSyncer = {
  717. ensureSessionSubscription: vi.fn(),
  718. syncSnapshotAndBroadcast: vi.fn(),
  719. } as unknown as ZCodeTaskIndexSyncer;
  720. const service = createZCodeSessionService({ agentService, taskIndexSyncer });
  721. await expect(
  722. service.resumeSession({
  723. workspacePath: "/workspace/app",
  724. sessionId: "session-1",
  725. model: { providerId: "bigmodel-api", modelId: "GLM-5.2" },
  726. thoughtLevel: "max",
  727. }),
  728. ).resolves.toBe(correctedSnapshot);
  729. expect(agentService.setThoughtLevel).toHaveBeenCalledWith({
  730. workspacePath: "/workspace/app",
  731. workspaceIdentity: undefined,
  732. sessionId: "session-1",
  733. thoughtLevel: "max",
  734. });
  735. expect(taskIndexSyncer.syncSnapshotAndBroadcast).toHaveBeenCalledWith(correctedSnapshot, {
  736. modelOverride: "bigmodel-api/GLM-5.2",
  737. thoughtLevelOverride: "max",
  738. broadcastReason: "task_status_changed",
  739. });
  740. });
  741. it("skips resume thought replay when the restored model does not support the requested level", async () => {
  742. const snapshot = {
  743. protocol: { name: "ZCode Protocol", version: 1 },
  744. session: {
  745. sessionId: "session-1",
  746. mode: "build",
  747. status: "idle",
  748. createdAt: 1,
  749. updatedAt: 2,
  750. workspace: {
  751. workspacePath: "/workspace/app",
  752. workspaceKey: "/workspace/app",
  753. },
  754. },
  755. settings: {
  756. model: {
  757. current: {
  758. providerId: "account:bigmodel-individual-coding-plan",
  759. modelId: "GLM-5-Turbo",
  760. },
  761. available: [],
  762. },
  763. thoughtLevel: {
  764. enabled: true,
  765. current: "enabled",
  766. available: [
  767. { value: "enabled", label: "Enabled" },
  768. { value: "off", label: "Off" },
  769. ],
  770. },
  771. mode: { current: "build" },
  772. },
  773. runtime: {
  774. activeTurnId: undefined,
  775. eventSeq: 1,
  776. stateRevision: 1,
  777. pendingRequestIds: [],
  778. },
  779. projection: { target: null, lastError: null, pendingPermissions: [] },
  780. messages: [],
  781. } as unknown as ZCodeSessionStateSnapshot;
  782. const agentService = {
  783. resumeSession: vi.fn(async () => snapshot),
  784. setThoughtLevel: vi.fn(async () => {
  785. throw new Error("setThoughtLevel should not be called");
  786. }),
  787. } as unknown as IZCodeAgentService;
  788. const taskIndexSyncer = {
  789. ensureSessionSubscription: vi.fn(),
  790. syncSnapshotAndBroadcast: vi.fn(),
  791. } as unknown as ZCodeTaskIndexSyncer;
  792. const service = createZCodeSessionService({ agentService, taskIndexSyncer });
  793. await expect(
  794. service.resumeSession({
  795. workspacePath: "/workspace/app",
  796. sessionId: "session-1",
  797. model: { providerId: "account:bigmodel-individual-coding-plan", modelId: "GLM-5-Turbo" },
  798. thoughtLevel: "max",
  799. }),
  800. ).resolves.toBe(snapshot);
  801. expect(agentService.setThoughtLevel).not.toHaveBeenCalled();
  802. expect(taskIndexSyncer.syncSnapshotAndBroadcast).toHaveBeenCalledWith(snapshot, {
  803. modelOverride: "account:bigmodel-individual-coding-plan/GLM-5-Turbo",
  804. broadcastReason: "task_status_changed",
  805. });
  806. });
  807. it("updates only task model when resume snapshot broadcast is disabled", async () => {
  808. const snapshot = {
  809. protocol: { name: "ZCode Protocol", version: 1 },
  810. session: {
  811. sessionId: "session-1",
  812. mode: "build",
  813. status: "idle",
  814. createdAt: 1,
  815. updatedAt: 2,
  816. workspace: {
  817. workspacePath: "/workspace/app",
  818. workspaceKey: "/workspace/app",
  819. },
  820. },
  821. settings: {
  822. model: {
  823. current: { providerId: "current-provider", modelId: "current-model" },
  824. available: [],
  825. },
  826. thoughtLevel: { enabled: false, available: [] },
  827. mode: { current: "build" },
  828. },
  829. runtime: { eventSeq: 1, stateRevision: 1, pendingRequestIds: [] },
  830. projection: {},
  831. messages: [],
  832. } as unknown as ZCodeSessionStateSnapshot;
  833. const agentService = {
  834. resumeSession: vi.fn(async () => snapshot),
  835. } as unknown as IZCodeAgentService;
  836. const taskIndexSyncer = {
  837. ensureSessionSubscription: vi.fn(),
  838. syncSnapshotAndBroadcast: vi.fn(),
  839. syncTaskModel: vi.fn(),
  840. } as unknown as ZCodeTaskIndexSyncer;
  841. const service = createZCodeSessionService({ agentService, taskIndexSyncer });
  842. await service.resumeSession({
  843. workspacePath: "/workspace/app",
  844. sessionId: "session-1",
  845. model: { providerId: "current-provider", modelId: "current-model" },
  846. broadcastSnapshot: false,
  847. });
  848. expect(taskIndexSyncer.syncSnapshotAndBroadcast).not.toHaveBeenCalled();
  849. expect(taskIndexSyncer.syncTaskModel).toHaveBeenCalledWith(
  850. {
  851. workspacePath: "/workspace/app",
  852. workspaceIdentity: undefined,
  853. sessionId: "session-1",
  854. },
  855. "current-provider/current-model",
  856. );
  857. });
  858. it("syncs explicit setModel snapshots into the task index", async () => {
  859. const snapshot = {
  860. session: {
  861. sessionId: "session-1",
  862. workspace: {
  863. workspacePath: "/workspace/app",
  864. workspaceKey: "/workspace/app",
  865. },
  866. },
  867. } as unknown as ZCodeSessionStateSnapshot;
  868. const agentService = {
  869. setModel: vi.fn(async () => snapshot),
  870. } as unknown as IZCodeAgentService;
  871. const taskIndexSyncer = {
  872. ensureSessionSubscription: vi.fn(),
  873. syncSnapshotAndBroadcast: vi.fn(),
  874. } as unknown as ZCodeTaskIndexSyncer;
  875. const service = createZCodeSessionService({ agentService, taskIndexSyncer });
  876. await expect(
  877. service.setModel({
  878. workspacePath: "/workspace/app",
  879. sessionId: "session-1",
  880. model: { providerId: "current-provider", modelId: "current-model" },
  881. }),
  882. ).resolves.toBe(snapshot);
  883. expect(taskIndexSyncer.ensureSessionSubscription).toHaveBeenCalledWith(
  884. {
  885. workspacePath: "/workspace/app",
  886. workspaceIdentity: undefined,
  887. sessionId: "session-1",
  888. },
  889. undefined,
  890. );
  891. expect(taskIndexSyncer.syncSnapshotAndBroadcast).toHaveBeenCalledWith(snapshot, {
  892. modelOverride: "current-provider/current-model",
  893. broadcastReason: "task_model_changed",
  894. });
  895. });
  896. });