v4-cold-resume.test.ts 116 KB

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