v4-cold-resume.test.ts 113 KB

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