v4-cold-resume.test.ts 132 KB

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