v4-cold-resume.test.ts 140 KB

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