v4-cold-resume.test.ts 143 KB

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