v4-cold-resume.test.ts 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845
  1. // M5 冷恢复(打开历史会话)验收网:CLI 重启后内存注册表为空,v4 订阅历史会话
  2. // 必须经 host.resumePersistedSession 把 record 拉起来,而不是抛
  3. // "Session is not active"(真 bug:桌面重启后点侧栏历史会话永远"连接中")。
  4. //
  5. // 两层覆盖:
  6. // - gateway 单元(stub host):单飞幂等 / 完整事件日志 hydration 路径 /
  7. // notFound vs resumeFailed 错误分型 / 宿主未实现钩子的退化行为。
  8. // - 集成(真 sqlite sessionStore + ZCodeProtocolAgentServer + binder):
  9. // 写 transcript → 关库重开(模拟 CLI 重启,context.sessions 为空)→
  10. // v4 subscribe → snapshot 含历史行(transcript 合成路径)→ sendText 再发一轮成功;
  11. // restoreWarning 语义保真(workspace 无可用模型时 sendText 被拒);
  12. // store 无此会话 → fault.subscribe.sessionNotFound。
  13. import { mkdtemp, rm } from "node:fs/promises";
  14. import { tmpdir } from "node:os";
  15. import { join } from "node:path";
  16. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  17. import { createSqliteSessionStore } from "@zcode/adapters/storage";
  18. import {
  19. zcodeProtocolMethods,
  20. zcodeSessionStateSnapshotSchema,
  21. type ZCodeProtocolMessage,
  22. } from "@zcode/shared";
  23. import {
  24. V4_METHODS,
  25. V4_NOTIFICATIONS,
  26. commandAckSchema,
  27. conversationTopic,
  28. conversationTopicFrameSchema,
  29. routedTopicWireFrameSchema,
  30. sessionsIndexTopic,
  31. sessionsIndexTopicFrameSchema,
  32. v4ConversationSubscribeResultSchema,
  33. v4ConversationRowsRangeResultSchema,
  34. v4SessionsIndexSubscribeResultSchema,
  35. type ConversationTopicFrame,
  36. } from "@zcode/shared/zcode-protocol-v4";
  37. import type {
  38. EventId,
  39. MessageId,
  40. MessagePart,
  41. MessageWithParts,
  42. ModelId,
  43. ModelProviderId,
  44. ProjectId,
  45. SessionEvent,
  46. SessionId,
  47. TraceId,
  48. WorkspaceId,
  49. } from "@zcode/contracts";
  50. import {
  51. CompactTrigger,
  52. SESSION_ENTRY_MODEL_SELECTION,
  53. SessionEventType,
  54. type CompactBoundaryPayload,
  55. } from "@zcode/contracts";
  56. import {
  57. ModelConfig,
  58. ModelOptionSpecsConfig,
  59. ModelPropertiesConfig,
  60. ProviderRegistry,
  61. type Provider,
  62. } from "@zcode/provider";
  63. import {
  64. ConversationV4Gateway,
  65. V4SubscribeSessionUnavailableError,
  66. type ColdSessionResumeOutcome,
  67. } from "../src/zcode-protocol-v4/index.js";
  68. import { resolveSessionContextUsage } from "../src/zcode-protocol/session-mapper.js";
  69. import { getRegistryBackedModel } from "../src/app/provider-registry-selection.js";
  70. import { ZCodeProtocolAgentServer } from "../src/zcode-protocol/server.js";
  71. import type { SessionUsageSeed } from "../src/zcode-protocol-v4/product-projection.js";
  72. import type { ZCodeApp, ZCodeAppOptions } from "../src/app/types.js";
  73. import { createApiKeyProviderConfig } from "./provider-config-fixtures.js";
  74. import { createRegistryBackedTestApp } from "./helpers/registry-backed-test-app.js";
  75. // ── gateway 单元层(stub host,模式对齐 v4-gateway.test.ts)──────────────────
  76. interface ColdHostStub {
  77. sessions: Set<string>;
  78. frames: ConversationTopicFrame[];
  79. errors: Array<{ scope: string; error: unknown }>;
  80. resumeCalls: string[];
  81. resumeThoughtLevels: Array<string | undefined>;
  82. resumeImpl: (sessionId: string) => Promise<ColdSessionResumeOutcome>;
  83. persistedEvents: Map<string, SessionEvent[]>;
  84. usageSeeds: Map<string, SessionUsageSeed>;
  85. synthesizedSessions: Set<string>;
  86. }
  87. function makeColdHost(): ColdHostStub {
  88. const host: ColdHostStub = {
  89. sessions: new Set(),
  90. frames: [],
  91. errors: [],
  92. resumeCalls: [],
  93. resumeThoughtLevels: [],
  94. // 默认打桩:恢复成功 = 会话进入内存注册表(对应 binder 的 resumeSession 建 record)。
  95. resumeImpl: async (sessionId) => {
  96. host.sessions.add(sessionId);
  97. return { status: "resumed" };
  98. },
  99. persistedEvents: new Map(),
  100. usageSeeds: new Map(),
  101. synthesizedSessions: new Set(),
  102. };
  103. return host;
  104. }
  105. function coldResumeHook(host: ColdHostStub) {
  106. return async (sessionId: string, resumeThoughtLevel?: string) => {
  107. host.resumeCalls.push(sessionId);
  108. host.resumeThoughtLevels.push(resumeThoughtLevel);
  109. return await host.resumeImpl(sessionId);
  110. };
  111. }
  112. function makeColdGateway(
  113. host: ColdHostStub,
  114. options: { withResumeHook?: boolean; now?: () => number } = {},
  115. ): ConversationV4Gateway {
  116. const withResumeHook = options.withResumeHook ?? true;
  117. return new ConversationV4Gateway(
  118. {
  119. sessionExists: (sessionId) => host.sessions.has(sessionId),
  120. emitWireFrame: (wire) => {
  121. if (wire.kind !== "complete" || !wire.topic.startsWith("conversation/")) {
  122. throw new Error("cold-resume test adapter only accepts complete conversation wires");
  123. }
  124. host.frames.push(wire.frame as ConversationTopicFrame);
  125. },
  126. executeCommand: async () => undefined,
  127. ...(withResumeHook
  128. ? {
  129. resumePersistedSession: coldResumeHook(host),
  130. }
  131. : {}),
  132. loadPersistedEvents: async (sessionId) => ({
  133. events: host.persistedEvents.get(sessionId) ?? [],
  134. synthesized: host.synthesizedSessions.has(sessionId),
  135. }),
  136. getSessionUsageSeed: (sessionId) => host.usageSeeds.get(sessionId) ?? null,
  137. onError: (scope, error) => host.errors.push({ scope, error }),
  138. },
  139. {
  140. now: options.now ?? (() => 1_700_000_999_000),
  141. createLogEpoch: () => "epoch-cold",
  142. },
  143. );
  144. }
  145. function makeEvent(
  146. sessionId: string,
  147. seq: number,
  148. type: SessionEvent["type"],
  149. payload: unknown,
  150. ): SessionEvent {
  151. return {
  152. id: `event-${seq}` as EventId,
  153. sessionId: sessionId as SessionId,
  154. turnId: undefined,
  155. type,
  156. timestamp: new Date(1_700_000_000_000 + seq * 1000),
  157. traceId: "trace-cold" as TraceId,
  158. sequenceNumber: seq,
  159. payload,
  160. } as SessionEvent;
  161. }
  162. function subscribeParams(sessionId: string) {
  163. return {
  164. topic: conversationTopic(sessionId),
  165. connectionId: "conn-cold",
  166. clientMode: "desktop-continuous",
  167. };
  168. }
  169. function deferred() {
  170. let resolve!: () => void;
  171. const promise = new Promise<void>((complete) => {
  172. resolve = complete;
  173. });
  174. return { promise, resolve };
  175. }
  176. function nextMacrotask(): Promise<void> {
  177. return new Promise((resolve) => setImmediate(resolve));
  178. }
  179. describe("v4 冷恢复(gateway 单元)", () => {
  180. it("冷订阅未加载会话:单一 READY 完成 activation 与 hydration", async () => {
  181. const host = makeColdHost();
  182. host.persistedEvents.set("sess-cold", [
  183. makeEvent("sess-cold", 1, SessionEventType.SessionCreated, {
  184. mode: "default",
  185. contextWindow: 200_000,
  186. }),
  187. ]);
  188. const gateway = makeColdGateway(host);
  189. const result = await gateway.subscribe(subscribeParams("sess-cold"));
  190. expect(host.resumeCalls).toEqual(["sess-cold"]);
  191. expect(host.sessions.has("sess-cold")).toBe(true);
  192. expect(result.ack.mode).toBe("snapshot");
  193. expect(result.ack.openTiming).toMatchObject({
  194. version: 1,
  195. sessionRuntimeState: "cold",
  196. cliSessionRestoreMs: expect.any(Number),
  197. initialFrameEncodeMs: expect.any(Number),
  198. snapshotRowCount: expect.any(Number),
  199. });
  200. expect(result.initialFrame?.payload.kind).toBe("snapshot");
  201. });
  202. it("Todo123: 同批容量种子不二次查询,恢复期间新模型和用量覆盖旧种子", async () => {
  203. const entered = deferred();
  204. const release = deferred();
  205. const getSessionUsageSeed = vi.fn(() => null);
  206. const sessionId = "sess-usage-race";
  207. const gateway = new ConversationV4Gateway({
  208. sessionExists: () => true,
  209. emitWireFrame: () => {},
  210. executeCommand: async () => undefined,
  211. getSessionUsageSeed,
  212. loadPersistedEvents: async () => {
  213. entered.resolve();
  214. await release.promise;
  215. return {
  216. synthesized: true,
  217. sourceEventSeq: 1,
  218. events: [
  219. makeEvent(sessionId, 1, SessionEventType.SessionCreated, { contextWindow: 1_000_000 }),
  220. ],
  221. usageSeed: {
  222. contextWindow: {
  223. usedTokens: 29908,
  224. maxTokens: 1_000_000,
  225. autoCompactThresholdTokens: null,
  226. },
  227. },
  228. };
  229. },
  230. });
  231. try {
  232. const pending = gateway.subscribe(subscribeParams(sessionId));
  233. await entered.promise;
  234. gateway.ingest(
  235. sessionId,
  236. makeEvent(sessionId, 2, SessionEventType.ModelSelected, {
  237. modelSelection: { providerId: "new", modelId: "new-model" },
  238. contextWindow: 500_000,
  239. }),
  240. );
  241. gateway.ingest(
  242. sessionId,
  243. makeEvent(sessionId, 3, SessionEventType.ModelComplete, {
  244. content: "",
  245. stopReason: "end_turn",
  246. querySource: "main_turn",
  247. usage: { inputTokens: 700, outputTokens: 30 },
  248. }),
  249. );
  250. release.resolve();
  251. const result = await pending;
  252. if (result.initialFrame?.payload.kind !== "snapshot") throw new Error("Expected snapshot");
  253. expect(result.initialFrame.payload.snapshot.config.model).toBe("new-model");
  254. expect(result.initialFrame.payload.snapshot.usage.contextWindow).toMatchObject({
  255. usedTokens: 730,
  256. maxTokens: 500_000,
  257. });
  258. expect(getSessionUsageSeed).not.toHaveBeenCalled();
  259. } finally {
  260. release.resolve();
  261. gateway.dispose();
  262. }
  263. });
  264. it("首帧编码耗时包含 wire projection 构建", async () => {
  265. const sessionId = "sess-live-initial-frame-timing";
  266. const host = makeColdHost();
  267. host.sessions.add(sessionId);
  268. let monotonicTime = 0;
  269. let simulateWireProjectionBuild = false;
  270. const gateway = makeColdGateway(host, {
  271. now: () => {
  272. // publisher 构建 initial frame 时会写 sentAt;借该公开时钟缝隙推进 monotonic clock,
  273. // 可确定性验证构建耗时是否包含在 initialFrameEncodeMs,而不依赖真实 CPU 速度。
  274. if (simulateWireProjectionBuild) monotonicTime += 25;
  275. return 1_700_000_999_000;
  276. },
  277. });
  278. gateway.ingest(
  279. sessionId,
  280. makeEvent(sessionId, 1, SessionEventType.SessionCreated, {
  281. mode: "default",
  282. contextWindow: 200_000,
  283. }),
  284. );
  285. const nowSpy = vi.spyOn(performance, "now").mockImplementation(() => monotonicTime);
  286. simulateWireProjectionBuild = true;
  287. try {
  288. const result = await gateway.subscribe(subscribeParams(sessionId));
  289. expect(result.ack.openTiming?.initialFrameEncodeMs).toBe(25);
  290. } finally {
  291. nowSpy.mockRestore();
  292. gateway.dispose();
  293. }
  294. });
  295. it("冷订阅只把 task-local thought hint 交给首次 resume", async () => {
  296. const host = makeColdHost();
  297. const gateway = makeColdGateway(host);
  298. await gateway.subscribe({
  299. ...subscribeParams("sess-cold-thought"),
  300. resumeThoughtLevel: "deep",
  301. });
  302. expect(host.resumeThoughtLevels).toEqual(["deep"]);
  303. });
  304. it("桌面与手机并发冷订阅同一会话:activation 单飞且首个终态一致", async () => {
  305. const host = makeColdHost();
  306. const messages: MessageWithParts[] = [];
  307. const loadedPersistedMessages: unknown[] = [];
  308. const usagePersistedMessages: unknown[] = [];
  309. const resumeEntered = deferred();
  310. const resumeGate = deferred();
  311. host.resumeImpl = async (sessionId) => {
  312. // production 在 app.resume() 前先注册 record;第二个订阅此时会观察到 live,
  313. // 但仍必须加入 activation flight,不能用空 materialization 抢跑 hydration。
  314. host.sessions.add(sessionId);
  315. resumeEntered.resolve();
  316. await resumeGate.promise;
  317. return { status: "resumed", persistedMessages: messages };
  318. };
  319. const gateway = new ConversationV4Gateway(
  320. {
  321. sessionExists: (sessionId) => host.sessions.has(sessionId),
  322. resumePersistedSession: coldResumeHook(host),
  323. loadPersistedEvents: async (_sessionId, persistedMessages) => {
  324. loadedPersistedMessages.push(persistedMessages);
  325. return { events: [], synthesized: true };
  326. },
  327. getSessionUsageSeed: (_sessionId, persistedMessages) => {
  328. usagePersistedMessages.push(persistedMessages);
  329. return null;
  330. },
  331. emitWireFrame: () => {},
  332. executeCommand: async () => undefined,
  333. },
  334. { now: () => 1_700_000_999_000, createLogEpoch: () => "epoch-cold" },
  335. );
  336. const first = gateway.subscribe(subscribeParams("sess-cold"));
  337. const second = gateway.subscribe({
  338. ...subscribeParams("sess-cold"),
  339. clientMode: "web-remote-replayable",
  340. connectionId: "conn-cold-2",
  341. });
  342. // 等真实恢复进入 barrier 后再放行,避免依赖内部 Promise 链的 microtask 层数。
  343. await resumeEntered.promise;
  344. resumeGate.resolve();
  345. const [a, b] = await Promise.all([first, second]);
  346. expect(host.resumeCalls).toEqual(["sess-cold"]);
  347. expect(loadedPersistedMessages).toEqual([messages]);
  348. expect(usagePersistedMessages).toEqual([messages]);
  349. if (a.initialFrame?.payload.kind !== "snapshot") {
  350. throw new Error("Expected desktop snapshot frame");
  351. }
  352. if (b.initialFrame?.payload.kind !== "snapshot") {
  353. throw new Error("Expected mobile snapshot frame");
  354. }
  355. expect(a.ack.subscriptionId).not.toBe(b.ack.subscriptionId);
  356. expect(a.initialFrame.payload.snapshot).toEqual(b.initialFrame.payload.snapshot);
  357. });
  358. it("cold READY 同时阻塞 command/query,完成后各只进入一次既有流程", async () => {
  359. const host = makeColdHost();
  360. const resumeStarted = deferred();
  361. const resumeGate = deferred();
  362. const hydrationStarted = deferred();
  363. const hydrationGate = deferred();
  364. const queryCommandId = "cmd-query-cold-ready";
  365. let discardedReady = false;
  366. host.resumeImpl = async (sessionId) => {
  367. // 复现 production:record 先入册,遗留 admitted input 在 resume 收尾时才变成 discarded。
  368. host.sessions.add(sessionId);
  369. resumeStarted.resolve();
  370. await resumeGate.promise;
  371. discardedReady = true;
  372. return { status: "resumed", persistedMessages: [] };
  373. };
  374. const admitCommandInput = vi.fn(async () => null);
  375. const executeCommand = vi.fn(async () => undefined);
  376. const invalidatePersistentCommandFacts = vi.fn();
  377. const lookupDiscardedCommand = vi.fn(async (key: { commandId: string }) =>
  378. discardedReady && key.commandId === queryCommandId
  379. ? {
  380. commandId: queryCommandId,
  381. status: "failed" as const,
  382. reasonCode: "fault.command.inputDiscardedOnRestart",
  383. revisionAtDecision: 0,
  384. }
  385. : null,
  386. );
  387. const gateway = new ConversationV4Gateway(
  388. {
  389. sessionExists: (sessionId) => host.sessions.has(sessionId),
  390. resumePersistedSession: coldResumeHook(host),
  391. loadPersistedEvents: async () => {
  392. hydrationStarted.resolve();
  393. await hydrationGate.promise;
  394. return { events: [], synthesized: true };
  395. },
  396. admitCommandInput,
  397. lookupDiscardedCommand,
  398. invalidatePersistentCommandFacts,
  399. emitWireFrame: () => {},
  400. executeCommand,
  401. },
  402. { now: () => 1_700_000_999_000, createLogEpoch: () => "epoch-cold" },
  403. );
  404. const sessionId = "sess-command-ready";
  405. const subscribing = gateway.subscribe(subscribeParams(sessionId));
  406. await resumeStarted.promise;
  407. let commandSettled = false;
  408. let querySettled = false;
  409. const commanding = gateway
  410. .handleCommand({
  411. commandId: "cmd-command-ready",
  412. clientId: "client-command-ready",
  413. sessionId,
  414. type: "sendText",
  415. payload: { text: "继续" },
  416. issuedAt: 1_700_000_999_000,
  417. })
  418. .then((ack) => {
  419. commandSettled = true;
  420. return ack;
  421. });
  422. const querying = gateway
  423. .queryCommands({ commands: [{ sessionId, commandId: queryCommandId }] })
  424. .then((result) => {
  425. querySettled = true;
  426. return result;
  427. });
  428. try {
  429. await nextMacrotask();
  430. expect(commandSettled).toBe(false);
  431. expect(querySettled).toBe(false);
  432. expect(admitCommandInput).not.toHaveBeenCalled();
  433. expect(lookupDiscardedCommand).not.toHaveBeenCalled();
  434. expect(executeCommand).not.toHaveBeenCalled();
  435. resumeGate.resolve();
  436. await hydrationStarted.promise;
  437. expect(invalidatePersistentCommandFacts).not.toHaveBeenCalled();
  438. await nextMacrotask();
  439. expect(commandSettled).toBe(false);
  440. expect(querySettled).toBe(false);
  441. expect(admitCommandInput).not.toHaveBeenCalled();
  442. expect(lookupDiscardedCommand).not.toHaveBeenCalled();
  443. expect(executeCommand).not.toHaveBeenCalled();
  444. hydrationGate.resolve();
  445. const [subscription, ack, query] = await Promise.all([subscribing, commanding, querying]);
  446. expect(subscription.initialFrame?.payload.kind).toBe("snapshot");
  447. expect(ack.status).toBe("accepted");
  448. expect(query.results).toEqual([
  449. {
  450. key: { sessionId, commandId: queryCommandId },
  451. result: {
  452. commandId: queryCommandId,
  453. status: "failed",
  454. reasonCode: "fault.command.inputDiscardedOnRestart",
  455. revisionAtDecision: 0,
  456. },
  457. },
  458. ]);
  459. expect(admitCommandInput).toHaveBeenCalledTimes(1);
  460. expect(executeCommand).toHaveBeenCalledTimes(1);
  461. expect(
  462. lookupDiscardedCommand.mock.calls.filter(([key]) => key.commandId === queryCommandId),
  463. ).toHaveLength(1);
  464. } finally {
  465. resumeGate.resolve();
  466. hydrationGate.resolve();
  467. await Promise.allSettled([subscribing, commanding, querying]);
  468. gateway.dispose();
  469. }
  470. });
  471. it("既有 live session 的首次 hydration 不引入 cold READY command 等待", async () => {
  472. const host = makeColdHost();
  473. host.sessions.add("sess-live-hydration");
  474. const hydrationStarted = deferred();
  475. const hydrationGate = deferred();
  476. const executeCommand = vi.fn(async () => undefined);
  477. const gateway = new ConversationV4Gateway({
  478. sessionExists: (sessionId) => host.sessions.has(sessionId),
  479. loadPersistedEvents: async () => {
  480. hydrationStarted.resolve();
  481. await hydrationGate.promise;
  482. return { events: [], synthesized: false };
  483. },
  484. emitWireFrame: () => {},
  485. executeCommand,
  486. });
  487. const subscribing = gateway.subscribe(subscribeParams("sess-live-hydration"));
  488. await hydrationStarted.promise;
  489. const commanding = gateway.handleCommand({
  490. commandId: "cmd-live-hydration",
  491. clientId: "client-live-hydration",
  492. sessionId: "sess-live-hydration",
  493. type: "sendText",
  494. payload: { text: "继续" },
  495. issuedAt: 1_700_000_999_000,
  496. });
  497. try {
  498. await nextMacrotask();
  499. expect(executeCommand).toHaveBeenCalledTimes(1);
  500. await expect(commanding).resolves.toMatchObject({ status: "accepted" });
  501. hydrationGate.resolve();
  502. await subscribing;
  503. } finally {
  504. hydrationGate.resolve();
  505. await Promise.allSettled([subscribing, commanding]);
  506. gateway.dispose();
  507. }
  508. });
  509. it("没有 cold READY 时 command 只由 inbox 解析一次", async () => {
  510. const executeCommand = vi.fn(async () => undefined);
  511. const gateway = new ConversationV4Gateway({
  512. sessionExists: () => true,
  513. emitWireFrame: () => {},
  514. executeCommand,
  515. });
  516. let sessionIdReads = 0;
  517. const command = {
  518. commandId: "cmd-without-cold-ready",
  519. clientId: "client-without-cold-ready",
  520. get sessionId() {
  521. sessionIdReads += 1;
  522. return "sess-without-cold-ready";
  523. },
  524. type: "sendText",
  525. payload: { text: "继续" },
  526. issuedAt: 1_700_000_999_000,
  527. };
  528. try {
  529. await expect(gateway.handleCommand(command)).resolves.toMatchObject({ status: "accepted" });
  530. expect(executeCommand).toHaveBeenCalledTimes(1);
  531. expect(sessionIdReads).toBe(1);
  532. } finally {
  533. gateway.dispose();
  534. }
  535. });
  536. it("record 已入册但冷恢复失败时:command 保留 lifecycle error,且绝不 admission", async () => {
  537. const host = makeColdHost();
  538. const resumeStarted = deferred();
  539. const resumeGate = deferred();
  540. const resumeError = new Error("resume storage failed");
  541. host.resumeImpl = async (sessionId) => {
  542. host.sessions.add(sessionId);
  543. resumeStarted.resolve();
  544. await resumeGate.promise;
  545. throw resumeError;
  546. };
  547. const admitCommandInput = vi.fn(async () => null);
  548. const executeCommand = vi.fn(async () => undefined);
  549. const gateway = new ConversationV4Gateway({
  550. sessionExists: (sessionId) => host.sessions.has(sessionId),
  551. resumePersistedSession: coldResumeHook(host),
  552. loadPersistedEvents: async () => ({ events: [], synthesized: true }),
  553. admitCommandInput,
  554. emitWireFrame: () => {},
  555. executeCommand,
  556. });
  557. const subscribing = gateway.subscribe(subscribeParams("sess-command-resume-failed"));
  558. await resumeStarted.promise;
  559. const commanding = gateway.handleCommand({
  560. commandId: "cmd-command-resume-failed",
  561. clientId: "client-command-resume-failed",
  562. sessionId: "sess-command-resume-failed",
  563. type: "sendText",
  564. payload: { text: "继续" },
  565. issuedAt: 1_700_000_999_000,
  566. });
  567. try {
  568. resumeGate.resolve();
  569. const [subscribeFailure, commandFailure] = await Promise.all([
  570. subscribing.catch((error: unknown) => error),
  571. commanding.catch((error: unknown) => error),
  572. ]);
  573. expect(subscribeFailure).toBeInstanceOf(V4SubscribeSessionUnavailableError);
  574. expect(commandFailure).toBe(subscribeFailure);
  575. expect((commandFailure as V4SubscribeSessionUnavailableError).reasonCode).toBe(
  576. "fault.subscribe.resumeFailed",
  577. );
  578. expect(host.sessions.has("sess-command-resume-failed")).toBe(true);
  579. expect(admitCommandInput).not.toHaveBeenCalled();
  580. expect(executeCommand).not.toHaveBeenCalled();
  581. } finally {
  582. resumeGate.resolve();
  583. await Promise.allSettled([subscribing, commanding]);
  584. gateway.dispose();
  585. }
  586. });
  587. it("store 里也没有:fault.subscribe.sessionNotFound(结构化 reasonCode)", async () => {
  588. const host = makeColdHost();
  589. host.resumeImpl = async () => ({ status: "notFound" });
  590. const gateway = makeColdGateway(host);
  591. const failure = await gateway
  592. .subscribe(subscribeParams("sess-ghost"))
  593. .then(() => null)
  594. .catch((error: unknown) => error);
  595. expect(failure).toBeInstanceOf(V4SubscribeSessionUnavailableError);
  596. const typed = failure as V4SubscribeSessionUnavailableError;
  597. expect(typed.reasonCode).toBe("fault.subscribe.sessionNotFound");
  598. // renderer 订阅错误块直显 message → reasonCode 必须随文透出。
  599. expect(typed.message).toContain("fault.subscribe.sessionNotFound");
  600. });
  601. it("record 入册前恢复失败:保留原始 cause,并释放 rejected READY entry", async () => {
  602. const host = makeColdHost();
  603. host.resumeImpl = async () => {
  604. // 只代表 production 中 record 入册前的失败;入册后的 lifecycle 恢复不属于 READY 的职责。
  605. throw new Error("sqlite is on fire");
  606. };
  607. const gateway = makeColdGateway(host);
  608. const failure = await gateway
  609. .subscribe(subscribeParams("sess-cold"))
  610. .then(() => null)
  611. .catch((error: unknown) => error);
  612. expect(failure).toBeInstanceOf(V4SubscribeSessionUnavailableError);
  613. const typed = failure as V4SubscribeSessionUnavailableError;
  614. expect(typed.reasonCode).toBe("fault.subscribe.resumeFailed");
  615. expect(typed.message).toContain("sqlite is on fire");
  616. expect((typed.cause as Error).message).toBe("sqlite is on fire");
  617. expect(host.errors.some((entry) => entry.scope === "v4.subscribe.resume")).toBe(true);
  618. expect(host.resumeCalls).toEqual(["sess-cold"]);
  619. // 这里只证明 rejected READY promise 没被缓存;不宣称 record 入册后的 activation 可自动重试。
  620. host.resumeImpl = async (sessionId) => {
  621. host.sessions.add(sessionId);
  622. return { status: "resumed" };
  623. };
  624. const retried = await gateway.subscribe(subscribeParams("sess-cold"));
  625. expect(retried.initialFrame?.payload.kind).toBe("snapshot");
  626. expect(host.resumeCalls).toEqual(["sess-cold", "sess-cold"]);
  627. });
  628. it("宿主未实现钩子(旧宿主/测试桩):维持 not active 拒绝且带 sessionNotFound", async () => {
  629. const host = makeColdHost();
  630. const gateway = makeColdGateway(host, { withResumeHook: false });
  631. await expect(gateway.subscribe(subscribeParams("sess-cold"))).rejects.toThrow(
  632. /not active.*fault\.subscribe\.sessionNotFound/,
  633. );
  634. });
  635. it("transcript 合成冷恢复:用 runtime usage seed 覆盖 0/20万占位 context meter", async () => {
  636. const host = makeColdHost();
  637. host.synthesizedSessions.add("sess-cold");
  638. host.persistedEvents.set("sess-cold", [
  639. makeEvent("sess-cold", 1, SessionEventType.SessionCreated, {
  640. mode: "default",
  641. contextWindow: 200_000,
  642. }),
  643. makeEvent("sess-cold", 2, SessionEventType.ModelComplete, {
  644. content: "",
  645. contextWindow: 200_000,
  646. querySource: "main_turn",
  647. stopReason: "end_turn",
  648. usage: {
  649. inputTokens: 0,
  650. outputTokens: 0,
  651. cacheReadTokens: 0,
  652. cacheWriteTokens: 0,
  653. },
  654. }),
  655. ]);
  656. host.usageSeeds.set("sess-cold", {
  657. contextWindow: {
  658. usedTokens: 16_727,
  659. maxTokens: 1_000_000,
  660. autoCompactThresholdTokens: null,
  661. cache: {
  662. inputTokens: 16_638,
  663. cacheReadTokens: 1408,
  664. cacheWriteTokens: 0,
  665. latestHitRate: 0.08462555595624474,
  666. hitRate: 0.08462555595624474,
  667. hitRateRequestCount: 1,
  668. totalInputTokens: 16_638,
  669. totalCacheReadTokens: 1408,
  670. totalCacheWriteTokens: 0,
  671. },
  672. breakdown: [
  673. { source: "system_prompt", chars: 3236 },
  674. { source: "system_tool_schemas", chars: 57_600 },
  675. ],
  676. },
  677. cumulative: {
  678. inputTokens: 16_638,
  679. outputTokens: 89,
  680. cacheReadTokens: 1408,
  681. cacheWriteTokens: 0,
  682. },
  683. });
  684. const gateway = makeColdGateway(host);
  685. const result = await gateway.subscribe(subscribeParams("sess-cold"));
  686. if (result.initialFrame?.payload.kind !== "snapshot") {
  687. throw new Error("Expected snapshot initial frame");
  688. }
  689. expect(result.initialFrame.payload.snapshot.usage.contextWindow).toMatchObject({
  690. usedTokens: 16_727,
  691. maxTokens: 1_000_000,
  692. cache: { hitRate: 0.08462555595624474 },
  693. breakdown: [
  694. { source: "system_prompt", chars: 3236 },
  695. { source: "system_tool_schemas", chars: 57_600 },
  696. ],
  697. });
  698. });
  699. });
  700. // ── 集成层(真 sqlite store + ZCodeProtocolAgentServer + binder)─────────────
  701. const WORKSPACE_PATH = "/workspace/cold-resume";
  702. const workspace = { workspacePath: WORKSPACE_PATH, workspaceKey: WORKSPACE_PATH };
  703. const REMOTE_WORKSPACE_IDENTITY =
  704. "remote:ssh:example.test:22:coder:/workspace/cold-resume" as WorkspaceId;
  705. const remoteWorkspace = {
  706. workspaceIdentity: REMOTE_WORKSPACE_IDENTITY,
  707. workspaceKey: REMOTE_WORKSPACE_IDENTITY,
  708. workspacePath: WORKSPACE_PATH,
  709. };
  710. type TestSessionStore = ReturnType<typeof createSqliteSessionStore>;
  711. async function requestResult(server: ZCodeProtocolAgentServer, message: ZCodeProtocolMessage) {
  712. const response = await server.handleMessage(message);
  713. if (!response || !("result" in response)) {
  714. throw new Error(`Expected protocol success response: ${JSON.stringify(response)}`);
  715. }
  716. return response.result;
  717. }
  718. function takeInitialFrameParams(
  719. server: ZCodeProtocolAgentServer,
  720. requestId: string | number,
  721. ): unknown {
  722. const messages = server.takePostResponseMessages(requestId);
  723. expect(messages).toHaveLength(1);
  724. expect(messages[0]).toMatchObject({ method: V4_NOTIFICATIONS.conversationFrame });
  725. const wire = routedTopicWireFrameSchema.parse((messages[0] as { params: unknown }).params);
  726. if (wire.kind !== "complete") {
  727. throw new Error("cold-resume initial-frame adapter expected one complete physical wire");
  728. }
  729. return wire.frame;
  730. }
  731. async function saveUserTextMessage(
  732. store: TestSessionStore,
  733. sessionId: SessionId,
  734. messageId: MessageId,
  735. text: string,
  736. created: number,
  737. ) {
  738. await store.saveMessage({
  739. id: messageId,
  740. sessionID: sessionId,
  741. role: "user",
  742. time: { created },
  743. agent: "zcode-agent",
  744. model: {
  745. providerID: "glm" as ModelProviderId,
  746. modelID: "glm-4-air" as ModelId,
  747. },
  748. tools: {},
  749. });
  750. await store.savePart({
  751. id: `${messageId}_text` as MessagePart["id"],
  752. sessionID: sessionId,
  753. messageID: messageId,
  754. type: "text",
  755. text,
  756. time: { start: created, end: created },
  757. });
  758. }
  759. async function saveAssistantTextMessage(
  760. store: TestSessionStore,
  761. sessionId: SessionId,
  762. messageId: MessageId,
  763. parentMessageId: MessageId,
  764. text: string,
  765. created: number,
  766. ) {
  767. await store.saveMessage({
  768. id: messageId,
  769. sessionID: sessionId,
  770. role: "assistant",
  771. time: { created, completed: created },
  772. parentID: parentMessageId,
  773. providerID: "glm" as ModelProviderId,
  774. modelID: "glm-4-air" as ModelId,
  775. mode: "build",
  776. agent: "zcode-agent",
  777. path: { cwd: WORKSPACE_PATH, root: WORKSPACE_PATH },
  778. cost: 0,
  779. tokens: { input: 1, output: 1, reasoning: 0, cache: { read: 0, write: 0 } },
  780. });
  781. await store.savePart({
  782. id: `${messageId}_text` as MessagePart["id"],
  783. sessionID: sessionId,
  784. messageID: messageId,
  785. type: "text",
  786. text,
  787. time: { start: created, end: created },
  788. });
  789. }
  790. /** 冷恢复集成用最小 fake app(子集自 zcode-protocol.test.ts createFakeApp)。 */
  791. interface ColdFakeAppProbe {
  792. persistedMessagesReloadRequired?: boolean;
  793. readTodosCalls: number;
  794. resumeCalls: number;
  795. resumeEventTypes?: SessionEvent["type"][];
  796. resumePersistedMessagesProvided?: boolean[];
  797. }
  798. function createColdFakeApp(
  799. options: ZCodeAppOptions | undefined,
  800. sentInputs: Array<{ text: string }>,
  801. probe?: ColdFakeAppProbe,
  802. ): ZCodeApp {
  803. const sessionId = options?.sessionId ?? ("sess_cold" as SessionId);
  804. const traceId = options?.traceContext?.traceId ?? ("trace_cold" as never);
  805. let runtimeSink: { onSessionEvent(event: SessionEvent): Promise<void> | void } | undefined;
  806. let mode = options?.runtimeConfig?.mode ?? "build";
  807. let model = options?.runtimeConfig?.modelSelection
  808. ? `${options.runtimeConfig.modelSelection.providerId}/${options.runtimeConfig.modelSelection.modelId}`
  809. : "glm/glm-4.6";
  810. let thoughtLevel = options?.runtimeConfig?.modelSelection?.options?.reasoningLevel ?? "medium";
  811. const providerRegistry = options?.providerRegistry;
  812. const initialProviderId = options?.runtimeConfig?.modelSelection?.providerId ?? "glm";
  813. const initialModelId = options?.runtimeConfig?.modelSelection?.modelId ?? "glm-4.6";
  814. let runtimeContextWindow =
  815. options?.runtimeConfig?.contextWindow ??
  816. providerRegistry?.getModel(initialProviderId, initialModelId)?.config.properties
  817. ?.contextWindow ??
  818. 128_000;
  819. const modelProperties = {
  820. inputFormat: {
  821. supportsText: true,
  822. supportsImage: false,
  823. supportsVideo: false,
  824. supportsAudio: false,
  825. supportsPdf: false,
  826. },
  827. outputFormat: { supportsText: true },
  828. } as const;
  829. const baseModels = [
  830. {
  831. ref: { providerId: "glm", modelId: "glm-4.6" },
  832. label: "GLM 4.6",
  833. providerLabel: "glm",
  834. properties: modelProperties,
  835. },
  836. {
  837. ref: { providerId: "glm", modelId: "glm-4-air" },
  838. label: "GLM 4 Air",
  839. providerLabel: "glm",
  840. properties: modelProperties,
  841. },
  842. ];
  843. let models = [...baseModels];
  844. return {
  845. clearTarget: async () => false,
  846. close: async () => {},
  847. connectMcpServer: async () => {
  848. throw new Error("MCP is not available in fake app");
  849. },
  850. continueActiveTarget: async () => null,
  851. disconnectMcpServer: async () => undefined,
  852. forkFromCheckpoint: async () => {
  853. throw new Error("Fork is not available in fake app");
  854. },
  855. getDefaultThoughtLevel: () => "medium",
  856. getLocale: () => "en-US",
  857. getMode: () => mode,
  858. getModel: () => model,
  859. getTheme: () => "auto",
  860. getThoughtLevel: () => thoughtLevel,
  861. generateWorkspaceText: async () => {
  862. throw new Error("Workspace text generation is not available in fake app");
  863. },
  864. listCheckpoints: async () => [],
  865. listMcpServers: async () => ({}),
  866. listModels: () => models,
  867. getModelOption: (selection) =>
  868. providerRegistry && getRegistryBackedModel(providerRegistry, selection),
  869. listPlugins: async () => ({ loaded: [], failed: [] }) as never,
  870. listThoughtLevels: () => ["medium", "deep"],
  871. loadSessionTranscript: async () => [],
  872. readToolResultArtifact: async (uri) => ({
  873. bytes: 0,
  874. content: "",
  875. contentType: "text/plain",
  876. uri,
  877. }),
  878. readTodos: async () => {
  879. if (probe) probe.readTodosCalls += 1;
  880. return [];
  881. },
  882. readTarget: async () => null,
  883. recallPreviousInputHistory: async () => null,
  884. recordInputHistory: async () => null,
  885. resume: async (resumeOptions) => {
  886. if (probe) probe.resumeCalls += 1;
  887. probe?.resumePersistedMessagesProvided?.push(resumeOptions?.persistedMessages !== undefined);
  888. for (const [index, type] of (probe?.resumeEventTypes ?? []).entries()) {
  889. const payload =
  890. type === SessionEventType.WorkspaceHookAdmissionUpdated
  891. ? {
  892. pendingCount: 0,
  893. bundleDigest: "cold-resume-hooks",
  894. }
  895. : {
  896. hookEventName: "SessionStart",
  897. hookIndex: 0,
  898. hookRunId: `cold-resume-hook-${index + 1}`,
  899. };
  900. await runtimeSink?.onSessionEvent(makeEvent(String(sessionId), index + 1, type, payload));
  901. }
  902. return {
  903. directory: options?.runtimeConfig?.workingDirectory ?? WORKSPACE_PATH,
  904. interruptedToolCount: 0,
  905. messageCount: 0,
  906. partCount: 0,
  907. persistedMessagesReloadRequired: probe?.persistedMessagesReloadRequired ?? false,
  908. restoredMessages: [],
  909. traceId,
  910. };
  911. },
  912. runtime: {
  913. // TTL pool 在 resident 未超水位时也要读取权威 idle facts;冷恢复 fake 必须和
  914. // 生产 runtime 一样显式声明没有前台或后台工作,不能再依赖旧容量分支短路。
  915. hasActiveOrQueuedTurnWork: () => false,
  916. hasRunningBackgroundTasks: () => false,
  917. hasResidencyBlockingWork: () => false,
  918. // 合并后 sendText 的 afterLegacyStateMutation 会经 auto-drain 读前台执行位;
  919. // 与上面同一条论证:fake 必须显式声明没有前台工作,而不是让属性缺席变成 TypeError。
  920. getActiveForegroundExecutionId: () => undefined,
  921. getSessionModelSelection: () => {
  922. const separator = model.indexOf("/");
  923. return {
  924. providerId: model.slice(0, separator),
  925. modelId: model.slice(separator + 1),
  926. ...(thoughtLevel ? { options: { reasoningLevel: thoughtLevel } } : {}),
  927. };
  928. },
  929. getProjection: async () =>
  930. ({
  931. activeToolCalls: [],
  932. backgroundTasks: [],
  933. contextUsed: 0,
  934. contextWindow: runtimeContextWindow,
  935. createdAt: new Date(1),
  936. id: sessionId,
  937. mode,
  938. pendingPermissions: [],
  939. pendingSteerInputs: [],
  940. status: "idle",
  941. streamingToolLedger: [],
  942. target: null,
  943. totalTokenCount: 0,
  944. turnCount: 0,
  945. updatedAt: new Date(1),
  946. }) as never,
  947. getActiveTurnInfo: () => undefined,
  948. initializeSessionShellEnvironmentIfNeeded: () => false,
  949. subscribeEvents: (sink) => {
  950. runtimeSink = sink;
  951. return () => {};
  952. },
  953. updateConfig: (patch) => {
  954. if ("contextWindow" in patch) {
  955. runtimeContextWindow = patch.contextWindow ?? 0;
  956. }
  957. },
  958. } as never,
  959. sendInput: async (input, sendOptions) => {
  960. const text = (input as { text: string }).text;
  961. sentInputs.push({ text });
  962. const turnStarted = {
  963. ...makeEvent(String(sessionId), 0, SessionEventType.TurnStarted, {
  964. input: text,
  965. inputId: sendOptions?.inputId,
  966. turnNumber: 3,
  967. }),
  968. turnId: "turn-cold-send",
  969. } as SessionEvent;
  970. await runtimeSink?.onSessionEvent(turnStarted);
  971. sendOptions?.onTurnStartedObserved?.(turnStarted);
  972. return { kind: "accepted" } as never;
  973. },
  974. sessionId,
  975. setLocale: async (locale) => ({
  976. configPath: "/tmp/zcode/config.json",
  977. locale: locale === "zh-CN" ? "zh-CN" : "en-US",
  978. previousLocale: "en-US",
  979. requestedLocale: locale,
  980. traceId,
  981. }),
  982. setMode: async (nextMode) => {
  983. const previousMode = mode;
  984. mode = nextMode;
  985. return { mode, previousMode, traceId };
  986. },
  987. setPluginEnabled: async () => {
  988. throw new Error("Plugins are not available in fake app");
  989. },
  990. setTarget: async () => {
  991. throw new Error("Targets are not available in fake app");
  992. },
  993. setModel: async (nextModel) => {
  994. if (
  995. !models.some((option) => `${option.ref.providerId}/${option.ref.modelId}` === nextModel)
  996. ) {
  997. throw new Error(`Unsupported model in fake app: ${nextModel}`);
  998. }
  999. const previousModel = model;
  1000. model = nextModel;
  1001. return { model, previousModel, traceId };
  1002. },
  1003. setThoughtLevel: async (level) => {
  1004. const previousThoughtLevel = thoughtLevel;
  1005. thoughtLevel = level;
  1006. return { previousThoughtLevel, thoughtLevel, traceId };
  1007. },
  1008. steerTurn: async () => ({ kind: "rejected", reason: "no_active_turn" }),
  1009. submitPrompt: async () => {
  1010. throw new Error("Prompt execution is not available in fake app");
  1011. },
  1012. traceId,
  1013. updateTargetStatus: async () => null,
  1014. } as ZCodeApp;
  1015. }
  1016. const SESSION_ID = "sess_cold_resume" as SessionId;
  1017. const PARENT_SESSION_ID = "sess_cold_parent" as SessionId;
  1018. function createColdProviderRegistry(): ProviderRegistry {
  1019. const modelConfig = new ModelConfig({
  1020. properties: new ModelPropertiesConfig({
  1021. requiresMfjsToolSchema: false,
  1022. contextWindow: 1_000_000,
  1023. inputFormat: {
  1024. supportsText: true,
  1025. supportsImage: true,
  1026. supportsVideo: true,
  1027. supportsAudio: false,
  1028. supportsPdf: true,
  1029. },
  1030. outputFormat: { supportsText: true },
  1031. supportsToolCall: true,
  1032. supportsJsonSchemaOutput: true,
  1033. supportsNativeWebSearch: false,
  1034. supportsMidConversationSystem: true,
  1035. }),
  1036. optionSpecs: new ModelOptionSpecsConfig({
  1037. reasoningLevel: {
  1038. values: ["medium", "deep"],
  1039. map: '{"reasoning_effort":reasoningLevel}',
  1040. },
  1041. maxOutputTokens: {
  1042. max: 32_000,
  1043. map: '{"max_completion_tokens":maxOutputTokens}',
  1044. },
  1045. }),
  1046. });
  1047. const provider: Provider = {
  1048. providerId: "glm",
  1049. config: createApiKeyProviderConfig({
  1050. apiFormat: "openai-chat-completions",
  1051. apiKey: "sk-test",
  1052. baseURL: "https://api.example.test/v1",
  1053. models: ["glm-4-air", "glm-4.6"],
  1054. }),
  1055. models: [
  1056. { modelId: "glm-4-air", config: modelConfig },
  1057. { modelId: "glm-4.6", config: modelConfig },
  1058. ],
  1059. };
  1060. return new ProviderRegistry([provider]);
  1061. }
  1062. describe("v4 冷恢复(集成:真 sqlite + server + binder)", () => {
  1063. let tempRoot: string;
  1064. beforeEach(async () => {
  1065. tempRoot = await mkdtemp(join(tmpdir(), "zcode-v4-cold-resume-"));
  1066. });
  1067. afterEach(async () => {
  1068. await rm(tempRoot, { force: true, recursive: true });
  1069. });
  1070. /** 第一段人生:往 store 写入一段 user/assistant transcript 后关库(模拟 CLI 退出)。 */
  1071. async function seedPersistedSession(
  1072. dbPath: string,
  1073. workspaceIdentity?: WorkspaceId,
  1074. taskType: "interactive" | "fork" | "subagent_child" = "interactive",
  1075. ): Promise<void> {
  1076. const store = createSqliteSessionStore({ dbPath });
  1077. try {
  1078. await store.createSession({
  1079. id: SESSION_ID,
  1080. parentID: PARENT_SESSION_ID,
  1081. taskType,
  1082. projectID: "project_cold_resume" as ProjectId,
  1083. ...(workspaceIdentity ? { workspaceID: workspaceIdentity } : {}),
  1084. slug: "cold-resume-session",
  1085. directory: WORKSPACE_PATH,
  1086. path: WORKSPACE_PATH,
  1087. title: "Cold resume session",
  1088. version: "test-version",
  1089. time: { created: 1, updated: 4 },
  1090. });
  1091. await saveUserTextMessage(store, SESSION_ID, "msg_cold_user_1" as MessageId, "历史问题一", 1);
  1092. await saveAssistantTextMessage(
  1093. store,
  1094. SESSION_ID,
  1095. "msg_cold_assistant_1" as MessageId,
  1096. "msg_cold_user_1" as MessageId,
  1097. "历史回答一",
  1098. 2,
  1099. );
  1100. await saveUserTextMessage(store, SESSION_ID, "msg_cold_user_2" as MessageId, "历史问题二", 3);
  1101. await saveAssistantTextMessage(
  1102. store,
  1103. SESSION_ID,
  1104. "msg_cold_assistant_2" as MessageId,
  1105. "msg_cold_user_2" as MessageId,
  1106. "历史回答二",
  1107. 4,
  1108. );
  1109. await store.savePart({
  1110. id: "msg_cold_assistant_2_reasoning" as MessagePart["id"],
  1111. sessionID: SESSION_ID,
  1112. messageID: "msg_cold_assistant_2" as MessageId,
  1113. type: "reasoning",
  1114. text: "历史思考二",
  1115. time: { start: 4, end: 4 },
  1116. });
  1117. await store.savePart({
  1118. id: "msg_cold_assistant_2_tool" as MessagePart["id"],
  1119. sessionID: SESSION_ID,
  1120. messageID: "msg_cold_assistant_2" as MessageId,
  1121. type: "tool",
  1122. callID: "call_cold_read",
  1123. tool: "Read",
  1124. state: {
  1125. status: "completed",
  1126. input: { file_path: "README.md" },
  1127. output: "历史工具输出",
  1128. title: "Read README.md",
  1129. metadata: {},
  1130. time: { start: 4, end: 4 },
  1131. },
  1132. });
  1133. } finally {
  1134. store.close();
  1135. }
  1136. }
  1137. async function seedPersistedCompactedSession(dbPath: string): Promise<void> {
  1138. await seedPersistedSession(dbPath);
  1139. const store = createSqliteSessionStore({ dbPath });
  1140. const summaryMessageId = "msg_cold_compact_summary" as MessageId;
  1141. const compactBoundary: CompactBoundaryPayload = {
  1142. boundaryId: "boundary_cold_compact",
  1143. trigger: CompactTrigger.Manual,
  1144. preCompactTokenCount: 2,
  1145. postCompactTokenCount: 2,
  1146. truePostCompactTokenCount: 1,
  1147. summarizedMessageCount: 4,
  1148. summaryMessageIds: [summaryMessageId],
  1149. traceId: "trace_cold_compact" as TraceId,
  1150. };
  1151. try {
  1152. await store.saveMessage({
  1153. id: summaryMessageId,
  1154. sessionID: SESSION_ID,
  1155. role: "user",
  1156. time: { created: 5 },
  1157. summary: { title: "Compact summary", body: "压缩后的摘要", diffs: [] },
  1158. agent: "zcode-agent",
  1159. model: {
  1160. providerID: "glm" as ModelProviderId,
  1161. modelID: "glm-4-air" as ModelId,
  1162. },
  1163. tools: {},
  1164. });
  1165. await store.savePart({
  1166. id: "part_cold_compact_boundary" as MessagePart["id"],
  1167. sessionID: SESSION_ID,
  1168. messageID: summaryMessageId,
  1169. type: "compaction",
  1170. auto: false,
  1171. compactBoundary,
  1172. });
  1173. } finally {
  1174. store.close();
  1175. }
  1176. }
  1177. /** 第二段人生:同一 db 文件重开 → 新 server(内存注册表为空 = CLI 重启)。 */
  1178. function bootRestartedServer(
  1179. dbPath: string,
  1180. sentInputs: Array<{ text: string }>,
  1181. probe?: ColdFakeAppProbe,
  1182. createdAppOptions: ZCodeAppOptions[] = [],
  1183. ) {
  1184. const store = createSqliteSessionStore({ dbPath });
  1185. const providerRegistry = createColdProviderRegistry();
  1186. const server = new ZCodeProtocolAgentServer({
  1187. createZCodeApp: (options) => {
  1188. const effectiveOptions = { ...options, providerRegistry };
  1189. createdAppOptions.push(effectiveOptions);
  1190. return createColdFakeApp(effectiveOptions, sentInputs, probe);
  1191. },
  1192. cwd: WORKSPACE_PATH,
  1193. sessionStore: store,
  1194. });
  1195. return { server, store };
  1196. }
  1197. // 模型恢复须走真实 App,不能让生命周期测试替身复制生产迁移逻辑。
  1198. function bootRealRestartedServer(dbPath: string, registry = createColdProviderRegistry()) {
  1199. const store = createSqliteSessionStore({ dbPath });
  1200. const apps: ZCodeApp[] = [];
  1201. const server = new ZCodeProtocolAgentServer({
  1202. cwd: process.cwd(),
  1203. sessionStore: store,
  1204. createZCodeApp: async (options) => {
  1205. const app = await createRegistryBackedTestApp({
  1206. ...options,
  1207. env: {},
  1208. skipUserConfig: true,
  1209. providerRegistry: registry,
  1210. });
  1211. apps.push(app);
  1212. return app;
  1213. },
  1214. });
  1215. server.setNotificationSink((message) => {
  1216. if (!("id" in message)) return;
  1217. if (message.method === zcodeProtocolMethods.sessionRequestRuntimePreferences) {
  1218. void server.handleMessage({
  1219. id: message.id,
  1220. result: {
  1221. nativeSearchEnhancementsEnabled: false,
  1222. memoryEnabled: false,
  1223. },
  1224. });
  1225. }
  1226. });
  1227. return {
  1228. server,
  1229. apps,
  1230. close: async () => {
  1231. for (const app of apps) await app.close();
  1232. store.close();
  1233. },
  1234. };
  1235. }
  1236. it.each(["desktop-continuous", "web-remote-replayable"] as const)(
  1237. "Todo123: %s 缺档位旧选择仍按 Registry 展示 1M,执行选择不被补齐",
  1238. async (clientMode) => {
  1239. const dbPath = join(tempRoot, "missing-reasoning.db");
  1240. await seedPersistedSession(dbPath);
  1241. const store = createSqliteSessionStore({ dbPath });
  1242. const selection = { providerId: "glm", modelId: "glm-4-air" };
  1243. await store.saveSessionEntry({
  1244. id: "entry_missing_reasoning",
  1245. sessionID: SESSION_ID,
  1246. type: SESSION_ENTRY_MODEL_SELECTION,
  1247. data: selection,
  1248. time: { created: 5, updated: 5 },
  1249. });
  1250. store.close();
  1251. const { server, apps, close } = bootRealRestartedServer(dbPath);
  1252. try {
  1253. await requestResult(server, {
  1254. id: "missing-reasoning",
  1255. method: V4_METHODS.conversationSubscribe,
  1256. params: { topic: conversationTopic(SESSION_ID), connectionId: clientMode, clientMode },
  1257. });
  1258. const frame = conversationTopicFrameSchema.parse(
  1259. takeInitialFrameParams(server, "missing-reasoning"),
  1260. );
  1261. if (frame.payload.kind !== "snapshot") throw new Error("Expected snapshot");
  1262. expect(frame.payload.snapshot.config.modelSelection).toEqual(selection);
  1263. expect(frame.payload.snapshot.usage.contextWindow).toMatchObject({
  1264. usedTokens: 2,
  1265. maxTokens: 1_000_000,
  1266. });
  1267. expect(apps[0].runtime.getSessionModelSelection()).toBeUndefined();
  1268. expect(
  1269. frame.payload.snapshot.rows.window.some(
  1270. (row) => row.kind === "assistantText" && row.text === "历史回答二",
  1271. ),
  1272. ).toBe(true);
  1273. } finally {
  1274. await close();
  1275. }
  1276. },
  1277. );
  1278. it("Todo123: 无对应 Registry 模型仍可冷读内容,容量未知而非 20 万", async () => {
  1279. const dbPath = join(tempRoot, "unknown-model.db");
  1280. await seedPersistedSession(dbPath);
  1281. const { server, close } = bootRealRestartedServer(dbPath, new ProviderRegistry([]));
  1282. try {
  1283. await requestResult(server, {
  1284. id: "unknown-model",
  1285. method: V4_METHODS.conversationSubscribe,
  1286. params: {
  1287. topic: conversationTopic(SESSION_ID),
  1288. connectionId: "unknown",
  1289. clientMode: "desktop-continuous",
  1290. },
  1291. });
  1292. const frame = conversationTopicFrameSchema.parse(
  1293. takeInitialFrameParams(server, "unknown-model"),
  1294. );
  1295. if (frame.payload.kind !== "snapshot") throw new Error("Expected snapshot");
  1296. expect(frame.payload.snapshot.usage.contextWindow).toBeNull();
  1297. expect(
  1298. frame.payload.snapshot.rows.window.some(
  1299. (row) => row.kind === "assistantText" && row.text === "历史回答二",
  1300. ),
  1301. ).toBe(true);
  1302. } finally {
  1303. await close();
  1304. }
  1305. });
  1306. it("rowsRange-first 与 subscribe 并发时只按 Host 当前设置冷恢复一次", async () => {
  1307. const dbPath = join(tempRoot, "sessions.db");
  1308. await seedPersistedSession(dbPath);
  1309. const createdAppOptions: ZCodeAppOptions[] = [];
  1310. const { server, store } = bootRestartedServer(dbPath, [], undefined, createdAppOptions);
  1311. let pendingPreferenceRequestId: string | number | undefined;
  1312. let markPreferenceRequested: (() => void) | undefined;
  1313. const preferenceRequested = new Promise<void>((resolve) => {
  1314. markPreferenceRequested = resolve;
  1315. });
  1316. const preferenceRequests: ZCodeProtocolMessage[] = [];
  1317. server.setNotificationSink((message) => {
  1318. if (
  1319. "id" in message &&
  1320. message.method === zcodeProtocolMethods.sessionRequestRuntimePreferences
  1321. ) {
  1322. preferenceRequests.push(message);
  1323. pendingPreferenceRequestId = message.id;
  1324. markPreferenceRequested?.();
  1325. }
  1326. });
  1327. try {
  1328. const rowsPromise = requestResult(server, {
  1329. id: 2,
  1330. method: V4_METHODS.conversationRowsRange,
  1331. params: { sessionId: SESSION_ID, limit: 20 },
  1332. });
  1333. await preferenceRequested;
  1334. const subscribePromise = requestResult(server, {
  1335. id: 3,
  1336. method: V4_METHODS.conversationSubscribe,
  1337. params: {
  1338. topic: conversationTopic(SESSION_ID),
  1339. connectionId: "conn-query-first",
  1340. clientMode: "desktop-continuous",
  1341. },
  1342. });
  1343. await server.handleMessage({
  1344. id: pendingPreferenceRequestId!,
  1345. result: {
  1346. nativeSearchEnhancementsEnabled: false,
  1347. memoryEnabled: false,
  1348. },
  1349. });
  1350. const [rows] = await Promise.all([rowsPromise, subscribePromise]);
  1351. expect(v4ConversationRowsRangeResultSchema.parse(rows).rows).not.toHaveLength(0);
  1352. expect(preferenceRequests).toHaveLength(1);
  1353. expect(preferenceRequests[0]).toMatchObject({
  1354. params: { sessionId: SESSION_ID, scope: "runtime-materialization" },
  1355. });
  1356. const resumedRuntimeOptions = createdAppOptions.filter(
  1357. (options) => options.sessionId === SESSION_ID,
  1358. );
  1359. expect(resumedRuntimeOptions).toHaveLength(1);
  1360. expect(resumedRuntimeOptions[0]?.runtimeConfig?.nativeSearchEnhancementsEnabled).toBe(false);
  1361. expect(resumedRuntimeOptions[0]?.runtimeConfig?.memory?.enabled).toBe(false);
  1362. } finally {
  1363. store.close();
  1364. }
  1365. });
  1366. it("冷恢复 3.4.2 遗留的 WSL 显式用户任务时修复真实工作目录", async () => {
  1367. const dbPath = join(tempRoot, "sessions.db");
  1368. const legacySessionId = "sess_wsl_explicit_user_legacy" as SessionId;
  1369. const unrelatedSessionId = "sess_wsl_explicit_user_unrelated" as SessionId;
  1370. const workspacePath = "/home/dev/coding/DEMO-ERP-NEW";
  1371. const workspaceIdentity =
  1372. "remote:wsl:Ubuntu-24.04:dev:/home/dev/coding/DEMO-ERP-NEW" as WorkspaceId;
  1373. const unrelatedWorkspaceIdentity =
  1374. "remote:wsl:Ubuntu-24.04:other:/home/dev/coding/DEMO-ERP-NEW" as WorkspaceId;
  1375. const seedStore = createSqliteSessionStore({ dbPath });
  1376. try {
  1377. await seedStore.createSession({
  1378. id: legacySessionId,
  1379. projectID: "project_wsl_explicit_user_legacy" as ProjectId,
  1380. slug: "wsl-explicit-user-legacy",
  1381. directory: workspaceIdentity,
  1382. path: workspaceIdentity,
  1383. title: "WSL legacy task",
  1384. version: "3.4.2",
  1385. time: { created: 1, updated: 2 },
  1386. });
  1387. await seedStore.createSession({
  1388. id: unrelatedSessionId,
  1389. projectID: "project_wsl_explicit_user_unrelated" as ProjectId,
  1390. slug: "wsl-explicit-user-unrelated",
  1391. directory: unrelatedWorkspaceIdentity,
  1392. path: unrelatedWorkspaceIdentity,
  1393. title: "Unrelated WSL legacy task",
  1394. version: "3.4.2",
  1395. time: { created: 3, updated: 4 },
  1396. });
  1397. } finally {
  1398. seedStore.close();
  1399. }
  1400. const store = createSqliteSessionStore({ dbPath });
  1401. const resumedWorkingDirectories: string[] = [];
  1402. const server = new ZCodeProtocolAgentServer({
  1403. createZCodeApp: (options) => {
  1404. resumedWorkingDirectories.push(options?.runtimeConfig?.workingDirectory ?? "");
  1405. return createColdFakeApp(options, []);
  1406. },
  1407. cwd: workspacePath,
  1408. sessionStore: store,
  1409. });
  1410. try {
  1411. await requestResult(server, {
  1412. id: "wsl-legacy-resume",
  1413. method: V4_METHODS.conversationSubscribe,
  1414. params: {
  1415. topic: conversationTopic(legacySessionId),
  1416. connectionId: "conn-wsl-legacy-resume",
  1417. clientMode: "desktop-continuous",
  1418. },
  1419. });
  1420. expect(resumedWorkingDirectories).toEqual([workspacePath]);
  1421. await expect(store.getSession(legacySessionId)).resolves.toMatchObject({
  1422. directory: workspacePath,
  1423. path: workspacePath,
  1424. workspaceID: workspaceIdentity,
  1425. });
  1426. await expect(store.getSession(unrelatedSessionId)).resolves.toMatchObject({
  1427. directory: unrelatedWorkspaceIdentity,
  1428. path: unrelatedWorkspaceIdentity,
  1429. workspaceID: undefined,
  1430. });
  1431. } finally {
  1432. store.close();
  1433. }
  1434. });
  1435. it("冷恢复被 path.resolve 拼接过 remote identity 的 3.4.2 WSL 任务", async () => {
  1436. const dbPath = join(tempRoot, "sessions.db");
  1437. const legacySessionId = "sess_wsl_resolved_identity_legacy" as SessionId;
  1438. const workspacePath = "/home/dev/coding/DEMO-ERP-NEW";
  1439. const workspaceIdentity =
  1440. "remote:wsl:Ubuntu-24.04:dev:/home/dev/coding/DEMO-ERP-NEW" as WorkspaceId;
  1441. const resolvedLegacyDirectory = `${workspacePath}/${workspaceIdentity}`;
  1442. const seedStore = createSqliteSessionStore({ dbPath });
  1443. try {
  1444. await seedStore.createSession({
  1445. id: legacySessionId,
  1446. projectID: "project_wsl_resolved_identity_legacy" as ProjectId,
  1447. slug: "wsl-resolved-identity-legacy",
  1448. directory: resolvedLegacyDirectory,
  1449. path: resolvedLegacyDirectory,
  1450. title: "WSL resolved identity legacy task",
  1451. version: "3.4.2",
  1452. time: { created: 1, updated: 2 },
  1453. });
  1454. } finally {
  1455. seedStore.close();
  1456. }
  1457. const store = createSqliteSessionStore({ dbPath });
  1458. const resumedWorkingDirectories: string[] = [];
  1459. const server = new ZCodeProtocolAgentServer({
  1460. createZCodeApp: (options) => {
  1461. resumedWorkingDirectories.push(options?.runtimeConfig?.workingDirectory ?? "");
  1462. return createColdFakeApp(options, []);
  1463. },
  1464. cwd: workspacePath,
  1465. sessionStore: store,
  1466. });
  1467. try {
  1468. await requestResult(server, {
  1469. id: "wsl-resolved-legacy-resume",
  1470. method: V4_METHODS.conversationSubscribe,
  1471. params: {
  1472. topic: conversationTopic(legacySessionId),
  1473. connectionId: "conn-wsl-resolved-legacy-resume",
  1474. clientMode: "desktop-continuous",
  1475. },
  1476. });
  1477. expect(resumedWorkingDirectories).toEqual([workspacePath]);
  1478. await expect(store.getSession(legacySessionId)).resolves.toMatchObject({
  1479. directory: workspacePath,
  1480. path: workspacePath,
  1481. workspaceID: workspaceIdentity,
  1482. });
  1483. } finally {
  1484. store.close();
  1485. }
  1486. });
  1487. it("NULL identity 原子修复未命中且重读仍污染时禁止物化 runtime", async () => {
  1488. const dbPath = join(tempRoot, "sessions.db");
  1489. const sessionId = "sess_wsl_failed_atomic_repair" as SessionId;
  1490. const workspacePath = "/home/dev/project";
  1491. const workspaceIdentity = "remote:wsl:Debian:dev:/home/dev/project" as WorkspaceId;
  1492. const store = createSqliteSessionStore({ dbPath });
  1493. await store.createSession({
  1494. id: sessionId,
  1495. projectID: "project_wsl_failed_atomic_repair" as ProjectId,
  1496. slug: "wsl-failed-atomic-repair",
  1497. directory: workspaceIdentity,
  1498. path: workspaceIdentity,
  1499. title: "WSL failed atomic repair",
  1500. version: "3.4.2",
  1501. time: { created: 1, updated: 2 },
  1502. });
  1503. store.repairLegacyRemoteSessionWorkspace = vi.fn(async () => false);
  1504. const resumedWorkingDirectories: string[] = [];
  1505. const server = new ZCodeProtocolAgentServer({
  1506. createZCodeApp: (options) => {
  1507. resumedWorkingDirectories.push(options?.runtimeConfig?.workingDirectory ?? "");
  1508. return createColdFakeApp(options, []);
  1509. },
  1510. cwd: workspacePath,
  1511. sessionStore: store,
  1512. });
  1513. try {
  1514. const response = await server.handleMessage({
  1515. id: "wsl-failed-atomic-repair",
  1516. method: V4_METHODS.conversationSubscribe,
  1517. params: {
  1518. topic: conversationTopic(sessionId),
  1519. connectionId: "conn-wsl-failed-atomic-repair",
  1520. clientMode: "desktop-continuous",
  1521. },
  1522. });
  1523. expect(response).toMatchObject({
  1524. error: { message: expect.stringContaining("workspace repair") },
  1525. });
  1526. expect(resumedWorkingDirectories).toEqual([]);
  1527. await expect(store.getSession(sessionId)).resolves.toMatchObject({
  1528. directory: workspaceIdentity,
  1529. path: workspaceIdentity,
  1530. workspaceID: undefined,
  1531. });
  1532. } finally {
  1533. store.close();
  1534. }
  1535. });
  1536. it("NULL identity 原子修复返回未命中但并发请求已完整修复时继续恢复", async () => {
  1537. const dbPath = join(tempRoot, "sessions.db");
  1538. const sessionId = "sess_wsl_concurrent_atomic_repair" as SessionId;
  1539. const workspacePath = "/home/dev/project";
  1540. const workspaceIdentity = "remote:wsl:Debian:dev:/home/dev/project" as WorkspaceId;
  1541. const store = createSqliteSessionStore({ dbPath });
  1542. await store.createSession({
  1543. id: sessionId,
  1544. projectID: "project_wsl_concurrent_atomic_repair" as ProjectId,
  1545. slug: "wsl-concurrent-atomic-repair",
  1546. directory: workspaceIdentity,
  1547. path: workspaceIdentity,
  1548. title: "WSL concurrent atomic repair",
  1549. version: "3.4.2",
  1550. time: { created: 1, updated: 2 },
  1551. });
  1552. const persistRepair = store.repairLegacyRemoteSessionWorkspace.bind(store);
  1553. store.repairLegacyRemoteSessionWorkspace = vi.fn(async (input) => {
  1554. await persistRepair(input);
  1555. return false;
  1556. });
  1557. const resumedWorkingDirectories: string[] = [];
  1558. const server = new ZCodeProtocolAgentServer({
  1559. createZCodeApp: (options) => {
  1560. resumedWorkingDirectories.push(options?.runtimeConfig?.workingDirectory ?? "");
  1561. return createColdFakeApp(options, []);
  1562. },
  1563. cwd: workspacePath,
  1564. sessionStore: store,
  1565. });
  1566. try {
  1567. await requestResult(server, {
  1568. id: "wsl-concurrent-atomic-repair",
  1569. method: V4_METHODS.conversationSubscribe,
  1570. params: {
  1571. topic: conversationTopic(sessionId),
  1572. connectionId: "conn-wsl-concurrent-atomic-repair",
  1573. clientMode: "desktop-continuous",
  1574. },
  1575. });
  1576. expect(resumedWorkingDirectories).toEqual([workspacePath]);
  1577. await expect(store.getSession(sessionId)).resolves.toMatchObject({
  1578. directory: workspacePath,
  1579. path: workspacePath,
  1580. workspaceID: workspaceIdentity,
  1581. });
  1582. } finally {
  1583. store.close();
  1584. }
  1585. });
  1586. it("SSH 冷订阅 sessions-index:只迁移 task-index allowlist 证明归属的 3.3.6 历史会话", async () => {
  1587. const dbPath = join(tempRoot, "sessions.db");
  1588. const seedStore = createSqliteSessionStore({ dbPath });
  1589. const currentSessionId = "sess_current_remote_index" as SessionId;
  1590. const foreignSessionId = "sess_foreign_remote_index" as SessionId;
  1591. const unprovenLegacySessionId = "sess_unproven_legacy_remote_index" as SessionId;
  1592. const remoteWorkspaceIdentity = "remote:ssh:example.test:22:coder:/workspace/cold-resume";
  1593. const foreignWorkspaceIdentity =
  1594. "remote:ssh:other.example.test:22:coder:/workspace/cold-resume";
  1595. try {
  1596. await seedStore.createSession({
  1597. id: SESSION_ID,
  1598. projectID: "project_remote_index" as ProjectId,
  1599. slug: "remote-index-session",
  1600. directory: WORKSPACE_PATH,
  1601. path: WORKSPACE_PATH,
  1602. title: "Remote index session",
  1603. version: "test-version",
  1604. time: { created: 1, updated: 2 },
  1605. });
  1606. await seedStore.createSession({
  1607. id: currentSessionId,
  1608. projectID: "project_current_remote_index" as ProjectId,
  1609. workspaceID: remoteWorkspaceIdentity as WorkspaceId,
  1610. slug: "current-remote-index-session",
  1611. directory: WORKSPACE_PATH,
  1612. path: WORKSPACE_PATH,
  1613. title: "Current remote index session",
  1614. version: "test-version",
  1615. time: { created: 3, updated: 4 },
  1616. });
  1617. await seedStore.createSession({
  1618. id: unprovenLegacySessionId,
  1619. projectID: "project_unproven_legacy_remote_index" as ProjectId,
  1620. slug: "unproven-legacy-remote-index-session",
  1621. directory: WORKSPACE_PATH,
  1622. path: WORKSPACE_PATH,
  1623. title: "Unproven legacy remote index session",
  1624. version: "test-version",
  1625. time: { created: 4, updated: 5 },
  1626. });
  1627. await seedStore.createSession({
  1628. id: foreignSessionId,
  1629. projectID: "project_foreign_remote_index" as ProjectId,
  1630. workspaceID: foreignWorkspaceIdentity as WorkspaceId,
  1631. slug: "foreign-remote-index-session",
  1632. directory: WORKSPACE_PATH,
  1633. path: WORKSPACE_PATH,
  1634. title: "Foreign remote index session",
  1635. version: "test-version",
  1636. time: { created: 5, updated: 6 },
  1637. });
  1638. } finally {
  1639. seedStore.close();
  1640. }
  1641. const { server, store } = bootRestartedServer(dbPath, []);
  1642. try {
  1643. await requestResult(server, {
  1644. id: "remote-index",
  1645. method: V4_METHODS.conversationSubscribe,
  1646. params: {
  1647. topic: sessionsIndexTopic(remoteWorkspaceIdentity),
  1648. connectionId: "conn-remote-index",
  1649. clientMode: "desktop-continuous",
  1650. legacyTaskIds: [SESSION_ID],
  1651. },
  1652. });
  1653. const frame = sessionsIndexTopicFrameSchema.parse(
  1654. takeInitialFrameParams(server, "remote-index"),
  1655. );
  1656. if (frame.payload.kind !== "snapshot") {
  1657. throw new Error("Expected sessions-index snapshot frame");
  1658. }
  1659. expect(frame.payload.snapshot.workspaceId).toBe(remoteWorkspaceIdentity);
  1660. expect(frame.payload.snapshot.sessions).toEqual([
  1661. expect.objectContaining({
  1662. sessionId: currentSessionId,
  1663. workspaceId: remoteWorkspaceIdentity,
  1664. title: "Current remote index session",
  1665. }),
  1666. expect.objectContaining({
  1667. sessionId: SESSION_ID,
  1668. workspaceId: remoteWorkspaceIdentity,
  1669. title: "Remote index session",
  1670. }),
  1671. ]);
  1672. await expect(store.getSession(SESSION_ID)).resolves.toMatchObject({
  1673. workspaceID: remoteWorkspaceIdentity,
  1674. });
  1675. expect((await store.getSession(unprovenLegacySessionId))?.workspaceID).toBeUndefined();
  1676. await expect(store.getSession(foreignSessionId)).resolves.toMatchObject({
  1677. workspaceID: foreignWorkspaceIdentity,
  1678. });
  1679. // 未被当前 identity 的 task index 证明归属的空 identity 会话不得迁移;
  1680. // 同一数据库里的本地路径订阅仍只能看到这条未归属记录。
  1681. await requestResult(server, {
  1682. id: "local-index-after-remote",
  1683. method: V4_METHODS.conversationSubscribe,
  1684. params: {
  1685. topic: sessionsIndexTopic(WORKSPACE_PATH),
  1686. connectionId: "conn-local-index-after-remote",
  1687. clientMode: "desktop-continuous",
  1688. },
  1689. });
  1690. const localFrame = sessionsIndexTopicFrameSchema.parse(
  1691. takeInitialFrameParams(server, "local-index-after-remote"),
  1692. );
  1693. if (localFrame.payload.kind !== "snapshot") {
  1694. throw new Error("Expected local sessions-index snapshot frame");
  1695. }
  1696. expect(localFrame.payload.snapshot.sessions).toEqual([
  1697. expect.objectContaining({ sessionId: unprovenLegacySessionId }),
  1698. ]);
  1699. } finally {
  1700. store.close();
  1701. }
  1702. });
  1703. it("本地路径冷订阅 sessions-index:保持原目录查询语义", async () => {
  1704. const dbPath = join(tempRoot, "sessions.db");
  1705. const seedStore = createSqliteSessionStore({ dbPath });
  1706. const remoteSessionId = "sess_remote_same_path" as SessionId;
  1707. try {
  1708. await seedStore.createSession({
  1709. id: SESSION_ID,
  1710. projectID: "project_local_index" as ProjectId,
  1711. slug: "local-index-session",
  1712. directory: WORKSPACE_PATH,
  1713. path: WORKSPACE_PATH,
  1714. title: "Local index session",
  1715. version: "test-version",
  1716. time: { created: 1, updated: 2 },
  1717. });
  1718. await seedStore.createSession({
  1719. id: remoteSessionId,
  1720. projectID: "project_remote_same_path" as ProjectId,
  1721. workspaceID: "remote:ssh:example.test:22:coder:/workspace/cold-resume" as WorkspaceId,
  1722. slug: "remote-same-path-session",
  1723. directory: WORKSPACE_PATH,
  1724. path: WORKSPACE_PATH,
  1725. title: "Remote same path session",
  1726. version: "test-version",
  1727. time: { created: 3, updated: 4 },
  1728. });
  1729. } finally {
  1730. seedStore.close();
  1731. }
  1732. const { server, store } = bootRestartedServer(dbPath, []);
  1733. try {
  1734. await requestResult(server, {
  1735. id: "local-index",
  1736. method: V4_METHODS.conversationSubscribe,
  1737. params: {
  1738. topic: sessionsIndexTopic(WORKSPACE_PATH),
  1739. connectionId: "conn-local-index",
  1740. clientMode: "desktop-continuous",
  1741. // 防御旧/混合版本客户端误传:本地 topic 必须完全忽略远端迁移 allowlist。
  1742. legacyTaskIds: [SESSION_ID],
  1743. },
  1744. });
  1745. const frame = sessionsIndexTopicFrameSchema.parse(
  1746. takeInitialFrameParams(server, "local-index"),
  1747. );
  1748. if (frame.payload.kind !== "snapshot") {
  1749. throw new Error("Expected sessions-index snapshot frame");
  1750. }
  1751. expect(frame.payload.snapshot.workspaceId).toBe(WORKSPACE_PATH);
  1752. expect(frame.payload.snapshot.sessions).toEqual([
  1753. expect.objectContaining({
  1754. sessionId: SESSION_ID,
  1755. workspaceId: WORKSPACE_PATH,
  1756. title: "Local index session",
  1757. }),
  1758. ]);
  1759. expect((await store.getSession(SESSION_ID))?.workspaceID).toBeUndefined();
  1760. } finally {
  1761. store.close();
  1762. }
  1763. });
  1764. it("重启后首次订阅 sessions-index:parented fork 可见且辅助 child 保持隐藏", async () => {
  1765. const dbPath = join(tempRoot, "sessions.db");
  1766. const seedStore = createSqliteSessionStore({ dbPath });
  1767. const rootSessionId = "sess_index_root" as SessionId;
  1768. const forkSessionId = "sess_index_fork" as SessionId;
  1769. const workflowParentSessionId = "sess_index_workflow_parent" as SessionId;
  1770. try {
  1771. const fixtures = [
  1772. { id: rootSessionId, taskType: "interactive" as const },
  1773. {
  1774. id: forkSessionId,
  1775. parentID: rootSessionId,
  1776. taskType: "fork" as const,
  1777. },
  1778. {
  1779. id: workflowParentSessionId,
  1780. taskType: "workflow_parent" as const,
  1781. },
  1782. {
  1783. id: "sess_index_selection_side_chat" as SessionId,
  1784. parentID: rootSessionId,
  1785. taskType: "selection_side_chat" as const,
  1786. },
  1787. {
  1788. id: "sess_index_subagent_child" as SessionId,
  1789. parentID: rootSessionId,
  1790. taskType: "subagent_child" as const,
  1791. },
  1792. {
  1793. id: "sess_index_workflow_child" as SessionId,
  1794. parentID: workflowParentSessionId,
  1795. taskType: "workflow_child" as const,
  1796. },
  1797. {
  1798. id: "sess_index_nested_workflow_child" as SessionId,
  1799. parentID: workflowParentSessionId,
  1800. taskType: "nested_workflow_child" as const,
  1801. },
  1802. ];
  1803. for (const [index, fixture] of fixtures.entries()) {
  1804. await seedStore.createSession({
  1805. ...fixture,
  1806. projectID: `project_index_membership_${index}` as ProjectId,
  1807. slug: `index-membership-${index}`,
  1808. directory: WORKSPACE_PATH,
  1809. path: WORKSPACE_PATH,
  1810. title: `Index membership ${index}`,
  1811. version: "test-version",
  1812. time: { created: index + 1, updated: index + 1 },
  1813. });
  1814. }
  1815. } finally {
  1816. seedStore.close();
  1817. }
  1818. const { server, store } = bootRestartedServer(dbPath, []);
  1819. try {
  1820. // 不先 resume 任一 child,直接模拟 App 重启后的首次列表订阅。
  1821. await requestResult(server, {
  1822. id: "cold-index-membership",
  1823. method: V4_METHODS.conversationSubscribe,
  1824. params: {
  1825. topic: sessionsIndexTopic(WORKSPACE_PATH),
  1826. connectionId: "conn-cold-index-membership",
  1827. clientMode: "desktop-continuous",
  1828. },
  1829. });
  1830. const frame = sessionsIndexTopicFrameSchema.parse(
  1831. takeInitialFrameParams(server, "cold-index-membership"),
  1832. );
  1833. if (frame.payload.kind !== "snapshot") {
  1834. throw new Error("Expected sessions-index snapshot frame");
  1835. }
  1836. expect(frame.payload.snapshot.sessions.map((session) => session.sessionId).sort()).toEqual(
  1837. [rootSessionId, forkSessionId, workflowParentSessionId].sort(),
  1838. );
  1839. expect(
  1840. frame.payload.snapshot.sessions.find((session) => session.sessionId === forkSessionId),
  1841. ).toMatchObject({
  1842. parentSessionId: rootSessionId,
  1843. sessionId: forkSessionId,
  1844. });
  1845. } finally {
  1846. store.close();
  1847. }
  1848. });
  1849. for (const clientMode of ["desktop-continuous", "web-remote-replayable"] as const) {
  1850. for (const lifecycle of ["warm", "grace", "parent-release", "cold"] as const) {
  1851. it(`SAT27/SAT28: ${clientMode} child ${lifecycle} 重开保持隐藏且拒绝用户输入`, async () => {
  1852. const dbPath = join(tempRoot, "sessions.db");
  1853. await seedPersistedSession(dbPath, undefined, "subagent_child");
  1854. const sentInputs: Array<{ text: string }> = [];
  1855. const options: ZCodeAppOptions[] = [];
  1856. const { server, store } = bootRestartedServer(dbPath, sentInputs, undefined, options);
  1857. const { v4Gateway: gateway } = (
  1858. server as unknown as {
  1859. context: { v4Gateway: ConversationV4Gateway };
  1860. }
  1861. ).context;
  1862. async function subscribe(id: string, topic: string) {
  1863. await requestResult(server, {
  1864. id,
  1865. method: V4_METHODS.conversationSubscribe,
  1866. params: { topic, connectionId: id, clientMode },
  1867. });
  1868. return takeInitialFrameParams(server, id);
  1869. }
  1870. try {
  1871. await subscribe("index-before", sessionsIndexTopic(WORKSPACE_PATH));
  1872. if (lifecycle !== "cold") {
  1873. gateway.ingestDetachedLiveSession(
  1874. SESSION_ID,
  1875. makeEvent(SESSION_ID, 1, SessionEventType.SessionCreated, {
  1876. mode: "default",
  1877. contextWindow: 200_000,
  1878. }),
  1879. PARENT_SESSION_ID,
  1880. );
  1881. gateway.ingestDetachedLiveSession(
  1882. SESSION_ID,
  1883. {
  1884. ...makeEvent(SESSION_ID, 2, SessionEventType.TurnStarted, {
  1885. turnNumber: 1,
  1886. input: "child task",
  1887. }),
  1888. turnId: "child-turn",
  1889. },
  1890. PARENT_SESSION_ID,
  1891. );
  1892. gateway.ingestDetachedLiveSession(
  1893. SESSION_ID,
  1894. {
  1895. ...makeEvent(SESSION_ID, 3, SessionEventType.ModelStreaming, {
  1896. kind: "text_delta",
  1897. delta: "child done",
  1898. done: false,
  1899. }),
  1900. turnId: "child-turn",
  1901. },
  1902. PARENT_SESSION_ID,
  1903. );
  1904. gateway.ingestDetachedLiveSession(
  1905. SESSION_ID,
  1906. {
  1907. ...makeEvent(SESSION_ID, 4, SessionEventType.TurnComplete, {
  1908. duration: 1,
  1909. response: "done",
  1910. resultType: "success",
  1911. tokenCount: 1,
  1912. toolCallCount: 0,
  1913. }),
  1914. turnId: "child-turn",
  1915. },
  1916. PARENT_SESSION_ID,
  1917. );
  1918. }
  1919. if (lifecycle === "grace")
  1920. expect(gateway.pruneDetachedChildPublishers(Date.now() + 180_000)).toBe(1);
  1921. if (lifecycle === "parent-release") gateway.deactivateSession(PARENT_SESSION_ID);
  1922. const child = conversationTopicFrameSchema.parse(
  1923. await subscribe("child", conversationTopic(SESSION_ID)),
  1924. );
  1925. expect(child.payload.kind).toBe("snapshot");
  1926. if (child.payload.kind !== "snapshot") throw new Error("expected child snapshot");
  1927. expect(child.payload.snapshot.rows.window.length).toBeGreaterThan(0);
  1928. const index = sessionsIndexTopicFrameSchema.parse(
  1929. await subscribe("index-after", sessionsIndexTopic(WORKSPACE_PATH)),
  1930. );
  1931. if (index.payload.kind !== "snapshot") throw new Error("expected index snapshot");
  1932. expect(index.payload.snapshot.sessions.map((session) => session.sessionId)).not.toContain(
  1933. SESSION_ID,
  1934. );
  1935. const legacy = (await requestResult(server, {
  1936. id: "legacy-list",
  1937. method: zcodeProtocolMethods.sessionList,
  1938. params: { workspace },
  1939. })) as { sessions: Array<{ sessionId: string }> };
  1940. expect(legacy.sessions.map((session) => session.sessionId)).not.toContain(SESSION_ID);
  1941. expect((await store.getSession(SESSION_ID))?.taskType).toBe("subagent_child");
  1942. if (lifecycle !== "warm")
  1943. expect(
  1944. options.find((option) => option.sessionId === SESSION_ID)?.runtimeConfig?.taskType,
  1945. ).toBe("subagent_child");
  1946. for (const type of [
  1947. "sendText",
  1948. "sendGoalCommand",
  1949. "compact",
  1950. "retryTurn",
  1951. "editUserQuery",
  1952. ] as const) {
  1953. const targetRow = child.payload.snapshot.rows.window.findLast(
  1954. (row) => row.kind === (type === "editUserQuery" ? "userInput" : "assistantText"),
  1955. );
  1956. const ack = commandAckSchema.parse(
  1957. await requestResult(server, {
  1958. id: type,
  1959. method: V4_METHODS.command,
  1960. params: {
  1961. commandId: `child-${type}`,
  1962. clientId: "child-test",
  1963. sessionId: SESSION_ID,
  1964. type,
  1965. baseRevision: child.payload.snapshot.revision,
  1966. baseLogEpoch: child.payload.snapshot.logEpoch,
  1967. payload:
  1968. type === "sendText" || type === "sendGoalCommand"
  1969. ? { text: "continue child" }
  1970. : type === "retryTurn" || type === "editUserQuery"
  1971. ? {
  1972. target: {
  1973. rowId: targetRow?.rowId ?? 1,
  1974. entityId: targetRow?.entityId ?? "missing",
  1975. },
  1976. ...(type === "editUserQuery" ? { newText: "edit child" } : {}),
  1977. }
  1978. : {},
  1979. issuedAt: Date.now(),
  1980. },
  1981. }),
  1982. );
  1983. expect(ack).toMatchObject(
  1984. lifecycle === "warm"
  1985. ? { status: "rejected", reasonCode: "proto.sessionNotFound" }
  1986. : { status: "failed", reasonCode: "guard.subagentReadOnly" },
  1987. );
  1988. }
  1989. expect(await store.listSessionInputs({ sessionID: SESSION_ID })).toEqual([]);
  1990. expect(sentInputs).toEqual([]);
  1991. } finally {
  1992. gateway.dispose();
  1993. store.close();
  1994. }
  1995. });
  1996. }
  1997. }
  1998. it("SAT28: legacy session/send 同样拒绝 child 续聊", async () => {
  1999. const dbPath = join(tempRoot, "sessions.db");
  2000. await seedPersistedSession(dbPath, undefined, "subagent_child");
  2001. const { server, store } = bootRestartedServer(dbPath, []);
  2002. try {
  2003. await requestResult(server, {
  2004. id: "open-child",
  2005. method: V4_METHODS.conversationSubscribe,
  2006. params: {
  2007. topic: conversationTopic(SESSION_ID),
  2008. connectionId: "legacy-child",
  2009. clientMode: "desktop-continuous",
  2010. },
  2011. });
  2012. const result = await server.handleMessage({
  2013. id: "legacy-send",
  2014. method: zcodeProtocolMethods.sessionSend,
  2015. params: { sessionId: SESSION_ID, content: "continue child", queryId: "legacy-child-send" },
  2016. });
  2017. expect(result).toMatchObject({ error: { data: { reasonCode: "guard.subagentReadOnly" } } });
  2018. expect(await store.listSessionInputs({ sessionID: SESSION_ID })).toEqual([]);
  2019. } finally {
  2020. store.close();
  2021. }
  2022. });
  2023. it("SAT29: 显式 session/list 按 workspace 查询隐藏身份,不激活 child;普通列表保留 fork", async () => {
  2024. const dbPath = join(tempRoot, "sessions.db");
  2025. await seedPersistedSession(dbPath, undefined, "subagent_child");
  2026. const options: ZCodeAppOptions[] = [];
  2027. const { server, store } = bootRestartedServer(dbPath, [], undefined, options);
  2028. try {
  2029. await store.createSession({
  2030. id: "visible-fork" as SessionId,
  2031. parentID: PARENT_SESSION_ID,
  2032. taskType: "fork",
  2033. projectID: "project" as ProjectId,
  2034. slug: "fork",
  2035. title: "fork",
  2036. directory: WORKSPACE_PATH,
  2037. path: WORKSPACE_PATH,
  2038. version: "test",
  2039. });
  2040. const read = (id: string, params: unknown) =>
  2041. requestResult(server, { id, method: zcodeProtocolMethods.sessionList, params }) as Promise<{
  2042. sessions: Array<{ sessionId: string; sessionKind: string }>;
  2043. }>;
  2044. const normal = await read("normal", { workspace });
  2045. expect(normal.sessions.map((item) => item.sessionId)).toEqual(["visible-fork"]);
  2046. const explicit = await read("explicit", {
  2047. workspace,
  2048. sessionIds: [SESSION_ID, "visible-fork", "missing"],
  2049. });
  2050. expect(explicit.sessions.map((item) => [item.sessionId, item.sessionKind])).toEqual([
  2051. [SESSION_ID, "subagent_child"],
  2052. ["visible-fork", "fork"],
  2053. ]);
  2054. expect(
  2055. (await read("foreign", { workspace: remoteWorkspace, sessionIds: [SESSION_ID] })).sessions,
  2056. ).toEqual([]);
  2057. expect(options).toEqual([]);
  2058. } finally {
  2059. store.close();
  2060. }
  2061. });
  2062. it("重启后冷订阅:transcript 合成重建历史 + 可交互 + sendText 再发一轮成功", async () => {
  2063. const dbPath = join(tempRoot, "sessions.db");
  2064. await seedPersistedSession(dbPath);
  2065. const sentInputs: Array<{ text: string }> = [];
  2066. const { server, store } = bootRestartedServer(dbPath, sentInputs);
  2067. try {
  2068. const subscribed = v4ConversationSubscribeResultSchema.parse(
  2069. await requestResult(server, {
  2070. id: 2,
  2071. method: V4_METHODS.conversationSubscribe,
  2072. params: {
  2073. topic: conversationTopic(SESSION_ID),
  2074. connectionId: "conn-desktop",
  2075. clientMode: "desktop-continuous",
  2076. },
  2077. }),
  2078. );
  2079. expect(subscribed.ack.mode).toBe("snapshot");
  2080. const frame = conversationTopicFrameSchema.parse(takeInitialFrameParams(server, 2));
  2081. if (frame?.payload.kind !== "snapshot") {
  2082. throw new Error("Expected snapshot initial frame");
  2083. }
  2084. const snapshot = frame.payload.snapshot;
  2085. // Bug 根因:旧 cold hydration 固定合成 20 万,导致首帧在后续 live 事件纠正前
  2086. // 已触发满载/压缩。首个原始 snapshot 必须直接使用当前 registry 的 1M。
  2087. expect(snapshot.usage.contextWindow).toMatchObject({
  2088. maxTokens: 1_000_000,
  2089. usedTokens: 2,
  2090. });
  2091. // 历史行齐全(transcript→event 合成路径:重启后 record 的内存事件日志为空)。
  2092. const texts = snapshot.rows.window
  2093. .filter((row) => row.kind === "userInput" || row.kind === "assistantText")
  2094. .map((row) => ("text" in row ? row.text : ""));
  2095. expect(texts).toEqual(["历史问题一", "历史回答一", "历史问题二", "历史回答二"]);
  2096. expect(snapshot.rows.window.find((row) => row.kind === "reasoning")).toMatchObject({
  2097. text: "历史思考二",
  2098. state: "complete",
  2099. });
  2100. expect(snapshot.rows.window.find((row) => row.kind === "toolCall")).toMatchObject({
  2101. output: { text: "历史工具输出" },
  2102. status: "success",
  2103. toolCallId: "call_cold_read",
  2104. toolName: "Read",
  2105. });
  2106. // control 可交互:完成态 + 输入直发(composer 不该禁用)。
  2107. expect(snapshot.control.phase).toBe("completedSuccess");
  2108. expect(snapshot.control.canStop).toBe(false);
  2109. expect(snapshot.inputRouting.mode).toBe("startNow");
  2110. // 再发一轮:sendText 必须 accepted 并落到 runtime sendInput。
  2111. const ack = commandAckSchema.parse(
  2112. await requestResult(server, {
  2113. id: 3,
  2114. method: V4_METHODS.command,
  2115. params: {
  2116. commandId: "cmd-cold-send-1",
  2117. clientId: "client-cold",
  2118. sessionId: SESSION_ID,
  2119. type: "sendText",
  2120. payload: { text: "重启后的新问题" },
  2121. issuedAt: 1_700_000_100_000,
  2122. },
  2123. }),
  2124. );
  2125. expect(ack.status).toBe("accepted");
  2126. await new Promise((resolve) => setTimeout(resolve, 0));
  2127. expect(sentInputs).toEqual([{ text: "重启后的新问题" }]);
  2128. // sessions-index 联动:恢复后的会话进入 live 注册表,列表订阅可见。
  2129. const indexResult = v4SessionsIndexSubscribeResultSchema.parse(
  2130. await requestResult(server, {
  2131. id: 4,
  2132. method: V4_METHODS.conversationSubscribe,
  2133. params: {
  2134. topic: sessionsIndexTopic(WORKSPACE_PATH),
  2135. connectionId: "conn-desktop-index",
  2136. clientMode: "desktop-continuous",
  2137. },
  2138. }),
  2139. );
  2140. const indexFrame = sessionsIndexTopicFrameSchema.parse(takeInitialFrameParams(server, 4));
  2141. if (indexFrame.payload.kind !== "snapshot") {
  2142. throw new Error("Expected sessions-index snapshot frame");
  2143. }
  2144. expect(indexFrame.payload.snapshot.sessions.map((session) => session.sessionId)).toContain(
  2145. SESSION_ID,
  2146. );
  2147. const resumedSummary = indexFrame.payload.snapshot.sessions.find(
  2148. (session) => session.sessionId === SESSION_ID,
  2149. );
  2150. expect(resumedSummary?.parentSessionId).toBe(PARENT_SESSION_ID);
  2151. // 幂等:再次订阅同一会话不再重建 record(无重复恢复副作用),直接出帧。
  2152. const resubscribed = v4ConversationSubscribeResultSchema.parse(
  2153. await requestResult(server, {
  2154. id: 5,
  2155. method: V4_METHODS.conversationSubscribe,
  2156. params: {
  2157. topic: conversationTopic(SESSION_ID),
  2158. connectionId: "conn-desktop-2",
  2159. clientMode: "desktop-continuous",
  2160. },
  2161. }),
  2162. );
  2163. expect(resubscribed.ack.mode).toBe("snapshot");
  2164. expect(
  2165. conversationTopicFrameSchema.parse(takeInitialFrameParams(server, 5)).payload.kind,
  2166. ).toBe("snapshot");
  2167. } finally {
  2168. store.close();
  2169. }
  2170. });
  2171. it("当前本地 attachment 路径优先于旧 session 的规范化路径", async () => {
  2172. const dbPath = join(tempRoot, "sessions.db");
  2173. await seedPersistedSession(dbPath);
  2174. const sentInputs: Array<{ text: string }> = [];
  2175. const createdAppOptions: ZCodeAppOptions[] = [];
  2176. const { server, store } = bootRestartedServer(dbPath, sentInputs, undefined, createdAppOptions);
  2177. const attachmentWorkspace = {
  2178. workspacePath: `${WORKSPACE_PATH}/`,
  2179. workspaceKey: `${WORKSPACE_PATH}/`,
  2180. };
  2181. try {
  2182. await requestResult(server, {
  2183. id: "subscribe-with-trailing-slash",
  2184. method: V4_METHODS.conversationSubscribe,
  2185. params: {
  2186. topic: conversationTopic(SESSION_ID),
  2187. connectionId: "conn-trailing-slash",
  2188. clientMode: "desktop-continuous",
  2189. workspace: attachmentWorkspace,
  2190. },
  2191. });
  2192. takeInitialFrameParams(server, "subscribe-with-trailing-slash");
  2193. const ack = commandAckSchema.parse(
  2194. await requestResult(server, {
  2195. id: "send-after-trailing-slash-resume",
  2196. method: V4_METHODS.command,
  2197. params: {
  2198. commandId: "cmd-trailing-slash-resume",
  2199. clientId: "client-trailing-slash-resume",
  2200. sessionId: SESSION_ID,
  2201. type: "sendText",
  2202. payload: { text: "继续" },
  2203. issuedAt: 1_700_000_100_000,
  2204. },
  2205. }),
  2206. );
  2207. expect(ack.status).toBe("accepted");
  2208. await new Promise((resolve) => setTimeout(resolve, 0));
  2209. expect(sentInputs).toEqual([{ text: "继续" }]);
  2210. expect(createdAppOptions[0]?.runtimeConfig?.workspacePath).toBe(
  2211. attachmentWorkspace.workspacePath,
  2212. );
  2213. } finally {
  2214. store.close();
  2215. }
  2216. });
  2217. it("V4 冷订阅只激活 runtime 并复用一次持久物化,legacy resume 仍返回完整 snapshot", async () => {
  2218. const dbPath = join(tempRoot, "sessions.db");
  2219. await seedPersistedSession(dbPath);
  2220. const probe: ColdFakeAppProbe = { readTodosCalls: 0, resumeCalls: 0 };
  2221. const { server, store } = bootRestartedServer(dbPath, [], probe);
  2222. const messagesSpy = vi.spyOn(store, "messages");
  2223. try {
  2224. await requestResult(server, {
  2225. id: "subscribe-activation-only",
  2226. method: V4_METHODS.conversationSubscribe,
  2227. params: {
  2228. topic: conversationTopic(SESSION_ID),
  2229. connectionId: "conn-activation-only",
  2230. clientMode: "desktop-continuous",
  2231. },
  2232. });
  2233. const frame = conversationTopicFrameSchema.parse(
  2234. takeInitialFrameParams(server, "subscribe-activation-only"),
  2235. );
  2236. if (frame.payload.kind !== "snapshot") throw new Error("Expected snapshot frame");
  2237. // Bug 根因:旧 V4 resume 钩子会先构建一份无人消费的 legacy snapshot,
  2238. // usage seed 随后又构建第二份。readTodos 只属于 full snapshot,可作为稳定 seam
  2239. // 证明 V4 现在只做 activation + 自己的 durable hydration。
  2240. expect(probe).toEqual({ readTodosCalls: 0, resumeCalls: 1 });
  2241. // 性能根因:同一份父会话 messages 过去又被 hydration、subagent seed、usage seed
  2242. // 各读一次。正常冷订阅必须只在 activation 起点物化一次。
  2243. expect(
  2244. messagesSpy.mock.calls.filter(([input]) => input.sessionID === SESSION_ID),
  2245. ).toHaveLength(1);
  2246. expect(frame.payload.snapshot.usage.contextWindow).toMatchObject({
  2247. // 当前分支的模型 registry 是 context-window 权威;窄读只替换 usage 取数,
  2248. // 不能把冷 runtime projection 的旧 128k 分母重新覆盖到 V4 首帧。
  2249. maxTokens: 1_000_000,
  2250. usedTokens: 2,
  2251. });
  2252. const legacy = zcodeSessionStateSnapshotSchema.parse(
  2253. await requestResult(server, {
  2254. id: "legacy-resume-after-v4",
  2255. method: zcodeProtocolMethods.sessionResume,
  2256. params: { sessionId: SESSION_ID, workspace },
  2257. }),
  2258. );
  2259. expect(probe).toEqual({ readTodosCalls: 1, resumeCalls: 1 });
  2260. expect(legacy.runtime.contextUsage).toMatchObject({
  2261. size: 1_000_000,
  2262. used: 2,
  2263. });
  2264. expect(frame.payload.snapshot.usage.contextWindow?.cache).toEqual(
  2265. legacy.runtime.contextUsage?.cache,
  2266. );
  2267. } finally {
  2268. store.close();
  2269. }
  2270. });
  2271. it("fresh server 的 legacy session/resume 不向 runtime 注入 V4 持久物化", async () => {
  2272. const dbPath = join(tempRoot, "sessions.db");
  2273. await seedPersistedSession(dbPath);
  2274. const probe: ColdFakeAppProbe = {
  2275. readTodosCalls: 0,
  2276. resumeCalls: 0,
  2277. resumePersistedMessagesProvided: [],
  2278. };
  2279. const { server, store } = bootRestartedServer(dbPath, [], probe);
  2280. try {
  2281. const legacy = zcodeSessionStateSnapshotSchema.parse(
  2282. await requestResult(server, {
  2283. id: "fresh-legacy-resume",
  2284. method: zcodeProtocolMethods.sessionResume,
  2285. params: { sessionId: SESSION_ID, workspace },
  2286. }),
  2287. );
  2288. expect(probe).toMatchObject({
  2289. readTodosCalls: 1,
  2290. resumeCalls: 1,
  2291. resumePersistedMessagesProvided: [false],
  2292. });
  2293. expect(legacy.session.sessionId).toBe(SESSION_ID);
  2294. expect(legacy.runtime.contextUsage).toMatchObject({
  2295. size: 1_000_000,
  2296. used: 2,
  2297. });
  2298. } finally {
  2299. store.close();
  2300. }
  2301. });
  2302. it("runtime 修补中断 compact 后只刷新一次持久物化", async () => {
  2303. const dbPath = join(tempRoot, "sessions.db");
  2304. await seedPersistedSession(dbPath);
  2305. const probe: ColdFakeAppProbe = {
  2306. persistedMessagesReloadRequired: true,
  2307. readTodosCalls: 0,
  2308. resumeCalls: 0,
  2309. };
  2310. const { server, store } = bootRestartedServer(dbPath, [], probe);
  2311. const messagesSpy = vi.spyOn(store, "messages");
  2312. try {
  2313. await requestResult(server, {
  2314. id: "subscribe-compact-refresh",
  2315. method: V4_METHODS.conversationSubscribe,
  2316. params: {
  2317. topic: conversationTopic(SESSION_ID),
  2318. connectionId: "conn-compact-refresh",
  2319. clientMode: "desktop-continuous",
  2320. },
  2321. });
  2322. expect(
  2323. messagesSpy.mock.calls.filter(([input]) => input.sessionID === SESSION_ID),
  2324. ).toHaveLength(2);
  2325. expect(probe.resumeCalls).toBe(1);
  2326. } finally {
  2327. store.close();
  2328. }
  2329. });
  2330. it("compact 是最后操作:重启后的首帧保持压缩后 usage", async () => {
  2331. const dbPath = join(tempRoot, "sessions.db");
  2332. await seedPersistedCompactedSession(dbPath);
  2333. const { server, store } = bootRestartedServer(dbPath, []);
  2334. try {
  2335. await requestResult(server, {
  2336. id: "subscribe-compact-desktop",
  2337. method: V4_METHODS.conversationSubscribe,
  2338. params: {
  2339. topic: conversationTopic(SESSION_ID),
  2340. connectionId: "conn-compact-desktop",
  2341. clientMode: "desktop-continuous",
  2342. },
  2343. });
  2344. const desktopFrame = conversationTopicFrameSchema.parse(
  2345. takeInitialFrameParams(server, "subscribe-compact-desktop"),
  2346. );
  2347. if (desktopFrame.payload.kind !== "snapshot") {
  2348. throw new Error("Expected desktop snapshot frame");
  2349. }
  2350. expect(desktopFrame.payload.snapshot.usage.contextWindow).toMatchObject({
  2351. maxTokens: 1_000_000,
  2352. usedTokens: 1,
  2353. });
  2354. expect(desktopFrame.payload.snapshot.usage.contextWindow?.cache).toBeUndefined();
  2355. } finally {
  2356. store.close();
  2357. }
  2358. });
  2359. it("旧 assistant boundary 缺少压缩后 token 时保持 assistant usage fallback", async () => {
  2360. const compactBoundary: CompactBoundaryPayload = {
  2361. boundaryId: "boundary_cold_legacy",
  2362. trigger: CompactTrigger.Manual,
  2363. preCompactTokenCount: 9,
  2364. summarizedMessageCount: 2,
  2365. summaryMessageIds: [],
  2366. traceId: "trace_cold_legacy_boundary" as TraceId,
  2367. };
  2368. const legacyMessage = {
  2369. info: {
  2370. role: "assistant",
  2371. tokens: { input: 7, output: 2, reasoning: 0, cache: { read: 0, write: 0 } },
  2372. } as MessageWithParts["info"],
  2373. parts: [
  2374. {
  2375. type: "compaction",
  2376. auto: false,
  2377. compactBoundary,
  2378. } as MessagePart,
  2379. ],
  2380. };
  2381. const projection = await createColdFakeApp(undefined, []).runtime.getProjection();
  2382. expect(resolveSessionContextUsage({ messages: [legacyMessage], projection })).toMatchObject({
  2383. size: 128_000,
  2384. used: 9,
  2385. });
  2386. });
  2387. it("重启后冷订阅:优先从 Agent durable selection 恢复 task-local thought", async () => {
  2388. const dbPath = join(tempRoot, "sessions.db");
  2389. await seedPersistedSession(dbPath);
  2390. const seedStore = createSqliteSessionStore({ dbPath });
  2391. try {
  2392. await seedStore.saveSessionEntry({
  2393. id: `${SESSION_ID}:runtime-model-selection`,
  2394. sessionID: SESSION_ID,
  2395. type: SESSION_ENTRY_MODEL_SELECTION,
  2396. time: { created: 5, updated: 5 },
  2397. data: { modelId: "glm-4.6", providerId: "glm", thoughtLevel: "deep" },
  2398. });
  2399. } finally {
  2400. seedStore.close();
  2401. }
  2402. const { server, close } = bootRealRestartedServer(dbPath);
  2403. try {
  2404. await requestResult(server, {
  2405. id: "subscribe-thought",
  2406. method: V4_METHODS.conversationSubscribe,
  2407. params: {
  2408. topic: conversationTopic(SESSION_ID),
  2409. connectionId: "conn-thought",
  2410. clientMode: "desktop-continuous",
  2411. // 即便 host 的 legacy hint 迟到/过期,Agent 自己的 durable selection 仍优先。
  2412. resumeThoughtLevel: "medium",
  2413. },
  2414. });
  2415. const frame = conversationTopicFrameSchema.parse(
  2416. takeInitialFrameParams(server, "subscribe-thought"),
  2417. );
  2418. if (frame.payload.kind !== "snapshot") throw new Error("Expected snapshot frame");
  2419. expect(frame.payload.snapshot.config).toMatchObject({
  2420. model: "glm-4.6",
  2421. provider: "glm",
  2422. thought: "deep",
  2423. thoughtLevels: ["medium", "deep"],
  2424. });
  2425. } finally {
  2426. await close();
  2427. }
  2428. });
  2429. it("重启后冷订阅:旧 fork 消息缺档位时不借用相邻消息的档位", async () => {
  2430. const dbPath = join(tempRoot, "sessions.db");
  2431. const legacyForkSessionId = "sess_legacy_fork_thought" as SessionId;
  2432. const parentSessionId = "sess_legacy_fork_parent";
  2433. const targetMessageId = "msg_legacy_fork_target";
  2434. const hiddenMessageId = "msg_legacy_fork_hidden" as MessageId;
  2435. const noticeMessageId = "msg_legacy_fork_notice" as MessageId;
  2436. const forkOrigin = { parentSessionId, targetMessageId };
  2437. const seedStore = createSqliteSessionStore({ dbPath });
  2438. try {
  2439. await seedStore.createSession({
  2440. id: legacyForkSessionId,
  2441. parentID: parentSessionId as SessionId,
  2442. projectID: "project_legacy_fork_thought" as ProjectId,
  2443. slug: "legacy-fork-thought",
  2444. directory: WORKSPACE_PATH,
  2445. path: WORKSPACE_PATH,
  2446. title: "Legacy fork thought",
  2447. version: "test-version",
  2448. time: { created: 1, updated: 4 },
  2449. });
  2450. await seedStore.saveMessage({
  2451. id: hiddenMessageId,
  2452. sessionID: legacyForkSessionId,
  2453. role: "user",
  2454. time: { created: 1 },
  2455. agent: "zcode-agent",
  2456. model: {
  2457. providerID: "glm" as ModelProviderId,
  2458. modelID: "glm-4-air" as ModelId,
  2459. variant: "deep",
  2460. },
  2461. metadata: { forkOrigin },
  2462. semantics: {
  2463. origin: "system",
  2464. kind: "fork_notice",
  2465. uiVisibility: "hidden",
  2466. providerVisibility: "hidden",
  2467. transcriptVisibility: "hidden",
  2468. },
  2469. source: "fork",
  2470. synthetic: true,
  2471. visibility: "model-only",
  2472. tools: {},
  2473. });
  2474. await seedStore.savePart({
  2475. id: `${hiddenMessageId}_text` as MessagePart["id"],
  2476. sessionID: legacyForkSessionId,
  2477. messageID: hiddenMessageId,
  2478. type: "text",
  2479. text: "fork notice",
  2480. synthetic: true,
  2481. time: { start: 1, end: 1 },
  2482. });
  2483. await seedStore.saveMessage({
  2484. id: noticeMessageId,
  2485. sessionID: legacyForkSessionId,
  2486. role: "assistant",
  2487. time: { created: 2, completed: 2 },
  2488. parentID: hiddenMessageId,
  2489. providerID: "glm" as ModelProviderId,
  2490. modelID: "glm-4-air" as ModelId,
  2491. mode: "build",
  2492. agent: "zcode-agent",
  2493. path: { cwd: WORKSPACE_PATH, root: WORKSPACE_PATH },
  2494. cost: 0,
  2495. tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
  2496. metadata: { forkOrigin },
  2497. semantics: {
  2498. origin: "system",
  2499. kind: "timeline_event",
  2500. uiVisibility: "visible",
  2501. providerVisibility: "hidden",
  2502. transcriptVisibility: "visible",
  2503. },
  2504. });
  2505. await seedStore.savePart({
  2506. id: `${noticeMessageId}_timeline` as MessagePart["id"],
  2507. sessionID: legacyForkSessionId,
  2508. messageID: noticeMessageId,
  2509. type: "timeline",
  2510. timelineType: "session_fork",
  2511. display: "separator",
  2512. status: "completed",
  2513. parentSessionId: parentSessionId as SessionId,
  2514. targetMessageId: targetMessageId as MessageId,
  2515. time: { start: 2, end: 2 },
  2516. });
  2517. } finally {
  2518. seedStore.close();
  2519. }
  2520. const { server, close } = bootRealRestartedServer(dbPath);
  2521. try {
  2522. await requestResult(server, {
  2523. id: "subscribe-legacy-fork-thought",
  2524. method: V4_METHODS.conversationSubscribe,
  2525. params: {
  2526. topic: conversationTopic(legacyForkSessionId),
  2527. connectionId: "conn-legacy-fork-thought",
  2528. clientMode: "desktop-continuous",
  2529. },
  2530. });
  2531. const frame = conversationTopicFrameSchema.parse(
  2532. takeInitialFrameParams(server, "subscribe-legacy-fork-thought"),
  2533. );
  2534. if (frame.payload.kind !== "snapshot") throw new Error("Expected snapshot frame");
  2535. expect(frame.payload.snapshot.config).toMatchObject({
  2536. model: "glm-4-air",
  2537. provider: "glm",
  2538. thought: "",
  2539. });
  2540. } finally {
  2541. await close();
  2542. }
  2543. });
  2544. it("冷恢复期间内部 hook 事件不刷新 sessions-index 活动时间", async () => {
  2545. const dbPath = join(tempRoot, "sessions.db");
  2546. await seedPersistedSession(dbPath);
  2547. const seedStore = createSqliteSessionStore({ dbPath });
  2548. const persistedActivityAt = (await seedStore.getSession(SESSION_ID))?.time.updated;
  2549. seedStore.close();
  2550. expect(persistedActivityAt).toBeTypeOf("number");
  2551. const resumeNow = persistedActivityAt! + 60_000;
  2552. const probe: ColdFakeAppProbe = {
  2553. readTodosCalls: 0,
  2554. resumeCalls: 0,
  2555. resumeEventTypes: [
  2556. SessionEventType.HookRunStarted,
  2557. SessionEventType.HookRunProgress,
  2558. SessionEventType.HookRunCompleted,
  2559. SessionEventType.HookRunFailed,
  2560. SessionEventType.HookRunBlocked,
  2561. SessionEventType.WorkspaceHookAdmissionUpdated,
  2562. ],
  2563. };
  2564. const { server, store } = bootRestartedServer(dbPath, [], probe);
  2565. const nowSpy = vi.spyOn(Date, "now").mockReturnValue(resumeNow);
  2566. try {
  2567. await requestResult(server, {
  2568. id: "subscribe-resume-activity",
  2569. method: V4_METHODS.conversationSubscribe,
  2570. params: {
  2571. topic: conversationTopic(SESSION_ID),
  2572. connectionId: "conn-resume-activity",
  2573. clientMode: "desktop-continuous",
  2574. },
  2575. });
  2576. takeInitialFrameParams(server, "subscribe-resume-activity");
  2577. await requestResult(server, {
  2578. id: "index-resume-activity",
  2579. method: V4_METHODS.conversationSubscribe,
  2580. params: {
  2581. topic: sessionsIndexTopic(WORKSPACE_PATH),
  2582. connectionId: "conn-index-resume-activity",
  2583. clientMode: "desktop-continuous",
  2584. },
  2585. });
  2586. const frame = sessionsIndexTopicFrameSchema.parse(
  2587. takeInitialFrameParams(server, "index-resume-activity"),
  2588. );
  2589. if (frame.payload.kind !== "snapshot") {
  2590. throw new Error("Expected sessions-index snapshot frame");
  2591. }
  2592. expect(
  2593. frame.payload.snapshot.sessions.find((session) => session.sessionId === SESSION_ID)
  2594. ?.lastActivityAt,
  2595. ).toBe(persistedActivityAt);
  2596. } finally {
  2597. nowSpy.mockRestore();
  2598. store.close();
  2599. }
  2600. });
  2601. it("重启后冷订阅:旧 transcript 无档位时留空,不读取 task-index 提示", async () => {
  2602. const dbPath = join(tempRoot, "sessions.db");
  2603. await seedPersistedSession(dbPath);
  2604. const { server, close } = bootRealRestartedServer(dbPath);
  2605. try {
  2606. await requestResult(server, {
  2607. id: "subscribe-legacy-thought",
  2608. method: V4_METHODS.conversationSubscribe,
  2609. params: {
  2610. topic: conversationTopic(SESSION_ID),
  2611. connectionId: "conn-legacy-thought",
  2612. clientMode: "desktop-continuous",
  2613. // 旧消息没有档位,桌面提示不能替用户补选。
  2614. resumeThoughtLevel: "deep",
  2615. },
  2616. });
  2617. const frame = conversationTopicFrameSchema.parse(
  2618. takeInitialFrameParams(server, "subscribe-legacy-thought"),
  2619. );
  2620. if (frame.payload.kind !== "snapshot") throw new Error("Expected snapshot frame");
  2621. expect(frame.payload.snapshot.config).toMatchObject({
  2622. model: "glm-4-air",
  2623. provider: "glm",
  2624. thought: "",
  2625. thoughtLevels: ["medium", "deep"],
  2626. });
  2627. } finally {
  2628. await close();
  2629. }
  2630. });
  2631. it("远端 identity 历史会话冷恢复后沿用持久化 identity,sendText 成功", async () => {
  2632. const dbPath = join(tempRoot, "sessions.db");
  2633. await seedPersistedSession(dbPath, REMOTE_WORKSPACE_IDENTITY);
  2634. const sentInputs: Array<{ text: string }> = [];
  2635. const { server, store } = bootRestartedServer(dbPath, sentInputs);
  2636. try {
  2637. await requestResult(server, {
  2638. id: 2,
  2639. method: V4_METHODS.conversationSubscribe,
  2640. params: {
  2641. topic: conversationTopic(SESSION_ID),
  2642. connectionId: "conn-remote-desktop",
  2643. clientMode: "desktop-continuous",
  2644. },
  2645. });
  2646. const ack = commandAckSchema.parse(
  2647. await requestResult(server, {
  2648. id: 3,
  2649. method: V4_METHODS.command,
  2650. params: {
  2651. commandId: "cmd-remote-cold-send",
  2652. clientId: "client-remote-cold",
  2653. sessionId: SESSION_ID,
  2654. type: "sendText",
  2655. payload: { text: "远端重连后的新问题" },
  2656. issuedAt: 1_700_000_100_000,
  2657. },
  2658. }),
  2659. );
  2660. expect(ack.status).toBe("accepted");
  2661. await new Promise((resolve) => setTimeout(resolve, 0));
  2662. expect(sentInputs).toEqual([{ text: "远端重连后的新问题" }]);
  2663. } finally {
  2664. store.close();
  2665. }
  2666. });
  2667. it("进程 Registry 已就绪时冷恢复不等待旧 workspace registry", async () => {
  2668. const dbPath = join(tempRoot, "sessions.db");
  2669. await seedPersistedSession(dbPath);
  2670. const sentInputs: Array<{ text: string }> = [];
  2671. const { server, store } = bootRestartedServer(dbPath, sentInputs);
  2672. try {
  2673. await requestResult(server, {
  2674. id: 1,
  2675. method: V4_METHODS.conversationSubscribe,
  2676. params: {
  2677. topic: conversationTopic(SESSION_ID),
  2678. connectionId: "conn-process-registry",
  2679. clientMode: "desktop-continuous",
  2680. },
  2681. });
  2682. const ack = commandAckSchema.parse(
  2683. await requestResult(server, {
  2684. id: 2,
  2685. method: V4_METHODS.command,
  2686. params: {
  2687. commandId: "cmd-process-registry-cold-send",
  2688. clientId: "client-process-registry",
  2689. sessionId: SESSION_ID,
  2690. type: "sendText",
  2691. payload: { text: "使用当前 Environment Registry" },
  2692. issuedAt: 1_700_000_100_000,
  2693. },
  2694. }),
  2695. );
  2696. expect(ack.status).toBe("accepted");
  2697. await new Promise((resolve) => setTimeout(resolve, 0));
  2698. expect(sentInputs).toEqual([{ text: "使用当前 Environment Registry" }]);
  2699. } finally {
  2700. store.close();
  2701. }
  2702. });
  2703. it("store 无此会话:订阅报 fault.subscribe.sessionNotFound(binder notFound 分型)", async () => {
  2704. const dbPath = join(tempRoot, "sessions.db");
  2705. await seedPersistedSession(dbPath);
  2706. const sentInputs: Array<{ text: string }> = [];
  2707. const { server, store } = bootRestartedServer(dbPath, sentInputs);
  2708. try {
  2709. const response = await server.handleMessage({
  2710. id: 1,
  2711. method: V4_METHODS.conversationSubscribe,
  2712. params: {
  2713. topic: conversationTopic("sess_never_existed"),
  2714. connectionId: "conn-desktop",
  2715. clientMode: "desktop-continuous",
  2716. },
  2717. } as ZCodeProtocolMessage);
  2718. if (!response || !("error" in response)) {
  2719. throw new Error(`Expected protocol error response: ${JSON.stringify(response)}`);
  2720. }
  2721. expect(response.error.message).toContain("fault.subscribe.sessionNotFound");
  2722. } finally {
  2723. store.close();
  2724. }
  2725. });
  2726. });