v4-cold-resume.test.ts 145 KB

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