zcodeTaskIndexSyncer.test.ts 107 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206
  1. import { mkdtempSync, rmSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { Emitter, type Event } from "@zcode/rpc";
  5. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  6. import type {
  7. SessionsIndexTopicWireFrame,
  8. IZCodeAgentService,
  9. ZCodeAgentRuntimeLifecycleEvent,
  10. ZCodeAgentSessionTarget,
  11. } from "../src/zcode-agent/zcodeAgent.js";
  12. import { TaskIndexRepo } from "../src/session/taskIndexRepo.js";
  13. import { setDataBaseDir } from "../src/paths.js";
  14. import { createZCodeTaskIndexSyncer } from "../src/zcode-agent/zcodeTaskIndexSyncer.js";
  15. import type {
  16. ModelSelection,
  17. ZCodeSessionStateSnapshot,
  18. ZCodeTaskMeta,
  19. ZCodeWorkspaceEvent,
  20. } from "@zcode/shared";
  21. import { elideSessionSnapshotForIndex, ZCODE_AGENT_PROVIDER_NOT_READY_CODE } from "@zcode/shared";
  22. import type {
  23. SessionSummary,
  24. ErrorAttribution,
  25. SessionsIndexTopicFrame,
  26. WorkspaceConfigState,
  27. WorkspaceConfigTopicFrame,
  28. WorkspaceConfigTopicWireFrame,
  29. } from "@zcode/shared/zcode-protocol-v4";
  30. import {
  31. encodeTopicWireFrames,
  32. PROTOCOL_V4_LIMITS,
  33. utf8JsonByteLength,
  34. } from "@zcode/shared/zcode-protocol-v4";
  35. let tempDir: string;
  36. // 跟踪当前测试的 env,用于 afterEach 清理
  37. let currentEnv: TestEnv | undefined;
  38. beforeEach(() => {
  39. tempDir = mkdtempSync(join(tmpdir(), "zcode-task-index-syncer-"));
  40. setDataBaseDir(tempDir);
  41. });
  42. afterEach(async () => {
  43. // 先关闭 repo 确保 SQLite 连接释放,避免 Windows EPERM
  44. currentEnv?.repo?.close();
  45. currentEnv = undefined;
  46. setDataBaseDir(null);
  47. // Windows 需要等待一下让文件句柄释放
  48. await new Promise((resolve) => setTimeout(resolve, 50));
  49. try {
  50. rmSync(tempDir, { recursive: true, force: true });
  51. } catch {
  52. // Windows 有时仍会有权限问题,忽略即可
  53. }
  54. });
  55. interface TestEnv {
  56. agent: IZCodeAgentService;
  57. indexEmitter: TestTopicEmitter<SessionsIndexTopicFrame, SessionsIndexTopicWireFrame>;
  58. configEmitter: TestTopicEmitter<WorkspaceConfigTopicFrame, WorkspaceConfigTopicWireFrame>;
  59. lifecycleEmitter: Emitter<ZCodeAgentRuntimeLifecycleEvent>;
  60. repo: TaskIndexRepo;
  61. }
  62. interface TestTopicEmitter<F extends { topic: string; subscriptionId: string }, W> {
  63. event: Event<W>;
  64. fire(frame: F, deliveryKind?: "initial" | "online" | "recovery"): void;
  65. fireWire(wire: W): void;
  66. dispose(): void;
  67. }
  68. function createTestTopicEmitter<
  69. F extends { topic: string; subscriptionId: string },
  70. W,
  71. >(): TestTopicEmitter<F, W> {
  72. const emitter = new Emitter<W>();
  73. let serial = 1;
  74. return {
  75. event: emitter.event,
  76. fire(frame, deliveryKind = "online") {
  77. const logicalFrameOrdinal = serial++;
  78. emitter.fire({
  79. wireVersion: 3,
  80. kind: "complete",
  81. logicalFrameId: `test-logical-${logicalFrameOrdinal}`,
  82. logicalFrameOrdinal,
  83. deliveryKind,
  84. topic: frame.topic,
  85. subscriptionId: frame.subscriptionId,
  86. frame,
  87. } as W);
  88. },
  89. fireWire: (wire) => emitter.fire(wire),
  90. dispose: () => emitter.dispose(),
  91. };
  92. }
  93. const INDEX_SUBSCRIPTION_ID = "six-test-1";
  94. const CONFIG_SUBSCRIPTION_ID = "wcs-test-1";
  95. type IndexSubscribeResult = Awaited<ReturnType<IZCodeAgentService["subscribeSessionsIndexV4"]>>;
  96. type IndexResyncResult = Awaited<ReturnType<IZCodeAgentService["resyncSessionsIndexV4"]>>;
  97. type ConfigResyncResult = Awaited<ReturnType<IZCodeAgentService["resyncWorkspaceConfigV4"]>>;
  98. function summaryOf(
  99. sessionId: string,
  100. phase: SessionSummary["phase"],
  101. overrides: Partial<SessionSummary> = {},
  102. ): SessionSummary {
  103. return {
  104. sessionId,
  105. workspaceId: "/repo",
  106. title: "",
  107. phase,
  108. sessionEnded: phase === "completedSuccess" || phase === "completedInterrupted",
  109. hasBackgroundWork: false,
  110. lastActivityAt: 100,
  111. createdAt: 1,
  112. ...overrides,
  113. };
  114. }
  115. function indexSnapshotFrame(
  116. sessions: SessionSummary[],
  117. seq = 1,
  118. workspaceKey = "/repo",
  119. ): SessionsIndexTopicFrame {
  120. return {
  121. topic: `sessions-index/${workspaceKey}`,
  122. subscriptionId: INDEX_SUBSCRIPTION_ID,
  123. fromSeq: 0,
  124. toSeq: seq,
  125. sentAt: 1,
  126. payload: {
  127. kind: "snapshot",
  128. snapshot: {
  129. protocolVersion: 1,
  130. workspaceId: workspaceKey,
  131. logEpoch: "epoch-test",
  132. sessions,
  133. },
  134. },
  135. };
  136. }
  137. function indexUpsertFrame(session: SessionSummary, seq = 2): SessionsIndexTopicFrame {
  138. return {
  139. topic: "sessions-index//repo",
  140. subscriptionId: INDEX_SUBSCRIPTION_ID,
  141. fromSeq: seq - 1,
  142. toSeq: seq,
  143. sentAt: 2,
  144. payload: { kind: "deltas", deltas: [{ op: "session.upserted", session }] },
  145. };
  146. }
  147. function configFrame(config: WorkspaceConfigState, seq = 1): WorkspaceConfigTopicFrame {
  148. return {
  149. topic: "workspace-config//repo",
  150. subscriptionId: CONFIG_SUBSCRIPTION_ID,
  151. fromSeq: 0,
  152. toSeq: seq,
  153. sentAt: 3,
  154. payload: {
  155. kind: "snapshot",
  156. snapshot: {
  157. protocolVersion: 1,
  158. workspaceId: "/repo",
  159. logEpoch: "epoch-cfg",
  160. config,
  161. },
  162. },
  163. };
  164. }
  165. function configDeltaFrame(config: WorkspaceConfigState, seq: number): WorkspaceConfigTopicFrame {
  166. return {
  167. topic: "workspace-config//repo",
  168. subscriptionId: CONFIG_SUBSCRIPTION_ID,
  169. fromSeq: seq - 1,
  170. toSeq: seq,
  171. sentAt: 4,
  172. payload: {
  173. kind: "deltas",
  174. deltas: [{ op: "config.updated", config }],
  175. },
  176. };
  177. }
  178. function setupEnv(
  179. options: {
  180. initialSessions?: SessionSummary[];
  181. workspaceKey?: string;
  182. runtimeLifecycle?: boolean;
  183. } = {},
  184. ): TestEnv {
  185. const indexEmitter = createTestTopicEmitter<
  186. SessionsIndexTopicFrame,
  187. SessionsIndexTopicWireFrame
  188. >();
  189. const configEmitter = createTestTopicEmitter<
  190. WorkspaceConfigTopicFrame,
  191. WorkspaceConfigTopicWireFrame
  192. >();
  193. const lifecycleEmitter = new Emitter<ZCodeAgentRuntimeLifecycleEvent>();
  194. const agent: IZCodeAgentService = {
  195. subscribeSessionsIndexV4: vi.fn(async () => {
  196. const ack = {
  197. subscriptionId: INDEX_SUBSCRIPTION_ID,
  198. mode: "snapshot" as const,
  199. logEpoch: "epoch-test",
  200. };
  201. // 04A 真链路:response 与 initial 在同一 read;Promise continuation 尚未运行时
  202. // notification 已同步 fire,syncer 必须先 staging,ACK 后再按 subId 释放。
  203. indexEmitter.fire(
  204. indexSnapshotFrame(options.initialSessions ?? [], 1, options.workspaceKey),
  205. "initial",
  206. );
  207. return { ack };
  208. }),
  209. unsubscribeSessionsIndexV4: vi.fn(async () => {}),
  210. resyncSessionsIndexV4: vi.fn(async (params) => ({
  211. ack: {
  212. subscriptionId: params.subscriptionId,
  213. mode: params.forceSnapshot ? ("snapshot" as const) : ("resume" as const),
  214. logEpoch: "epoch-test",
  215. },
  216. })),
  217. onDynamicSessionsIndexFrame: vi.fn(() => indexEmitter.event),
  218. subscribeWorkspaceConfigV4: vi.fn(async () => ({
  219. ack: {
  220. subscriptionId: CONFIG_SUBSCRIPTION_ID,
  221. mode: "snapshot" as const,
  222. logEpoch: "epoch-cfg",
  223. },
  224. })),
  225. unsubscribeWorkspaceConfigV4: vi.fn(async () => {}),
  226. resyncWorkspaceConfigV4: vi.fn(async (params) => ({
  227. ack: {
  228. subscriptionId: params.subscriptionId,
  229. mode: params.forceSnapshot ? ("snapshot" as const) : ("resume" as const),
  230. logEpoch: "epoch-cfg",
  231. },
  232. })),
  233. onDynamicWorkspaceConfigFrame: vi.fn(() => configEmitter.event),
  234. resumeSession: vi.fn(async (target: ZCodeAgentSessionTarget) =>
  235. snapshotWith(target.sessionId, target.workspacePath),
  236. ),
  237. listSessions: vi.fn(async () => []),
  238. readSession: vi.fn(async (target: ZCodeAgentSessionTarget) =>
  239. snapshotWith(target.sessionId, target.workspacePath),
  240. ),
  241. hasActiveCuaOperationTurn: vi.fn(() => false),
  242. ...(options.runtimeLifecycle ? { onAgentRuntimeLifecycle: lifecycleEmitter.event } : {}),
  243. } as unknown as IZCodeAgentService;
  244. const env = {
  245. agent,
  246. indexEmitter,
  247. configEmitter,
  248. lifecycleEmitter,
  249. repo: new TaskIndexRepo(),
  250. };
  251. currentEnv = env;
  252. return env;
  253. }
  254. /** 等待 workspace v4 订阅建立完成(subscribe promise resolve + 初始帧静默入基线)。 */
  255. async function subscribed(env: TestEnv): Promise<void> {
  256. await vi.waitFor(() => {
  257. expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalled();
  258. });
  259. // establishWorkspaceSubscriptions 里 Promise.all 之后才写 subscriptionId;多让一拍。
  260. await new Promise((resolve) => setImmediate(resolve));
  261. }
  262. const seedTarget: ZCodeAgentSessionTarget = {
  263. workspacePath: "/repo",
  264. sessionId: "sess_complete",
  265. };
  266. async function seedRunningTask(repo: TaskIndexRepo): Promise<ZCodeTaskMeta> {
  267. return repo.syncTaskMeta({
  268. meta: {
  269. taskId: seedTarget.sessionId,
  270. traceId: "trace_seed",
  271. title: "Pending task",
  272. workspacePath: seedTarget.workspacePath,
  273. createdAt: 1,
  274. updatedAt: 2,
  275. mode: "build",
  276. status: "running",
  277. },
  278. });
  279. }
  280. function snapshotWith(
  281. sessionId: string,
  282. workspacePath: string,
  283. overrides: {
  284. title?: string;
  285. createdAt?: number;
  286. updatedAt?: number;
  287. userMessageText?: string;
  288. assistantMessageText?: string;
  289. assistantCompletedAt?: number;
  290. sessionStatus?: ZCodeSessionStateSnapshot["session"]["status"];
  291. settingsModel?: ModelSelection;
  292. messageModel?: ModelSelection;
  293. thoughtLevel?: string;
  294. target?: ZCodeSessionStateSnapshot["projection"]["target"];
  295. lastError?: { type: string; message: string; attribution?: ErrorAttribution };
  296. } = {},
  297. ): ZCodeSessionStateSnapshot {
  298. const settingsModel = overrides.settingsModel ?? {
  299. providerId: "anthropic",
  300. modelId: "haiku-4.5",
  301. };
  302. const messageModel = overrides.messageModel ?? settingsModel;
  303. const messages = [];
  304. if (overrides.userMessageText !== undefined) {
  305. messages.push({
  306. info: {
  307. messageId: "msg_u1",
  308. role: "user" as const,
  309. time: { created: overrides.updatedAt ?? 1, completed: overrides.updatedAt ?? 1 },
  310. model: messageModel,
  311. },
  312. parts: [
  313. {
  314. partId: "p1",
  315. type: "text" as const,
  316. text: overrides.userMessageText,
  317. },
  318. ],
  319. });
  320. }
  321. if (overrides.assistantMessageText !== undefined) {
  322. messages.push({
  323. info: {
  324. messageId: "msg_a1",
  325. sessionId,
  326. parentMessageId: "msg_u1",
  327. role: "assistant" as const,
  328. time: {
  329. created: overrides.updatedAt ?? 1,
  330. ...(typeof overrides.assistantCompletedAt === "number"
  331. ? { completed: overrides.assistantCompletedAt }
  332. : {}),
  333. },
  334. agent: "zcode",
  335. model: messageModel,
  336. path: { cwd: workspacePath, root: workspacePath },
  337. },
  338. parts: [
  339. {
  340. partId: "p2",
  341. type: "text" as const,
  342. text: overrides.assistantMessageText,
  343. },
  344. ],
  345. });
  346. }
  347. return {
  348. protocol: { name: "ZCode Protocol", version: 1 },
  349. session: {
  350. sessionId,
  351. workspace: { workspacePath, workspaceKey: workspacePath },
  352. sessionKind: "interactive",
  353. revision: 1,
  354. status: overrides.sessionStatus ?? "running",
  355. mode: "build",
  356. title: overrides.title ?? "",
  357. createdAt: overrides.createdAt ?? 1,
  358. updatedAt: overrides.updatedAt ?? 1,
  359. contextWindow: 100000,
  360. contextUsage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
  361. activeTurnId: undefined,
  362. lastTurnId: undefined,
  363. lastInputId: undefined,
  364. archivedAt: undefined,
  365. },
  366. settings: {
  367. model: {
  368. current: settingsModel,
  369. available: [],
  370. },
  371. thoughtLevel: {
  372. enabled: overrides.thoughtLevel !== undefined,
  373. current: overrides.thoughtLevel,
  374. available: overrides.thoughtLevel ? [overrides.thoughtLevel] : [],
  375. },
  376. mode: { current: "build" },
  377. },
  378. projection: {
  379. target: overrides.target ?? null,
  380. lastError: overrides.lastError ?? null,
  381. pendingPermissions: [],
  382. },
  383. runtime: { stream: { recovering: false } },
  384. messages: messages as unknown as ZCodeSessionStateSnapshot["messages"],
  385. } as unknown as ZCodeSessionStateSnapshot;
  386. }
  387. describe("createZCodeTaskIndexSyncer", () => {
  388. it("writes status: completed on v4 phase running->completedSuccess, broadcasts and emits terminal/ready", async () => {
  389. const env = setupEnv({
  390. initialSessions: [summaryOf(seedTarget.sessionId, "running")],
  391. });
  392. await seedRunningTask(env.repo);
  393. const syncer = createZCodeTaskIndexSyncer({
  394. agentService: env.agent,
  395. taskIndexRepo: env.repo,
  396. });
  397. const broadcasts: ZCodeWorkspaceEvent[] = [];
  398. const subscription = syncer.onDynamicWorkspaceEvent({
  399. workspacePath: seedTarget.workspacePath,
  400. })((event) => broadcasts.push(event));
  401. const terminals: Array<{ kind: string; sessionId: string }> = [];
  402. const readies: Array<{ reason: string; sessionId: string }> = [];
  403. syncer.onSessionTerminalEvent((event) =>
  404. terminals.push({ kind: event.kind, sessionId: event.target.sessionId }),
  405. );
  406. syncer.onSessionReadyEvent((event) =>
  407. readies.push({ reason: event.reason, sessionId: event.target.sessionId }),
  408. );
  409. syncer.ensureSessionSubscription(seedTarget);
  410. await subscribed(env);
  411. env.indexEmitter.fire(indexUpsertFrame(summaryOf(seedTarget.sessionId, "completedSuccess")));
  412. await vi.waitFor(async () => {
  413. const meta = await env.repo.getTaskMeta({
  414. workspacePath: seedTarget.workspacePath,
  415. taskId: seedTarget.sessionId,
  416. });
  417. expect(meta?.status).toBe("completed");
  418. });
  419. // 终态迁移同时给 host runtime command queue 发终态 + ready(先 terminal 后 ready)。
  420. expect(terminals).toEqual([{ kind: "turn.completed", sessionId: seedTarget.sessionId }]);
  421. expect(readies).toEqual([{ reason: "prompt_completed", sessionId: seedTarget.sessionId }]);
  422. expect(env.agent.readSession).toHaveBeenCalledWith({
  423. ...seedTarget,
  424. runtimePolicy: "existing-only",
  425. contentProfile: "index",
  426. });
  427. expect(env.agent.resumeSession).not.toHaveBeenCalled();
  428. expect(broadcasts.length).toBeGreaterThanOrEqual(1);
  429. const changed = broadcasts.filter((event) => event.type === "workspace_task_list_changed");
  430. expect(changed.length).toBeGreaterThanOrEqual(1);
  431. const first = changed[0];
  432. if (first.type === "workspace_task_list_changed") {
  433. expect(first.taskId).toBe(seedTarget.sessionId);
  434. expect(first.taskMeta?.status).toBe("completed");
  435. expect(first.unreadSignal).toBe("background_terminal");
  436. }
  437. subscription.dispose();
  438. syncer.disposeAll();
  439. env.indexEmitter.dispose();
  440. env.configEmitter.dispose();
  441. });
  442. it.each([
  443. ["普通完成", undefined, "completedSuccess", true],
  444. ["Goal verified", "verified", "completedSuccess", true],
  445. ["Goal active 中间轮", "active", "completedSuccess", false],
  446. ["Goal verifying", "verifying", "completedSuccess", false],
  447. ["Goal notSatisfied", "notSatisfied", "completedSuccess", false],
  448. ["Goal paused/取消", "paused", "completedInterrupted", false],
  449. ["Goal failed 非错误终态", "failed", "completedSuccess", false],
  450. ["真实错误", "failed", "error", true],
  451. ] as const)(
  452. "%s 的终态未读信号符合 Goal 边界",
  453. async (_label, goalStatus, phase, shouldSignal) => {
  454. const env = setupEnv({
  455. initialSessions: [summaryOf(seedTarget.sessionId, "running", { goalStatus })],
  456. });
  457. await seedRunningTask(env.repo);
  458. const syncer = createZCodeTaskIndexSyncer({
  459. agentService: env.agent,
  460. taskIndexRepo: env.repo,
  461. });
  462. const broadcasts: ZCodeWorkspaceEvent[] = [];
  463. syncer.onDynamicWorkspaceEvent({
  464. workspacePath: seedTarget.workspacePath,
  465. })((event) => broadcasts.push(event));
  466. syncer.ensureSessionSubscription(seedTarget);
  467. await subscribed(env);
  468. env.indexEmitter.fire(
  469. indexUpsertFrame(summaryOf(seedTarget.sessionId, phase, { goalStatus })),
  470. );
  471. await vi.waitFor(() => expect(env.agent.readSession).toHaveBeenCalled());
  472. const unreadSignals = broadcasts.filter(
  473. (event) =>
  474. event.type === "workspace_task_list_changed" &&
  475. event.unreadSignal === "background_terminal",
  476. );
  477. expect(unreadSignals).toHaveLength(shouldSignal ? 1 : 0);
  478. syncer.disposeAll();
  479. env.indexEmitter.dispose();
  480. env.configEmitter.dispose();
  481. },
  482. );
  483. it("resyncs full snapshot on terminal transition so searchable_text catches up (v4 command path)", async () => {
  484. const env = setupEnv({
  485. initialSessions: [summaryOf("sess_v4_search", "running")],
  486. });
  487. vi.mocked(env.agent.readSession).mockResolvedValue(
  488. snapshotWith("sess_v4_search", "/repo", {
  489. title: "查询订单接口",
  490. userMessageText: "帮我查询订单接口的实现",
  491. assistantMessageText: "订单接口在 orderService 里实现。",
  492. assistantCompletedAt: 130,
  493. updatedAt: 120,
  494. }),
  495. );
  496. const syncer = createZCodeTaskIndexSyncer({
  497. agentService: env.agent,
  498. taskIndexRepo: env.repo,
  499. });
  500. const broadcasts: ZCodeWorkspaceEvent[] = [];
  501. syncer.onDynamicWorkspaceEvent({ workspacePath: "/repo" })((event) => broadcasts.push(event));
  502. syncer.ensureSessionSubscription({
  503. workspacePath: "/repo",
  504. sessionId: "sess_v4_search",
  505. });
  506. await subscribed(env);
  507. env.indexEmitter.fire(indexUpsertFrame(summaryOf("sess_v4_search", "completedSuccess")));
  508. // 行由回源 snapshot 创建(v4 命令路径没有 op 驱动的 snapshot 同步),正文可搜。
  509. await vi.waitFor(async () => {
  510. const result = await env.repo.queryTaskList({
  511. workspaceScopes: [{ workspacePath: "/repo" }],
  512. search: "orderService",
  513. });
  514. expect(result.total).toBe(1);
  515. });
  516. expect(
  517. broadcasts.filter(
  518. (event) =>
  519. event.type === "workspace_task_list_changed" &&
  520. event.unreadSignal === "background_terminal",
  521. ),
  522. ).toHaveLength(1);
  523. syncer.disposeAll();
  524. env.indexEmitter.dispose();
  525. env.configEmitter.dispose();
  526. });
  527. it("writes status: error on v4 phase running->error and fills lastError from resynced snapshot", async () => {
  528. const env = setupEnv({
  529. initialSessions: [summaryOf(seedTarget.sessionId, "running")],
  530. });
  531. await seedRunningTask(env.repo);
  532. vi.mocked(env.agent.readSession).mockResolvedValue(
  533. snapshotWith(seedTarget.sessionId, seedTarget.workspacePath, {
  534. title: "Pending task",
  535. userMessageText: "run it",
  536. lastError: { type: "MODEL_ERROR", message: "boom" },
  537. updatedAt: 6,
  538. }),
  539. );
  540. const syncer = createZCodeTaskIndexSyncer({
  541. agentService: env.agent,
  542. taskIndexRepo: env.repo,
  543. });
  544. const broadcasts: ZCodeWorkspaceEvent[] = [];
  545. const subscription = syncer.onDynamicWorkspaceEvent({
  546. workspacePath: seedTarget.workspacePath,
  547. })((event) => broadcasts.push(event));
  548. const readies: string[] = [];
  549. syncer.onSessionReadyEvent((event) => readies.push(event.reason));
  550. syncer.ensureSessionSubscription(seedTarget);
  551. await subscribed(env);
  552. env.indexEmitter.fire(indexUpsertFrame(summaryOf(seedTarget.sessionId, "error")));
  553. // sessions-index 摘要没有错误详情:status 先收敛,lastError 由回源 snapshot 补权威值。
  554. await vi.waitFor(async () => {
  555. const meta = await env.repo.getTaskMeta({
  556. workspacePath: seedTarget.workspacePath,
  557. taskId: seedTarget.sessionId,
  558. });
  559. expect(meta?.status).toBe("error");
  560. expect(meta?.lastError?.message).toBe("boom");
  561. expect(meta?.lastError?.code).toBe("MODEL_ERROR");
  562. });
  563. expect(readies).toEqual(["prompt_failed"]);
  564. expect(broadcasts.length).toBeGreaterThanOrEqual(1);
  565. subscription.dispose();
  566. syncer.disposeAll();
  567. env.indexEmitter.dispose();
  568. env.configEmitter.dispose();
  569. });
  570. it("writes title and broadcasts when v4 summary title changes", async () => {
  571. const env = setupEnv({
  572. initialSessions: [summaryOf(seedTarget.sessionId, "running")],
  573. });
  574. await seedRunningTask(env.repo);
  575. const syncer = createZCodeTaskIndexSyncer({
  576. agentService: env.agent,
  577. taskIndexRepo: env.repo,
  578. });
  579. const broadcasts: ZCodeWorkspaceEvent[] = [];
  580. const subscription = syncer.onDynamicWorkspaceEvent({
  581. workspacePath: seedTarget.workspacePath,
  582. })((event) => broadcasts.push(event));
  583. syncer.ensureSessionSubscription(seedTarget);
  584. await subscribed(env);
  585. env.indexEmitter.fire(
  586. indexUpsertFrame(summaryOf(seedTarget.sessionId, "running", { title: "hello world" })),
  587. );
  588. await vi.waitFor(async () => {
  589. const meta = await env.repo.getTaskMeta({
  590. workspacePath: seedTarget.workspacePath,
  591. taskId: seedTarget.sessionId,
  592. });
  593. expect(meta?.title).toBe("hello world");
  594. });
  595. expect(broadcasts.length).toBeGreaterThanOrEqual(1);
  596. const last = broadcasts[broadcasts.length - 1];
  597. if (last.type === "workspace_task_list_changed") {
  598. expect(last.taskMeta?.title).toBe("hello world");
  599. }
  600. subscription.dispose();
  601. syncer.disposeAll();
  602. env.indexEmitter.dispose();
  603. env.configEmitter.dispose();
  604. });
  605. it("falls back to a full snapshot when title arrives before task index row exists", async () => {
  606. const env = setupEnv();
  607. const target: ZCodeAgentSessionTarget = {
  608. workspacePath: "/repo",
  609. sessionId: "sess_missing",
  610. };
  611. vi.mocked(env.agent.readSession).mockResolvedValue(
  612. snapshotWith("sess_missing", "/repo", {
  613. title: "first prompt title",
  614. updatedAt: 8,
  615. }),
  616. );
  617. const syncer = createZCodeTaskIndexSyncer({
  618. agentService: env.agent,
  619. taskIndexRepo: env.repo,
  620. });
  621. const broadcasts: ZCodeWorkspaceEvent[] = [];
  622. const subscription = syncer.onDynamicWorkspaceEvent({
  623. workspacePath: "/repo",
  624. })((event) => broadcasts.push(event));
  625. syncer.ensureSessionSubscription(target);
  626. await subscribed(env);
  627. // v4 命令路径首发:会话以带首标题的 upsert 出现,sqlite 尚无行 → 回源完整 snapshot。
  628. env.indexEmitter.fire(
  629. indexUpsertFrame(summaryOf("sess_missing", "running", { title: "first prompt title" })),
  630. );
  631. await vi.waitFor(() => {
  632. expect(env.agent.readSession).toHaveBeenCalledWith({
  633. ...target,
  634. runtimePolicy: "existing-only",
  635. contentProfile: "index",
  636. });
  637. expect(env.agent.resumeSession).not.toHaveBeenCalled();
  638. });
  639. await vi.waitFor(async () => {
  640. const meta = await env.repo.getTaskMeta({
  641. workspacePath: "/repo",
  642. taskId: "sess_missing",
  643. });
  644. expect(meta?.title).toBe("first prompt title");
  645. });
  646. const groupedStructure = await env.repo.queryGroupedTaskViewStructure({
  647. workspaceScopes: [{ workspacePath: "/repo" }],
  648. });
  649. expect(groupedStructure.topLevelOrders[0]).toMatchObject({
  650. type: "task",
  651. taskId: "sess_missing",
  652. });
  653. expect(broadcasts.length).toBe(1);
  654. subscription.dispose();
  655. syncer.disposeAll();
  656. env.indexEmitter.dispose();
  657. env.configEmitter.dispose();
  658. });
  659. it("places a promoted v4 draft at grouped root top before its title arrives", async () => {
  660. const env = setupEnv({
  661. initialSessions: [summaryOf("sess-promoted", "draft")],
  662. });
  663. const target: ZCodeAgentSessionTarget = {
  664. workspacePath: "/repo",
  665. sessionId: "sess-promoted",
  666. };
  667. vi.mocked(env.agent.readSession).mockResolvedValue(
  668. snapshotWith("sess-promoted", "/repo", { title: "", updatedAt: 8 }),
  669. );
  670. const syncer = createZCodeTaskIndexSyncer({
  671. agentService: env.agent,
  672. taskIndexRepo: env.repo,
  673. });
  674. const broadcasts: ZCodeWorkspaceEvent[] = [];
  675. const subscription = syncer.onDynamicWorkspaceEvent({ workspacePath: "/repo" })((event) =>
  676. broadcasts.push(event),
  677. );
  678. syncer.ensureSessionSubscription(target);
  679. await subscribed(env);
  680. env.indexEmitter.fire(indexUpsertFrame(summaryOf("sess-promoted", "running")));
  681. await vi.waitFor(async () => {
  682. const structure = await env.repo.queryGroupedTaskViewStructure({
  683. workspaceScopes: [{ workspacePath: "/repo" }],
  684. });
  685. expect(structure.topLevelOrders[0]).toMatchObject({
  686. type: "task",
  687. taskId: "sess-promoted",
  688. });
  689. });
  690. expect(broadcasts).toContainEqual(
  691. expect.objectContaining({
  692. type: "workspace_task_list_changed",
  693. taskId: "sess-promoted",
  694. reason: "task_created",
  695. }),
  696. );
  697. subscription.dispose();
  698. syncer.disposeAll();
  699. env.indexEmitter.dispose();
  700. env.configEmitter.dispose();
  701. });
  702. it("silently seeds missing rows from the first sessions-index snapshot and skips drafts", async () => {
  703. const env = setupEnv({
  704. initialSessions: [summaryOf("sess_history", "completedSuccess", { title: "历史会话" })],
  705. });
  706. const syncer = createZCodeTaskIndexSyncer({
  707. agentService: env.agent,
  708. taskIndexRepo: env.repo,
  709. });
  710. const broadcasts: ZCodeWorkspaceEvent[] = [];
  711. const subscription = syncer.onDynamicWorkspaceEvent({
  712. workspacePath: "/repo",
  713. })((event) => broadcasts.push(event));
  714. syncer.ensureSessionSubscription({
  715. workspacePath: "/repo",
  716. sessionId: "sess_history",
  717. });
  718. await subscribed(env);
  719. // 冷启动 snapshot 不回放历史终态/广播,但必须补齐缺失索引行,避免远端新库永远为空。
  720. await vi.waitFor(async () => {
  721. const meta = await env.repo.getTaskMeta({ workspacePath: "/repo", taskId: "sess_history" });
  722. expect(meta).toMatchObject({
  723. taskId: "sess_history",
  724. title: "历史会话",
  725. provider: "glm",
  726. status: "completed",
  727. });
  728. });
  729. // draft 会话(纯内存态)不进 task index。
  730. env.indexEmitter.fire(indexUpsertFrame(summaryOf("sess_draft", "draft", { title: "草稿" })));
  731. await new Promise((resolve) => setImmediate(resolve));
  732. expect(await env.repo.getTaskMeta({ workspacePath: "/repo", taskId: "sess_draft" })).toBeNull();
  733. expect(broadcasts.length).toBe(0);
  734. subscription.dispose();
  735. syncer.disposeAll();
  736. env.indexEmitter.dispose();
  737. env.configEmitter.dispose();
  738. });
  739. it("keeps dynamic workspace-event consumers passive when no runtime exists", async () => {
  740. const env = setupEnv();
  741. const syncer = createZCodeTaskIndexSyncer({
  742. agentService: env.agent,
  743. taskIndexRepo: env.repo,
  744. });
  745. const subscription = syncer.onDynamicWorkspaceEvent({
  746. workspacePath: "/repo",
  747. workspaceIdentity: "remote:ssh:dev:/repo",
  748. })(() => {});
  749. await new Promise((resolve) => setImmediate(resolve));
  750. expect(env.agent.subscribeSessionsIndexV4).not.toHaveBeenCalled();
  751. expect(env.agent.subscribeWorkspaceConfigV4).not.toHaveBeenCalled();
  752. subscription.dispose();
  753. syncer.disposeAll();
  754. env.indexEmitter.dispose();
  755. env.configEmitter.dispose();
  756. });
  757. it("installs dormant frame listeners before first available subscribe and reuses them after restart", async () => {
  758. const env = setupEnv({
  759. initialSessions: [summaryOf(seedTarget.sessionId, "running")],
  760. runtimeLifecycle: true,
  761. });
  762. const syncer = createZCodeTaskIndexSyncer({
  763. agentService: env.agent,
  764. taskIndexRepo: env.repo,
  765. });
  766. const terminals: string[] = [];
  767. const readies: string[] = [];
  768. syncer.onSessionTerminalEvent((event) => terminals.push(event.kind));
  769. syncer.onSessionReadyEvent((event) => readies.push(event.reason));
  770. // 生产中 task adapter 会先 notify/ensure session,再由实际命令启动名单外 runtime。
  771. syncer.ensureSessionSubscription(seedTarget);
  772. await Promise.resolve();
  773. expect(env.agent.subscribeSessionsIndexV4).not.toHaveBeenCalled();
  774. expect(env.agent.onDynamicSessionsIndexFrame).not.toHaveBeenCalled();
  775. expect(env.agent.onDynamicWorkspaceConfigFrame).not.toHaveBeenCalled();
  776. env.lifecycleEmitter.fire({
  777. workspacePath: seedTarget.workspacePath,
  778. workspaceKey: seedTarget.workspacePath,
  779. runtimeIdentity: {
  780. generation: 1,
  781. identity: `${seedTarget.workspacePath}:1`,
  782. workspaceKey: seedTarget.workspacePath,
  783. },
  784. state: "available",
  785. });
  786. await subscribed(env);
  787. // 回归根因:首次 available 必须先挂 listener,subscribe response resolve 后、await
  788. // continuation 前同步到达的 initial frame 才能写入 task index;旧实现只重订阅。
  789. expect(env.agent.onDynamicSessionsIndexFrame).toHaveBeenCalledTimes(1);
  790. expect(env.agent.onDynamicWorkspaceConfigFrame).toHaveBeenCalledTimes(1);
  791. expect(env.agent.subscribeWorkspaceConfigV4).toHaveBeenCalledTimes(1);
  792. await vi.waitFor(async () => {
  793. const meta = await env.repo.getTaskMeta({
  794. workspacePath: seedTarget.workspacePath,
  795. taskId: seedTarget.sessionId,
  796. });
  797. expect(meta?.status).toBe("running");
  798. });
  799. env.indexEmitter.fire(indexUpsertFrame(summaryOf(seedTarget.sessionId, "completedSuccess")));
  800. await vi.waitFor(async () => {
  801. const meta = await env.repo.getTaskMeta({
  802. workspacePath: seedTarget.workspacePath,
  803. taskId: seedTarget.sessionId,
  804. });
  805. expect(meta?.status).toBe("completed");
  806. });
  807. expect(terminals).toEqual(["turn.completed"]);
  808. expect(readies).toEqual(["prompt_completed"]);
  809. env.lifecycleEmitter.fire({
  810. workspacePath: seedTarget.workspacePath,
  811. workspaceKey: seedTarget.workspacePath,
  812. runtimeIdentity: {
  813. generation: 1,
  814. identity: `${seedTarget.workspacePath}:1`,
  815. workspaceKey: seedTarget.workspacePath,
  816. },
  817. state: "unavailable",
  818. });
  819. env.lifecycleEmitter.fire({
  820. workspacePath: seedTarget.workspacePath,
  821. workspaceKey: seedTarget.workspacePath,
  822. runtimeIdentity: {
  823. generation: 2,
  824. identity: `${seedTarget.workspacePath}:2`,
  825. workspaceKey: seedTarget.workspacePath,
  826. },
  827. state: "available",
  828. });
  829. await vi.waitFor(() => {
  830. expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(2);
  831. expect(env.agent.subscribeWorkspaceConfigV4).toHaveBeenCalledTimes(2);
  832. });
  833. expect(env.agent.onDynamicSessionsIndexFrame).toHaveBeenCalledTimes(1);
  834. expect(env.agent.onDynamicWorkspaceConfigFrame).toHaveBeenCalledTimes(1);
  835. expect(terminals).toEqual(["turn.completed"]);
  836. expect(readies).toEqual(["prompt_completed"]);
  837. syncer.disposeAll();
  838. env.indexEmitter.dispose();
  839. env.configEmitter.dispose();
  840. env.lifecycleEmitter.dispose();
  841. });
  842. it("attaches only to an available runtime and returns to dormant after it exits", async () => {
  843. vi.useFakeTimers();
  844. try {
  845. const env = setupEnv({ runtimeLifecycle: true });
  846. const syncer = createZCodeTaskIndexSyncer({
  847. agentService: env.agent,
  848. taskIndexRepo: env.repo,
  849. });
  850. const workspaceIdentity = "remote:ssh:dev:/repo";
  851. const subscription = syncer.onDynamicWorkspaceEvent({
  852. workspacePath: "/repo",
  853. workspaceIdentity,
  854. })(() => {});
  855. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo", workspaceIdentity });
  856. await Promise.resolve();
  857. expect(env.agent.subscribeSessionsIndexV4).not.toHaveBeenCalled();
  858. env.lifecycleEmitter.fire({
  859. workspacePath: "/repo",
  860. workspaceIdentity,
  861. workspaceKey: workspaceIdentity,
  862. runtimeIdentity: {
  863. generation: 1,
  864. identity: `${workspaceIdentity}:1`,
  865. workspaceKey: workspaceIdentity,
  866. },
  867. state: "available",
  868. });
  869. await vi.waitFor(() => expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1));
  870. expect(env.agent.subscribeSessionsIndexV4).toHaveBeenLastCalledWith(
  871. expect.objectContaining({
  872. workspacePath: "/repo",
  873. workspaceIdentity,
  874. subscriberScope: "task-index",
  875. runtimePolicy: "existing-only",
  876. }),
  877. );
  878. env.lifecycleEmitter.fire({
  879. workspacePath: "/repo",
  880. workspaceIdentity,
  881. workspaceKey: workspaceIdentity,
  882. runtimeIdentity: {
  883. generation: 1,
  884. identity: `${workspaceIdentity}:1`,
  885. workspaceKey: workspaceIdentity,
  886. },
  887. state: "unavailable",
  888. });
  889. await vi.advanceTimersByTimeAsync(30_000);
  890. expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  891. env.lifecycleEmitter.fire({
  892. workspacePath: "/repo",
  893. workspaceIdentity,
  894. workspaceKey: workspaceIdentity,
  895. runtimeIdentity: {
  896. generation: 2,
  897. identity: `${workspaceIdentity}:2`,
  898. workspaceKey: workspaceIdentity,
  899. },
  900. state: "available",
  901. });
  902. await vi.waitFor(() => expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(2));
  903. subscription.dispose();
  904. syncer.disposeAll();
  905. env.indexEmitter.dispose();
  906. env.configEmitter.dispose();
  907. env.lifecycleEmitter.dispose();
  908. } finally {
  909. vi.useRealTimers();
  910. }
  911. });
  912. it("SAT29: 只清理明确属于当前 workspace 的 subagent 索引,保留 fork 与未确认记录", async () => {
  913. const env = setupEnv();
  914. for (const taskId of ["child", "fork", "unknown"]) {
  915. await env.repo.syncTaskMetaAtGroupedTop({
  916. meta: {
  917. ...snapshotWith(taskId, "/repo").session,
  918. taskId,
  919. traceId: "trace",
  920. title: taskId,
  921. workspacePath: "/repo",
  922. createdAt: 1,
  923. updatedAt: 2,
  924. mode: "build",
  925. provider: "glm",
  926. status: "completed",
  927. },
  928. });
  929. }
  930. await env.repo.syncTaskMeta({
  931. meta: {
  932. taskId: "child",
  933. traceId: "trace",
  934. title: "foreign",
  935. workspacePath: "/repo",
  936. workspaceIdentity: "remote:ssh:foreign:/repo",
  937. createdAt: 1,
  938. updatedAt: 2,
  939. mode: "build",
  940. provider: "glm",
  941. status: "completed",
  942. },
  943. });
  944. vi.mocked(env.agent.listSessions).mockResolvedValue([
  945. { ...snapshotWith("child", "/repo").session, sessionKind: "subagent_child" },
  946. { ...snapshotWith("fork", "/repo").session, sessionKind: "fork", parentSessionId: "parent" },
  947. ]);
  948. const syncer = createZCodeTaskIndexSyncer({ agentService: env.agent, taskIndexRepo: env.repo });
  949. const changed = vi.fn();
  950. const listener = syncer.onDynamicWorkspaceEvent("/repo")(changed);
  951. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  952. await vi.waitFor(async () =>
  953. expect(await env.repo.getTaskMeta({ workspacePath: "/repo", taskId: "child" })).toBeNull(),
  954. );
  955. expect(await env.repo.getTaskMeta({ workspacePath: "/repo", taskId: "fork" })).not.toBeNull();
  956. expect(
  957. await env.repo.getTaskMeta({ workspacePath: "/repo", taskId: "unknown" }),
  958. ).not.toBeNull();
  959. expect(
  960. await env.repo.getTaskMeta({
  961. workspacePath: "/repo",
  962. workspaceIdentity: "remote:ssh:foreign:/repo",
  963. taskId: "child",
  964. }),
  965. ).not.toBeNull();
  966. expect(env.agent.listSessions).toHaveBeenCalledWith(
  967. expect.objectContaining({
  968. workspacePath: "/repo",
  969. sessionIds: expect.arrayContaining(["child", "fork", "unknown"]),
  970. includeArchived: true,
  971. }),
  972. );
  973. expect(env.agent.resumeSession).not.toHaveBeenCalled();
  974. expect(changed).toHaveBeenCalled();
  975. listener.dispose();
  976. syncer.disposeAll();
  977. });
  978. it.each(["failure", "disposed"] as const)(
  979. "SAT29: 身份查询 %s 时保留既有索引",
  980. async (failure) => {
  981. const env = setupEnv();
  982. await env.repo.syncTaskMeta({
  983. meta: { ...(await seedRunningTask(env.repo)), provider: "glm" },
  984. });
  985. let finish:
  986. | ((value: Awaited<ReturnType<IZCodeAgentService["listSessions"]>>) => void)
  987. | undefined;
  988. vi.mocked(env.agent.listSessions).mockImplementation(() =>
  989. failure === "failure"
  990. ? Promise.reject(new Error("remote unavailable"))
  991. : new Promise((resolve) => {
  992. finish = resolve;
  993. }),
  994. );
  995. const syncer = createZCodeTaskIndexSyncer({
  996. agentService: env.agent,
  997. taskIndexRepo: env.repo,
  998. });
  999. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  1000. await vi.waitFor(() => expect(env.agent.listSessions).toHaveBeenCalled());
  1001. syncer.disposeAll();
  1002. finish?.([
  1003. { ...snapshotWith(seedTarget.sessionId, "/repo").session, sessionKind: "subagent_child" },
  1004. ]);
  1005. await new Promise((resolve) => setImmediate(resolve));
  1006. expect(
  1007. await env.repo.getTaskMeta({ workspacePath: "/repo", taskId: seedTarget.sessionId }),
  1008. ).not.toBeNull();
  1009. },
  1010. );
  1011. it("SAT28: child 完整快照不重新写入主列表", async () => {
  1012. const env = setupEnv();
  1013. const syncer = createZCodeTaskIndexSyncer({ agentService: env.agent, taskIndexRepo: env.repo });
  1014. const snapshot = snapshotWith("child", "/repo", { userMessageText: "child prompt" });
  1015. snapshot.session.sessionKind = "subagent_child";
  1016. await syncer.syncSnapshotAndBroadcast(snapshot, { broadcastReason: "task_status_changed" });
  1017. expect(await env.repo.getTaskMeta({ workspacePath: "/repo", taskId: "child" })).toBeNull();
  1018. syncer.disposeAll();
  1019. });
  1020. it("does not overwrite existing product-shell state during initial snapshot reconciliation", async () => {
  1021. const env = setupEnv({
  1022. initialSessions: [
  1023. summaryOf("sess_existing", "completedSuccess", {
  1024. title: "Agent 标题",
  1025. titleSource: "generated",
  1026. lastActivityAt: 999,
  1027. }),
  1028. ],
  1029. });
  1030. await env.repo.syncTaskMeta({
  1031. meta: {
  1032. taskId: "sess_existing",
  1033. traceId: "trace-existing",
  1034. title: "用户标题",
  1035. titleOverridden: true,
  1036. workspacePath: "/repo",
  1037. createdAt: 1,
  1038. updatedAt: 100,
  1039. mode: "build",
  1040. model: "anthropic/haiku-4.5",
  1041. provider: "glm",
  1042. status: "completed",
  1043. },
  1044. pinned: true,
  1045. titleOverridden: true,
  1046. });
  1047. const syncer = createZCodeTaskIndexSyncer({
  1048. agentService: env.agent,
  1049. taskIndexRepo: env.repo,
  1050. });
  1051. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  1052. await subscribed(env);
  1053. const [meta] = await env.repo.listTaskMetas({ workspacePath: "/repo", pinned: true });
  1054. expect(meta).toMatchObject({
  1055. taskId: "sess_existing",
  1056. title: "用户标题",
  1057. titleOverridden: true,
  1058. updatedAt: 100,
  1059. mode: "build",
  1060. model: "anthropic/haiku-4.5",
  1061. });
  1062. syncer.disposeAll();
  1063. env.indexEmitter.dispose();
  1064. env.configEmitter.dispose();
  1065. });
  1066. it("seeds remote rows under workspaceIdentity instead of the shared workspacePath", async () => {
  1067. const workspaceIdentity = "remote:ssh:dev.example:22:codegeex:/repo";
  1068. const env = setupEnv({
  1069. workspaceKey: workspaceIdentity,
  1070. initialSessions: [
  1071. summaryOf("sess_remote", "completedSuccess", {
  1072. workspaceId: workspaceIdentity,
  1073. title: "远端会话",
  1074. }),
  1075. ],
  1076. });
  1077. const syncer = createZCodeTaskIndexSyncer({
  1078. agentService: env.agent,
  1079. taskIndexRepo: env.repo,
  1080. });
  1081. syncer.onDynamicWorkspaceEvent({
  1082. workspacePath: "/repo",
  1083. workspaceIdentity,
  1084. })(() => {});
  1085. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo", workspaceIdentity });
  1086. await subscribed(env);
  1087. await vi.waitFor(async () => {
  1088. const remoteMeta = await env.repo.getTaskMeta({
  1089. workspacePath: "/repo",
  1090. workspaceIdentity,
  1091. taskId: "sess_remote",
  1092. });
  1093. expect(remoteMeta?.workspaceIdentity).toBe(workspaceIdentity);
  1094. });
  1095. expect(
  1096. await env.repo.getTaskMeta({ workspacePath: "/repo", taskId: "sess_remote" }),
  1097. ).toBeNull();
  1098. syncer.disposeAll();
  1099. env.indexEmitter.dispose();
  1100. env.configEmitter.dispose();
  1101. });
  1102. it("forwards v4 workspace-config frames as workspace_config_options_update and drops empty catalogs", async () => {
  1103. const env = setupEnv();
  1104. const syncer = createZCodeTaskIndexSyncer({
  1105. agentService: env.agent,
  1106. taskIndexRepo: env.repo,
  1107. });
  1108. const broadcasts: ZCodeWorkspaceEvent[] = [];
  1109. const subscription = syncer.onDynamicWorkspaceEvent({
  1110. workspacePath: "/repo",
  1111. })((event) => broadcasts.push(event));
  1112. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  1113. await subscribed(env);
  1114. // 空目录(无 live session 的订阅种子)不下发,避免清掉工具栏模型目录。
  1115. env.configEmitter.fire(configFrame({ configOptions: [], slashCommands: [] }));
  1116. expect(broadcasts.length).toBe(0);
  1117. env.configEmitter.fire(
  1118. configFrame(
  1119. {
  1120. configOptions: [
  1121. {
  1122. id: "model",
  1123. name: "Model",
  1124. category: "model",
  1125. type: "select",
  1126. currentValue: "anthropic/haiku-4.5",
  1127. options: [{ value: "anthropic/haiku-4.5", name: "Haiku 4.5" }],
  1128. },
  1129. ],
  1130. slashCommands: [{ name: "compact", description: "Compact" }],
  1131. },
  1132. 2,
  1133. ),
  1134. );
  1135. expect(broadcasts.length).toBe(1);
  1136. const event = broadcasts[0];
  1137. expect(event.type).toBe("workspace_config_options_update");
  1138. if (event.type === "workspace_config_options_update") {
  1139. expect(event.workspacePath).toBe("/repo");
  1140. expect(event.configOptions).toHaveLength(1);
  1141. expect(event.configOptions[0]?.id).toBe("model");
  1142. }
  1143. subscription.dispose();
  1144. syncer.disposeAll();
  1145. env.indexEmitter.dispose();
  1146. env.configEmitter.dispose();
  1147. });
  1148. it("syncSnapshotAndBroadcast writes meta and fires workspace_task_list_changed", async () => {
  1149. const env = setupEnv();
  1150. const syncer = createZCodeTaskIndexSyncer({
  1151. agentService: env.agent,
  1152. taskIndexRepo: env.repo,
  1153. });
  1154. const broadcasts: ZCodeWorkspaceEvent[] = [];
  1155. const subscription = syncer.onDynamicWorkspaceEvent({
  1156. workspacePath: "/repo",
  1157. })((event) => broadcasts.push(event));
  1158. const meta = await syncer.syncSnapshotAndBroadcast(
  1159. snapshotWith("sess_new", "/repo", {
  1160. title: "", // 模拟 runtime 还没写 title,触发 deriveTitleFromSnapshot
  1161. userMessageText: "fix the bug in checkout flow",
  1162. updatedAt: 999,
  1163. }),
  1164. { broadcastReason: "task_meta_changed" },
  1165. );
  1166. // 期望从首条 user message 推断 title
  1167. expect(meta.title).toBe("fix the bug in checkout flow");
  1168. expect(meta.updatedAt).toBe(999);
  1169. const persisted = await env.repo.getTaskMeta({
  1170. workspacePath: "/repo",
  1171. taskId: "sess_new",
  1172. });
  1173. expect(persisted?.title).toBe("fix the bug in checkout flow");
  1174. expect(broadcasts.length).toBe(1);
  1175. const evt = broadcasts[0];
  1176. if (evt.type === "workspace_task_list_changed") {
  1177. expect(evt.taskId).toBe("sess_new");
  1178. expect(evt.taskMeta?.title).toBe("fix the bug in checkout flow");
  1179. } else {
  1180. throw new Error("expected workspace_task_list_changed");
  1181. }
  1182. subscription.dispose();
  1183. syncer.disposeAll();
  1184. });
  1185. it("syncSnapshotAndBroadcast 对 index profile 裁剪后的 snapshot 产出与 full 完全一致的索引写入", async () => {
  1186. const big = "z".repeat(256 * 1024);
  1187. const full = snapshotWith("sess_profile", "/repo", {
  1188. title: "",
  1189. userMessageText: "排查订单列表慢查询",
  1190. assistantMessageText: "根因是缺少索引",
  1191. assistantCompletedAt: 50,
  1192. sessionStatus: "completed",
  1193. updatedAt: 60,
  1194. });
  1195. // 固定 traceId:缺省时 buildMetaFromSnapshot 会随机生成,与裁剪无关。
  1196. full.session.traceId = "trace_profile";
  1197. const assistant = full.messages.find((message) => message.info.role === "assistant");
  1198. if (!assistant) throw new Error("fixture assistant missing");
  1199. assistant.parts.unshift(
  1200. { partId: "p_reason", type: "reasoning", text: big } as never,
  1201. {
  1202. partId: "p_tool",
  1203. type: "tool",
  1204. callId: "call_profile",
  1205. tool: "bash",
  1206. state: {
  1207. status: "completed",
  1208. input: { command: big },
  1209. output: big,
  1210. title: "bash",
  1211. metadata: { output: big },
  1212. startedAt: 40,
  1213. completedAt: 41,
  1214. },
  1215. } as never,
  1216. );
  1217. const elided = elideSessionSnapshotForIndex(full);
  1218. expect(JSON.stringify(elided).length).toBeLessThan(big.length / 10);
  1219. const capture = async (snapshot: ZCodeSessionStateSnapshot) => {
  1220. const env = setupEnv();
  1221. const writes: unknown[] = [];
  1222. const original = env.repo.syncTaskMeta.bind(env.repo);
  1223. vi.spyOn(env.repo, "syncTaskMeta").mockImplementation(async (input) => {
  1224. writes.push(structuredClone(input));
  1225. return await original(input);
  1226. });
  1227. const syncer = createZCodeTaskIndexSyncer({
  1228. agentService: env.agent,
  1229. taskIndexRepo: env.repo,
  1230. });
  1231. const broadcasts: ZCodeWorkspaceEvent[] = [];
  1232. const subscription = syncer.onDynamicWorkspaceEvent({ workspacePath: "/repo" })((event) =>
  1233. broadcasts.push(event),
  1234. );
  1235. const meta = await syncer.syncSnapshotAndBroadcast(snapshot, {
  1236. broadcastReason: "task_status_changed",
  1237. });
  1238. subscription.dispose();
  1239. syncer.disposeAll();
  1240. return { meta, writes, broadcasts };
  1241. };
  1242. const fromFull = await capture(full);
  1243. const fromIndex = await capture(elided);
  1244. expect(fromFull.writes).toHaveLength(1);
  1245. expect(fromFull.writes[0]).toMatchObject({
  1246. meta: { title: "排查订单列表慢查询", status: "completed" },
  1247. searchableText: "排查订单列表慢查询\n根因是缺少索引",
  1248. });
  1249. expect(fromIndex.writes).toEqual(fromFull.writes);
  1250. expect(fromIndex.meta).toEqual(fromFull.meta);
  1251. expect(fromIndex.broadcasts).toEqual(fromFull.broadcasts);
  1252. });
  1253. it("syncSnapshotAndBroadcast prefers structured projection error code in task meta", async () => {
  1254. const env = setupEnv();
  1255. const syncer = createZCodeTaskIndexSyncer({
  1256. agentService: env.agent,
  1257. taskIndexRepo: env.repo,
  1258. });
  1259. const restored = snapshotWith("sess_error", "/repo", {
  1260. title: "stale model",
  1261. updatedAt: 999,
  1262. });
  1263. const meta = await syncer.syncSnapshotAndBroadcast(
  1264. {
  1265. ...restored,
  1266. session: {
  1267. ...restored.session,
  1268. status: "error",
  1269. },
  1270. projection: {
  1271. ...restored.projection,
  1272. lastError: {
  1273. type: "MODEL_ERROR",
  1274. code: "provider_not_found",
  1275. message: "Model provider is not configured: stale-provider",
  1276. detail: "stale-provider/gpt-5.5",
  1277. attribution: {
  1278. source: "runtime",
  1279. reason: "provider_not_configured",
  1280. providerId: "account:zai-individual-coding-plan",
  1281. },
  1282. },
  1283. },
  1284. },
  1285. { broadcastReason: "task_status_changed" },
  1286. );
  1287. expect(meta.lastError).toEqual({
  1288. code: "provider_not_found",
  1289. detail: "stale-provider/gpt-5.5",
  1290. message: "Model provider is not configured: stale-provider",
  1291. attribution: {
  1292. source: "runtime",
  1293. reason: "provider_not_configured",
  1294. providerId: "account:zai-individual-coding-plan",
  1295. },
  1296. });
  1297. syncer.disposeAll();
  1298. });
  1299. it("syncSnapshotAndBroadcast stores the latest message model when settings current is polluted", async () => {
  1300. const env = setupEnv();
  1301. const syncer = createZCodeTaskIndexSyncer({
  1302. agentService: env.agent,
  1303. taskIndexRepo: env.repo,
  1304. });
  1305. const meta = await syncer.syncSnapshotAndBroadcast(
  1306. snapshotWith("sess_model", "/repo", {
  1307. title: "historical model",
  1308. userMessageText: "fix perf",
  1309. settingsModel: {
  1310. providerId: "36965ea6-734a-46a8-8851-3dfec026589e",
  1311. modelId: "glm-5.1-highspeed",
  1312. },
  1313. messageModel: {
  1314. providerId: "default-deepseek",
  1315. modelId: "deepseek-v4-flash",
  1316. },
  1317. }),
  1318. { broadcastReason: "task_meta_changed" },
  1319. );
  1320. expect(meta.model).toBe("default-deepseek/deepseek-v4-flash");
  1321. await expect(
  1322. env.repo.getTaskMeta({
  1323. workspacePath: "/repo",
  1324. taskId: "sess_model",
  1325. }),
  1326. ).resolves.toMatchObject({
  1327. model: "default-deepseek/deepseek-v4-flash",
  1328. });
  1329. syncer.disposeAll();
  1330. });
  1331. it("syncSnapshotAndBroadcast can override task model for explicit model switches", async () => {
  1332. const env = setupEnv();
  1333. const syncer = createZCodeTaskIndexSyncer({
  1334. agentService: env.agent,
  1335. taskIndexRepo: env.repo,
  1336. });
  1337. const meta = await syncer.syncSnapshotAndBroadcast(
  1338. snapshotWith("sess_model_override", "/repo", {
  1339. title: "historical model",
  1340. userMessageText: "continue with visible model",
  1341. settingsModel: {
  1342. providerId: "current-provider",
  1343. modelId: "current-model",
  1344. },
  1345. messageModel: {
  1346. providerId: "removed-provider",
  1347. modelId: "removed-model",
  1348. },
  1349. }),
  1350. { modelOverride: "current-provider/current-model", broadcastReason: "task_meta_changed" },
  1351. );
  1352. expect(meta.model).toBe("current-provider/current-model");
  1353. await expect(
  1354. env.repo.getTaskMeta({
  1355. workspacePath: "/repo",
  1356. taskId: "sess_model_override",
  1357. }),
  1358. ).resolves.toMatchObject({
  1359. model: "current-provider/current-model",
  1360. });
  1361. syncer.disposeAll();
  1362. });
  1363. it("syncSnapshotAndBroadcast can override task thought level for explicit resume", async () => {
  1364. const env = setupEnv();
  1365. const syncer = createZCodeTaskIndexSyncer({
  1366. agentService: env.agent,
  1367. taskIndexRepo: env.repo,
  1368. });
  1369. const meta = await syncer.syncSnapshotAndBroadcast(
  1370. snapshotWith("sess_thought_override", "/repo", {
  1371. title: "historical thought level",
  1372. userMessageText: "continue with task-local thought level",
  1373. thoughtLevel: "high",
  1374. }),
  1375. { thoughtLevelOverride: "max", broadcastReason: "task_meta_changed" },
  1376. );
  1377. expect(meta.thoughtLevel).toBe("max");
  1378. await expect(
  1379. env.repo.getTaskMeta({
  1380. workspacePath: "/repo",
  1381. taskId: "sess_thought_override",
  1382. }),
  1383. ).resolves.toMatchObject({
  1384. thoughtLevel: "max",
  1385. });
  1386. syncer.disposeAll();
  1387. });
  1388. it("syncTaskModel updates only the persisted task model", async () => {
  1389. const env = setupEnv();
  1390. const syncer = createZCodeTaskIndexSyncer({
  1391. agentService: env.agent,
  1392. taskIndexRepo: env.repo,
  1393. });
  1394. await env.repo.syncTaskMeta({
  1395. meta: {
  1396. taskId: "sess_model_patch",
  1397. traceId: "trace_model_patch",
  1398. title: "Existing task",
  1399. workspacePath: "/repo",
  1400. createdAt: 1,
  1401. updatedAt: 2,
  1402. mode: "build",
  1403. model: "removed-provider/removed-model",
  1404. status: "completed",
  1405. },
  1406. });
  1407. await expect(
  1408. syncer.syncTaskModel(
  1409. {
  1410. workspacePath: "/repo",
  1411. sessionId: "sess_model_patch",
  1412. },
  1413. "current-provider/current-model",
  1414. ),
  1415. ).resolves.toMatchObject({
  1416. model: "current-provider/current-model",
  1417. status: "completed",
  1418. title: "Existing task",
  1419. });
  1420. syncer.disposeAll();
  1421. });
  1422. it("syncSnapshotAndBroadcast titles /goal sessions without indexing continuation reminders", async () => {
  1423. const env = setupEnv();
  1424. const syncer = createZCodeTaskIndexSyncer({
  1425. agentService: env.agent,
  1426. taskIndexRepo: env.repo,
  1427. });
  1428. const internalGoalPrompt = [
  1429. '<system-reminder source="goal-continuation">',
  1430. "Continue working toward the active session goal.",
  1431. "",
  1432. "<untrusted_objective>",
  1433. "优化性能到 60fps",
  1434. "</untrusted_objective>",
  1435. "</system-reminder>",
  1436. ].join("\n");
  1437. const meta = await syncer.syncSnapshotAndBroadcast(
  1438. snapshotWith("sess_goal", "/repo", {
  1439. title: internalGoalPrompt,
  1440. userMessageText: internalGoalPrompt,
  1441. target: {
  1442. sessionId: "sess_goal",
  1443. targetId: "goal_1",
  1444. objective: "优化性能到 60fps",
  1445. summaryTitle: "优化性能到 60fps",
  1446. status: "active",
  1447. tokenBudget: null,
  1448. tokensUsed: 0,
  1449. timeUsedSeconds: 0,
  1450. createdAt: 1,
  1451. updatedAt: 1,
  1452. },
  1453. }),
  1454. { broadcastReason: "task_meta_changed" },
  1455. );
  1456. // Bugfix: /goal 自动续跑的内部 reminder wrapper 只是模型输入,不是用户可见 query。
  1457. // 标题可以回退到真实 goal objective,但正文搜索索引不能写入内部安全封装文本。
  1458. expect(meta.title).toBe("优化性能到 60fps");
  1459. expect(meta.target).toMatchObject({
  1460. objective: "优化性能到 60fps",
  1461. summaryTitle: "优化性能到 60fps",
  1462. targetID: "goal_1",
  1463. });
  1464. const objectiveResult = await env.repo.queryTaskList({
  1465. workspaceScopes: [{ workspacePath: "/repo" }],
  1466. search: "60fps",
  1467. });
  1468. expect(objectiveResult.total).toBe(1);
  1469. const persisted = await env.repo.getTaskMeta({
  1470. workspacePath: "/repo",
  1471. taskId: "sess_goal",
  1472. });
  1473. expect(persisted?.target).toMatchObject({
  1474. objective: "优化性能到 60fps",
  1475. summaryTitle: "优化性能到 60fps",
  1476. targetID: "goal_1",
  1477. });
  1478. const internalPromptResult = await env.repo.queryTaskList({
  1479. workspaceScopes: [{ workspacePath: "/repo" }],
  1480. search: "system-reminder",
  1481. });
  1482. expect(internalPromptResult.total).toBe(0);
  1483. syncer.disposeAll();
  1484. });
  1485. it("syncSnapshotAndBroadcast preserves indexed goal when snapshot omits target", async () => {
  1486. const env = setupEnv();
  1487. const syncer = createZCodeTaskIndexSyncer({
  1488. agentService: env.agent,
  1489. taskIndexRepo: env.repo,
  1490. });
  1491. await syncer.syncSnapshotAndBroadcast(
  1492. snapshotWith("sess_goal_preserve", "/repo", {
  1493. target: {
  1494. sessionId: "sess_goal_preserve",
  1495. targetId: "goal_keep",
  1496. objective: "保留历史目标",
  1497. summaryTitle: null,
  1498. status: "active",
  1499. tokenBudget: null,
  1500. tokensUsed: 0,
  1501. timeUsedSeconds: 0,
  1502. createdAt: 1,
  1503. updatedAt: 1,
  1504. },
  1505. }),
  1506. { broadcastReason: "task_meta_changed" },
  1507. );
  1508. const omittedTargetSnapshot = snapshotWith("sess_goal_preserve", "/repo", {
  1509. title: "继续处理历史任务",
  1510. userMessageText: "继续处理历史任务",
  1511. });
  1512. delete omittedTargetSnapshot.projection.target;
  1513. await syncer.syncSnapshotAndBroadcast(omittedTargetSnapshot, {
  1514. broadcastReason: "task_meta_changed",
  1515. });
  1516. expect(
  1517. (
  1518. await env.repo.getTaskMeta({
  1519. workspacePath: "/repo",
  1520. taskId: "sess_goal_preserve",
  1521. })
  1522. )?.target,
  1523. ).toMatchObject({
  1524. objective: "保留历史目标",
  1525. targetID: "goal_keep",
  1526. });
  1527. await syncer.syncSnapshotAndBroadcast(
  1528. snapshotWith("sess_goal_preserve", "/repo", {
  1529. title: "明确清空历史目标",
  1530. userMessageText: "明确清空历史目标",
  1531. target: null,
  1532. }),
  1533. { broadcastReason: "task_meta_changed" },
  1534. );
  1535. expect(
  1536. (
  1537. await env.repo.getTaskMeta({
  1538. workspacePath: "/repo",
  1539. taskId: "sess_goal_preserve",
  1540. })
  1541. )?.target,
  1542. ).toBeNull();
  1543. syncer.disposeAll();
  1544. });
  1545. it("syncSnapshotAndBroadcast writes sqlite but skips broadcast when snapshot has no user content", async () => {
  1546. // Bugfix: createSession 刚返回时 snapshot 既没有 title 也没有 user message,
  1547. // 此时不应该广播 workspace_task_list_changed,否则侧边栏会先闪一下 "New session" 占位符。
  1548. // sqlite 行仍然要写,让后续 session.titleUpdated (source="first_input") 的 applyAgentPatch 能找到行。
  1549. const env = setupEnv();
  1550. const syncer = createZCodeTaskIndexSyncer({
  1551. agentService: env.agent,
  1552. taskIndexRepo: env.repo,
  1553. });
  1554. const broadcasts: ZCodeWorkspaceEvent[] = [];
  1555. const subscription = syncer.onDynamicWorkspaceEvent({
  1556. workspacePath: "/repo",
  1557. })((event) => broadcasts.push(event));
  1558. await syncer.syncSnapshotAndBroadcast(
  1559. snapshotWith("sess_empty", "/repo", {
  1560. title: "",
  1561. // 不带 userMessageText → snapshot.messages 为空
  1562. updatedAt: 1,
  1563. }),
  1564. { broadcastReason: "task_meta_changed" },
  1565. );
  1566. expect(broadcasts.length).toBe(0);
  1567. // sqlite 行应该已经写入,等待后续 applyAgentPatch 找得到
  1568. const persisted = await env.repo.getTaskMeta({
  1569. workspacePath: "/repo",
  1570. taskId: "sess_empty",
  1571. });
  1572. expect(persisted).not.toBeNull();
  1573. expect(persisted?.taskId).toBe("sess_empty");
  1574. subscription.dispose();
  1575. syncer.disposeAll();
  1576. });
  1577. it("syncSnapshotAndBroadcast can place desktop-created sessions at the grouped view top", async () => {
  1578. const env = setupEnv();
  1579. await env.repo.syncTaskMeta({
  1580. meta: {
  1581. taskId: "older-task",
  1582. traceId: "trace_older",
  1583. title: "Older task",
  1584. workspacePath: "/repo",
  1585. createdAt: 10,
  1586. updatedAt: 10,
  1587. mode: "build",
  1588. status: "completed",
  1589. },
  1590. });
  1591. await env.repo.syncTaskMeta({
  1592. meta: {
  1593. taskId: "newer-existing-task",
  1594. traceId: "trace_newer_existing",
  1595. title: "Newer existing task",
  1596. workspacePath: "/repo",
  1597. createdAt: 20,
  1598. updatedAt: 20,
  1599. mode: "build",
  1600. status: "completed",
  1601. },
  1602. });
  1603. await env.repo.queryGroupedTaskView({
  1604. workspaceScopes: [{ workspacePath: "/repo" }],
  1605. });
  1606. const syncer = createZCodeTaskIndexSyncer({
  1607. agentService: env.agent,
  1608. taskIndexRepo: env.repo,
  1609. });
  1610. await syncer.syncSnapshotAndBroadcast(
  1611. snapshotWith("desktop-created-task", "/repo", {
  1612. title: "Desktop created task",
  1613. userMessageText: "Desktop created task",
  1614. createdAt: 30,
  1615. updatedAt: 30,
  1616. }),
  1617. { moveGroupedTaskToTop: true },
  1618. );
  1619. const view = await env.repo.queryGroupedTaskView({
  1620. workspaceScopes: [{ workspacePath: "/repo" }],
  1621. });
  1622. expect(view.nodes[0]).toMatchObject({
  1623. type: "task",
  1624. task: { taskId: "desktop-created-task" },
  1625. });
  1626. syncer.disposeAll();
  1627. });
  1628. it("does not reorder an existing task when duplicate first-snapshot sync finishes late", async () => {
  1629. const env = setupEnv();
  1630. const syncer = createZCodeTaskIndexSyncer({
  1631. agentService: env.agent,
  1632. taskIndexRepo: env.repo,
  1633. });
  1634. // 先完成空 workspace 的一次性 grouped bootstrap,后续 task 才按真实新建路径进入 root。
  1635. await env.repo.queryGroupedTaskView({
  1636. workspaceScopes: [{ workspacePath: "/repo" }],
  1637. });
  1638. const firstTask = snapshotWith("first-task", "/repo", {
  1639. title: "First task",
  1640. userMessageText: "First task",
  1641. createdAt: 10,
  1642. updatedAt: 10,
  1643. });
  1644. const secondTask = snapshotWith("second-task", "/repo", {
  1645. title: "Second task",
  1646. userMessageText: "Second task",
  1647. createdAt: 20,
  1648. updatedAt: 20,
  1649. });
  1650. await syncer.syncSnapshotAndBroadcast(firstTask, {
  1651. moveGroupedTaskToTop: true,
  1652. broadcastReason: "task_status_changed",
  1653. });
  1654. await syncer.syncSnapshotAndBroadcast(secondTask, {
  1655. moveGroupedTaskToTop: true,
  1656. broadcastReason: "task_status_changed",
  1657. });
  1658. // Bugfix 回归:可见状态与首标题缺行可能让 first-task 的重复回源晚于 second-task 完成。
  1659. // 重复 snapshot 只能更新 meta,不能再次给 first-task 分配更小的顶层 sort_order。
  1660. await syncer.syncSnapshotAndBroadcast(firstTask, {
  1661. moveGroupedTaskToTop: true,
  1662. broadcastReason: "task_status_changed",
  1663. });
  1664. const view = await env.repo.queryGroupedTaskView({
  1665. workspaceScopes: [{ workspacePath: "/repo" }],
  1666. });
  1667. expect(view.nodes.slice(0, 2)).toMatchObject([
  1668. { type: "task", task: { taskId: "second-task" } },
  1669. { type: "task", task: { taskId: "first-task" } },
  1670. ]);
  1671. syncer.disposeAll();
  1672. });
  1673. it("syncSnapshotAndBroadcast preserves a newer sqlite updated_at (no regression)", async () => {
  1674. // Bugfix: snapshot 的 session.updatedAt 是 runtime sessionStore 里的"结构变更时间",
  1675. // 不一定包含 session.titleUpdated / turn.completed 这些事件触发的 Date.now() 增量。
  1676. // 如果直接用 snapshot.updatedAt 覆盖会让刚被 applyAgentPatch 写入的更新时间倒退,
  1677. // 表现就是新会话第一次 prompt 后又被压到列表底部。
  1678. const env = setupEnv();
  1679. const syncer = createZCodeTaskIndexSyncer({
  1680. agentService: env.agent,
  1681. taskIndexRepo: env.repo,
  1682. });
  1683. // 先写一条 sqlite 行,updated_at 是较新的时间戳(模拟 applyAgentPatch 已经写过一次 Date.now())
  1684. await env.repo.syncTaskMeta({
  1685. meta: {
  1686. taskId: "sess_regress",
  1687. traceId: "trace_seed",
  1688. title: "你好",
  1689. workspacePath: "/repo",
  1690. createdAt: 100,
  1691. updatedAt: 99999,
  1692. mode: "build",
  1693. },
  1694. });
  1695. // 用一个较旧的 snapshot.updatedAt 触发 sync
  1696. await syncer.syncSnapshotAndBroadcast(
  1697. snapshotWith("sess_regress", "/repo", {
  1698. title: "你好",
  1699. userMessageText: "你好",
  1700. createdAt: 100,
  1701. updatedAt: 100, // 远小于 sqlite 已有的 99999
  1702. }),
  1703. { broadcastReason: "task_meta_changed" },
  1704. );
  1705. const persisted = await env.repo.getTaskMeta({
  1706. workspacePath: "/repo",
  1707. taskId: "sess_regress",
  1708. });
  1709. // 期望 updated_at 不会倒退
  1710. expect(persisted?.updatedAt).toBe(99999);
  1711. syncer.disposeAll();
  1712. });
  1713. it("syncSnapshotAndBroadcast does not downgrade newer terminal status with an older running snapshot", async () => {
  1714. const env = setupEnv();
  1715. const syncer = createZCodeTaskIndexSyncer({
  1716. agentService: env.agent,
  1717. taskIndexRepo: env.repo,
  1718. });
  1719. await env.repo.syncTaskMeta({
  1720. meta: {
  1721. taskId: "sess_terminal_status",
  1722. traceId: "trace_complete",
  1723. title: "阅读这个项目",
  1724. workspacePath: "/repo",
  1725. createdAt: 100,
  1726. updatedAt: 99_999,
  1727. mode: "build",
  1728. status: "completed",
  1729. },
  1730. });
  1731. await syncer.syncSnapshotAndBroadcast(
  1732. snapshotWith("sess_terminal_status", "/repo", {
  1733. title: "阅读这个项目",
  1734. userMessageText: "阅读这个项目",
  1735. createdAt: 100,
  1736. updatedAt: 100,
  1737. }),
  1738. { broadcastReason: "task_meta_changed" },
  1739. );
  1740. const persisted = await env.repo.getTaskMeta({
  1741. workspacePath: "/repo",
  1742. taskId: "sess_terminal_status",
  1743. });
  1744. expect(persisted?.updatedAt).toBe(99_999);
  1745. expect(persisted?.status).toBe("completed");
  1746. syncer.disposeAll();
  1747. });
  1748. it("syncSnapshotAndBroadcast repairs running status when snapshot has a completed assistant turn", async () => {
  1749. const env = setupEnv();
  1750. const syncer = createZCodeTaskIndexSyncer({
  1751. agentService: env.agent,
  1752. taskIndexRepo: env.repo,
  1753. });
  1754. await env.repo.syncTaskMeta({
  1755. meta: {
  1756. taskId: "sess_repair_terminal",
  1757. traceId: "trace_running",
  1758. title: "阅读这个项目",
  1759. workspacePath: "/repo",
  1760. createdAt: 100,
  1761. updatedAt: 100,
  1762. mode: "build",
  1763. status: "running",
  1764. },
  1765. });
  1766. await syncer.syncSnapshotAndBroadcast(
  1767. snapshotWith("sess_repair_terminal", "/repo", {
  1768. title: "阅读这个项目",
  1769. userMessageText: "阅读这个项目",
  1770. assistantMessageText: "以下是该项目的完整概览。",
  1771. assistantCompletedAt: 130,
  1772. createdAt: 100,
  1773. updatedAt: 120,
  1774. }),
  1775. { broadcastReason: "task_meta_changed" },
  1776. );
  1777. const persisted = await env.repo.getTaskMeta({
  1778. workspacePath: "/repo",
  1779. taskId: "sess_repair_terminal",
  1780. });
  1781. expect(persisted?.status).toBe("completed");
  1782. syncer.disposeAll();
  1783. });
  1784. it("syncSnapshotAndBroadcast keeps idle completed snapshots terminal in sqlite", async () => {
  1785. const env = setupEnv();
  1786. const syncer = createZCodeTaskIndexSyncer({
  1787. agentService: env.agent,
  1788. taskIndexRepo: env.repo,
  1789. });
  1790. await env.repo.syncTaskMeta({
  1791. meta: {
  1792. taskId: "sess_idle_completed",
  1793. traceId: "trace_idle_completed",
  1794. title: "切换项目后继续对话",
  1795. workspacePath: "/repo",
  1796. createdAt: 100,
  1797. updatedAt: 100,
  1798. mode: "build",
  1799. status: "running",
  1800. },
  1801. });
  1802. await syncer.syncSnapshotAndBroadcast(
  1803. snapshotWith("sess_idle_completed", "/repo", {
  1804. title: "切换项目后继续对话",
  1805. userMessageText: "继续",
  1806. assistantMessageText: "已经处理完成。",
  1807. assistantCompletedAt: 130,
  1808. sessionStatus: "idle",
  1809. createdAt: 100,
  1810. updatedAt: 130,
  1811. }),
  1812. { broadcastReason: "task_meta_changed" },
  1813. );
  1814. const persisted = await env.repo.getTaskMeta({
  1815. workspacePath: "/repo",
  1816. taskId: "sess_idle_completed",
  1817. });
  1818. expect(persisted?.status).toBe("completed");
  1819. syncer.disposeAll();
  1820. });
  1821. it("only subscribes the workspace once even across many sessions", async () => {
  1822. const env = setupEnv();
  1823. const syncer = createZCodeTaskIndexSyncer({
  1824. agentService: env.agent,
  1825. taskIndexRepo: env.repo,
  1826. });
  1827. syncer.ensureSessionSubscription(seedTarget);
  1828. syncer.ensureSessionSubscription(seedTarget);
  1829. syncer.ensureSessionSubscription({
  1830. workspacePath: seedTarget.workspacePath,
  1831. sessionId: "another_session",
  1832. });
  1833. syncer.ensureWorkspaceSubscription({ workspacePath: seedTarget.workspacePath });
  1834. await subscribed(env);
  1835. expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  1836. expect(env.agent.subscribeWorkspaceConfigV4).toHaveBeenCalledTimes(1);
  1837. // 与 renderer 侧栏共 topic 不同代际:syncer 必须带独立 subscriberScope。
  1838. expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledWith(
  1839. expect.objectContaining({ subscriberScope: "task-index" }),
  1840. );
  1841. syncer.disposeAll();
  1842. env.indexEmitter.dispose();
  1843. env.configEmitter.dispose();
  1844. });
  1845. it("stages same-read index/config initial notifications and releases only the ACK subId", async () => {
  1846. const env = setupEnv();
  1847. await seedRunningTask(env.repo);
  1848. let resolveIndex!: (result: IndexSubscribeResult) => void;
  1849. vi.mocked(env.agent.subscribeSessionsIndexV4).mockImplementationOnce(
  1850. () => new Promise((resolve) => (resolveIndex = resolve)),
  1851. );
  1852. vi.mocked(env.agent.subscribeWorkspaceConfigV4).mockImplementationOnce(async () => {
  1853. env.configEmitter.fire(
  1854. configFrame({
  1855. configOptions: [
  1856. {
  1857. id: "model",
  1858. name: "Model",
  1859. category: "model",
  1860. type: "select",
  1861. currentValue: "anthropic/haiku-4.5",
  1862. options: [{ value: "anthropic/haiku-4.5", name: "Haiku 4.5" }],
  1863. },
  1864. ],
  1865. slashCommands: [],
  1866. }),
  1867. );
  1868. return {
  1869. ack: {
  1870. subscriptionId: CONFIG_SUBSCRIPTION_ID,
  1871. mode: "snapshot" as const,
  1872. logEpoch: "epoch-cfg",
  1873. },
  1874. };
  1875. });
  1876. const syncer = createZCodeTaskIndexSyncer({
  1877. agentService: env.agent,
  1878. taskIndexRepo: env.repo,
  1879. });
  1880. const workspaceEvents: ZCodeWorkspaceEvent[] = [];
  1881. const terminalEvents: string[] = [];
  1882. const workspaceSubscription = syncer.onDynamicWorkspaceEvent({ workspacePath: "/repo" })(
  1883. (event) => workspaceEvents.push(event),
  1884. );
  1885. const terminalSubscription = syncer.onSessionTerminalEvent((event) =>
  1886. terminalEvents.push(event.target.sessionId),
  1887. );
  1888. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  1889. await vi.waitFor(() => expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1));
  1890. env.indexEmitter.fire({
  1891. ...indexSnapshotFrame([summaryOf(seedTarget.sessionId, "completedSuccess")]),
  1892. subscriptionId: "foreign-sub",
  1893. });
  1894. env.indexEmitter.fire(indexSnapshotFrame([summaryOf(seedTarget.sessionId, "running")]));
  1895. resolveIndex({
  1896. ack: {
  1897. subscriptionId: INDEX_SUBSCRIPTION_ID,
  1898. mode: "snapshot",
  1899. logEpoch: "epoch-test",
  1900. },
  1901. });
  1902. await new Promise((resolve) => setImmediate(resolve));
  1903. env.indexEmitter.fire(indexUpsertFrame(summaryOf(seedTarget.sessionId, "completedSuccess")));
  1904. await vi.waitFor(async () => {
  1905. const meta = await env.repo.getTaskMeta({
  1906. workspacePath: seedTarget.workspacePath,
  1907. taskId: seedTarget.sessionId,
  1908. });
  1909. expect(meta?.status).toBe("completed");
  1910. });
  1911. expect(terminalEvents).toEqual([seedTarget.sessionId]);
  1912. expect(workspaceEvents.some((event) => event.type === "workspace_config_options_update")).toBe(
  1913. true,
  1914. );
  1915. terminalSubscription.dispose();
  1916. workspaceSubscription.dispose();
  1917. syncer.disposeAll();
  1918. env.indexEmitter.dispose();
  1919. env.configEmitter.dispose();
  1920. });
  1921. it("physical sessions-index 分片在最后一片前不修改 task index,齐片后只 apply 一次", async () => {
  1922. const env = setupEnv({
  1923. initialSessions: [summaryOf(seedTarget.sessionId, "running")],
  1924. });
  1925. await seedRunningTask(env.repo);
  1926. const syncer = createZCodeTaskIndexSyncer({
  1927. agentService: env.agent,
  1928. taskIndexRepo: env.repo,
  1929. });
  1930. const terminalEvents: string[] = [];
  1931. const terminalSubscription = syncer.onSessionTerminalEvent((event) =>
  1932. terminalEvents.push(event.target.sessionId),
  1933. );
  1934. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  1935. await subscribed(env);
  1936. const logical = indexUpsertFrame(
  1937. summaryOf(seedTarget.sessionId, "completedSuccess", { title: "中文🙂".repeat(300) }),
  1938. );
  1939. const wires = encodeTopicWireFrames(logical, {
  1940. topic: logical.topic,
  1941. subscriptionId: logical.subscriptionId,
  1942. logicalFrameId: "logical-index-fragmented",
  1943. logicalFrameOrdinal: 1_000,
  1944. deliveryKind: "online",
  1945. maxPhysicalFrameBytes: 500,
  1946. measurePhysicalFrameBytes: utf8JsonByteLength,
  1947. }) as SessionsIndexTopicWireFrame[];
  1948. expect(wires.length).toBeGreaterThan(2);
  1949. for (const wire of wires.slice(0, -1)) {
  1950. env.indexEmitter.fireWire(wire);
  1951. }
  1952. await new Promise((resolve) => setImmediate(resolve));
  1953. expect(
  1954. (
  1955. await env.repo.getTaskMeta({
  1956. workspacePath: seedTarget.workspacePath,
  1957. taskId: seedTarget.sessionId,
  1958. })
  1959. )?.status,
  1960. ).toBe("running");
  1961. expect(terminalEvents).toEqual([]);
  1962. env.indexEmitter.fireWire(wires.at(-1)!);
  1963. await vi.waitFor(async () => {
  1964. expect(
  1965. (
  1966. await env.repo.getTaskMeta({
  1967. workspacePath: seedTarget.workspacePath,
  1968. taskId: seedTarget.sessionId,
  1969. })
  1970. )?.status,
  1971. ).toBe("completed");
  1972. });
  1973. expect(terminalEvents).toEqual([seedTarget.sessionId]);
  1974. terminalSubscription.dispose();
  1975. syncer.disposeAll();
  1976. env.indexEmitter.dispose();
  1977. env.configEmitter.dispose();
  1978. });
  1979. it("physical superseded fault 与 newer complete 同批出现时 task index fail closed", async () => {
  1980. const env = setupEnv({
  1981. initialSessions: [summaryOf(seedTarget.sessionId, "running")],
  1982. });
  1983. await seedRunningTask(env.repo);
  1984. const syncer = createZCodeTaskIndexSyncer({
  1985. agentService: env.agent,
  1986. taskIndexRepo: env.repo,
  1987. });
  1988. const terminalEvents: string[] = [];
  1989. const terminalSubscription = syncer.onSessionTerminalEvent((event) =>
  1990. terminalEvents.push(event.target.sessionId),
  1991. );
  1992. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  1993. await subscribed(env);
  1994. const oldLogical = indexUpsertFrame(
  1995. summaryOf(seedTarget.sessionId, "completedSuccess", { title: "old".repeat(500) }),
  1996. );
  1997. const oldWires = encodeTopicWireFrames(oldLogical, {
  1998. topic: oldLogical.topic,
  1999. subscriptionId: oldLogical.subscriptionId,
  2000. logicalFrameId: "logical-index-old-partial",
  2001. logicalFrameOrdinal: 1_000,
  2002. deliveryKind: "online",
  2003. maxPhysicalFrameBytes: 500,
  2004. measurePhysicalFrameBytes: utf8JsonByteLength,
  2005. }) as SessionsIndexTopicWireFrame[];
  2006. env.indexEmitter.fireWire(oldWires[0]!);
  2007. const newer = indexUpsertFrame(summaryOf(seedTarget.sessionId, "completedSuccess"));
  2008. env.indexEmitter.fireWire({
  2009. wireVersion: 3,
  2010. kind: "complete",
  2011. deliveryKind: "online",
  2012. logicalFrameId: "logical-index-newer",
  2013. logicalFrameOrdinal: 1_001,
  2014. topic: newer.topic,
  2015. subscriptionId: newer.subscriptionId,
  2016. frame: newer,
  2017. });
  2018. await new Promise((resolve) => setImmediate(resolve));
  2019. expect(
  2020. (
  2021. await env.repo.getTaskMeta({
  2022. workspacePath: seedTarget.workspacePath,
  2023. taskId: seedTarget.sessionId,
  2024. })
  2025. )?.status,
  2026. ).toBe("running");
  2027. expect(terminalEvents).toEqual([]);
  2028. terminalSubscription.dispose();
  2029. syncer.disposeAll();
  2030. env.indexEmitter.dispose();
  2031. env.configEmitter.dispose();
  2032. });
  2033. it("stale subscribe ACK cannot replace the new generation and is unsubscribed", async () => {
  2034. const env = setupEnv();
  2035. await seedRunningTask(env.repo);
  2036. const restartEmitter = new Emitter<{ workspaceKey: string }>();
  2037. (env.agent as { onAgentRuntimeRestarted?: unknown }).onAgentRuntimeRestarted =
  2038. restartEmitter.event;
  2039. const resolvers: Array<(result: IndexSubscribeResult) => void> = [];
  2040. vi.mocked(env.agent.subscribeSessionsIndexV4).mockImplementation(
  2041. () => new Promise((resolve) => resolvers.push(resolve)),
  2042. );
  2043. const syncer = createZCodeTaskIndexSyncer({
  2044. agentService: env.agent,
  2045. taskIndexRepo: env.repo,
  2046. });
  2047. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2048. await vi.waitFor(() => expect(resolvers).toHaveLength(1));
  2049. env.indexEmitter.fire(indexSnapshotFrame([summaryOf(seedTarget.sessionId, "running")]));
  2050. restartEmitter.fire({ workspaceKey: "/repo" });
  2051. await vi.waitFor(() => expect(resolvers).toHaveLength(2));
  2052. env.indexEmitter.fire({
  2053. ...indexSnapshotFrame([summaryOf(seedTarget.sessionId, "running")]),
  2054. subscriptionId: "six-test-2",
  2055. });
  2056. resolvers[1]!({
  2057. ack: {
  2058. subscriptionId: "six-test-2",
  2059. mode: "snapshot",
  2060. logEpoch: "epoch-test-2",
  2061. },
  2062. });
  2063. await new Promise((resolve) => setImmediate(resolve));
  2064. resolvers[0]!({
  2065. ack: {
  2066. subscriptionId: INDEX_SUBSCRIPTION_ID,
  2067. mode: "snapshot",
  2068. logEpoch: "epoch-test",
  2069. },
  2070. });
  2071. await vi.waitFor(() =>
  2072. expect(env.agent.unsubscribeSessionsIndexV4).toHaveBeenCalledWith(
  2073. expect.objectContaining({ subscriptionId: INDEX_SUBSCRIPTION_ID }),
  2074. ),
  2075. );
  2076. env.indexEmitter.fire({
  2077. ...indexUpsertFrame(summaryOf(seedTarget.sessionId, "completedSuccess")),
  2078. subscriptionId: "six-test-2",
  2079. });
  2080. await vi.waitFor(async () => {
  2081. const meta = await env.repo.getTaskMeta({
  2082. workspacePath: seedTarget.workspacePath,
  2083. taskId: seedTarget.sessionId,
  2084. });
  2085. expect(meta?.status).toBe("completed");
  2086. });
  2087. syncer.disposeAll();
  2088. restartEmitter.dispose();
  2089. env.indexEmitter.dispose();
  2090. env.configEmitter.dispose();
  2091. });
  2092. it("dispose clears staged frames and unsubscribes ACKs that resolve after close", async () => {
  2093. const env = setupEnv();
  2094. let resolveIndex!: (result: IndexSubscribeResult) => void;
  2095. vi.mocked(env.agent.subscribeSessionsIndexV4).mockImplementationOnce(
  2096. () => new Promise((resolve) => (resolveIndex = resolve)),
  2097. );
  2098. const syncer = createZCodeTaskIndexSyncer({
  2099. agentService: env.agent,
  2100. taskIndexRepo: env.repo,
  2101. });
  2102. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2103. await vi.waitFor(() => expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1));
  2104. env.indexEmitter.fire(indexSnapshotFrame([summaryOf("staged-after-close", "running")]));
  2105. syncer.disposeAll();
  2106. resolveIndex({
  2107. ack: {
  2108. subscriptionId: INDEX_SUBSCRIPTION_ID,
  2109. mode: "snapshot",
  2110. logEpoch: "epoch-test",
  2111. },
  2112. });
  2113. await vi.waitFor(() => {
  2114. expect(env.agent.unsubscribeSessionsIndexV4).toHaveBeenCalledWith(
  2115. expect.objectContaining({ subscriptionId: INDEX_SUBSCRIPTION_ID }),
  2116. );
  2117. expect(env.agent.unsubscribeWorkspaceConfigV4).toHaveBeenCalledWith(
  2118. expect.objectContaining({ subscriptionId: CONFIG_SUBSCRIPTION_ID }),
  2119. );
  2120. });
  2121. env.indexEmitter.dispose();
  2122. env.configEmitter.dispose();
  2123. });
  2124. it("staging overflow 自动恢复且不会永久 freeze", async () => {
  2125. const env = setupEnv({
  2126. initialSessions: [summaryOf(seedTarget.sessionId, "running")],
  2127. });
  2128. await seedRunningTask(env.repo);
  2129. let resolveIndex!: (result: IndexSubscribeResult) => void;
  2130. vi.mocked(env.agent.subscribeSessionsIndexV4).mockImplementationOnce(
  2131. () => new Promise((resolve) => (resolveIndex = resolve)),
  2132. );
  2133. const syncer = createZCodeTaskIndexSyncer({
  2134. agentService: env.agent,
  2135. taskIndexRepo: env.repo,
  2136. });
  2137. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2138. await vi.waitFor(() => expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1));
  2139. for (let index = 0; index < 1_025; index += 1) {
  2140. env.indexEmitter.fire({
  2141. ...indexSnapshotFrame([summaryOf(seedTarget.sessionId, "running")]),
  2142. toSeq: index,
  2143. });
  2144. }
  2145. resolveIndex({
  2146. ack: {
  2147. subscriptionId: INDEX_SUBSCRIPTION_ID,
  2148. mode: "snapshot",
  2149. logEpoch: "epoch-test",
  2150. },
  2151. });
  2152. await new Promise((resolve) => setImmediate(resolve));
  2153. // pre-ACK overflow 没有可证明 base,必须仅换代 index topic 的 fresh snapshot。
  2154. await vi.waitFor(() => expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(2));
  2155. expect(env.agent.resyncSessionsIndexV4).not.toHaveBeenCalled();
  2156. expect(env.agent.subscribeWorkspaceConfigV4).toHaveBeenCalledTimes(1);
  2157. expect(env.agent.subscribeSessionsIndexV4).toHaveBeenLastCalledWith(
  2158. expect.objectContaining({
  2159. workspacePath: "/repo",
  2160. visibility: "background",
  2161. subscriberScope: "task-index",
  2162. runtimePolicy: "existing-only",
  2163. }),
  2164. );
  2165. env.indexEmitter.fire(indexUpsertFrame(summaryOf(seedTarget.sessionId, "completedSuccess"), 2));
  2166. await vi.waitFor(async () => {
  2167. const meta = await env.repo.getTaskMeta({
  2168. workspacePath: seedTarget.workspacePath,
  2169. taskId: seedTarget.sessionId,
  2170. });
  2171. expect(meta?.status).toBe("completed");
  2172. });
  2173. syncer.disposeAll();
  2174. env.indexEmitter.dispose();
  2175. env.configEmitter.dispose();
  2176. });
  2177. it("sessions-index initial assembly fault 不拿 ACK epoch 伪造 base,强制恢复冷 baseline", async () => {
  2178. const cold = summaryOf(seedTarget.sessionId, "running");
  2179. const env = setupEnv();
  2180. await seedRunningTask(env.repo);
  2181. vi.mocked(env.agent.subscribeSessionsIndexV4).mockImplementationOnce(async () => {
  2182. // ACK 前到达但 logical payload 非法:activation 后 assembler 产 typed fault,
  2183. // 这时客户端尚未原子 apply 任何 snapshot,ACK 本身不能证明 base=(epoch,0)。
  2184. env.indexEmitter.fire(
  2185. {
  2186. topic: "sessions-index//repo",
  2187. subscriptionId: INDEX_SUBSCRIPTION_ID,
  2188. fromSeq: 0,
  2189. toSeq: 0,
  2190. sentAt: 1,
  2191. payload: { kind: "deltas", deltas: [{ op: "invalid" }] },
  2192. } as unknown as SessionsIndexTopicFrame,
  2193. "initial",
  2194. );
  2195. return {
  2196. ack: {
  2197. subscriptionId: INDEX_SUBSCRIPTION_ID,
  2198. mode: "snapshot" as const,
  2199. logEpoch: "epoch-test",
  2200. },
  2201. };
  2202. });
  2203. let releaseRecovery!: () => void;
  2204. vi.mocked(env.agent.resyncSessionsIndexV4).mockImplementationOnce(
  2205. (params) =>
  2206. new Promise<IndexResyncResult>((resolve) => {
  2207. releaseRecovery = () => {
  2208. env.indexEmitter.fire(indexSnapshotFrame([cold], 1), "recovery");
  2209. resolve({
  2210. ack: {
  2211. subscriptionId: params.subscriptionId,
  2212. mode: "snapshot",
  2213. logEpoch: "epoch-test",
  2214. },
  2215. });
  2216. };
  2217. }),
  2218. );
  2219. const syncer = createZCodeTaskIndexSyncer({
  2220. agentService: env.agent,
  2221. taskIndexRepo: env.repo,
  2222. });
  2223. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2224. await vi.waitFor(() =>
  2225. expect(env.agent.resyncSessionsIndexV4).toHaveBeenCalledWith(
  2226. expect.objectContaining({
  2227. workspacePath: "/repo",
  2228. subscriptionId: INDEX_SUBSCRIPTION_ID,
  2229. base: null,
  2230. forceSnapshot: true,
  2231. }),
  2232. ),
  2233. );
  2234. // 整个 initial batch 丢失后,数值上衔接的 online delta 也不能抢先建立 baseline。
  2235. env.indexEmitter.fire(indexUpsertFrame(summaryOf(seedTarget.sessionId, "completedSuccess"), 1));
  2236. await new Promise((resolve) => setImmediate(resolve));
  2237. expect(
  2238. (
  2239. await env.repo.getTaskMeta({
  2240. workspacePath: seedTarget.workspacePath,
  2241. taskId: seedTarget.sessionId,
  2242. })
  2243. )?.status,
  2244. ).toBe("running");
  2245. releaseRecovery();
  2246. await new Promise((resolve) => setImmediate(resolve));
  2247. env.indexEmitter.fire(indexUpsertFrame(summaryOf(seedTarget.sessionId, "completedSuccess"), 2));
  2248. await vi.waitFor(async () => {
  2249. expect(
  2250. (
  2251. await env.repo.getTaskMeta({
  2252. workspacePath: seedTarget.workspacePath,
  2253. taskId: seedTarget.sessionId,
  2254. })
  2255. )?.status,
  2256. ).toBe("completed");
  2257. });
  2258. syncer.disposeAll();
  2259. env.indexEmitter.dispose();
  2260. env.configEmitter.dispose();
  2261. });
  2262. it("workspace-config initial assembly fault 仅以已 apply 状态为 base", async () => {
  2263. const env = setupEnv();
  2264. const recoveredConfig: WorkspaceConfigState = {
  2265. configOptions: [
  2266. {
  2267. id: "model",
  2268. name: "Model",
  2269. type: "select",
  2270. currentValue: "anthropic/haiku",
  2271. options: [],
  2272. },
  2273. ],
  2274. slashCommands: [],
  2275. };
  2276. vi.mocked(env.agent.subscribeWorkspaceConfigV4).mockImplementationOnce(async () => {
  2277. env.configEmitter.fire(
  2278. {
  2279. topic: "workspace-config//repo",
  2280. subscriptionId: CONFIG_SUBSCRIPTION_ID,
  2281. fromSeq: 0,
  2282. toSeq: 0,
  2283. sentAt: 1,
  2284. payload: { kind: "deltas", deltas: [{ op: "invalid" }] },
  2285. } as unknown as WorkspaceConfigTopicFrame,
  2286. "initial",
  2287. );
  2288. return {
  2289. ack: {
  2290. subscriptionId: CONFIG_SUBSCRIPTION_ID,
  2291. mode: "snapshot" as const,
  2292. logEpoch: "epoch-cfg",
  2293. },
  2294. };
  2295. });
  2296. vi.mocked(env.agent.resyncWorkspaceConfigV4).mockImplementationOnce(async (params) => {
  2297. if (params.forceSnapshot) {
  2298. env.configEmitter.fire(configFrame(recoveredConfig, 1), "recovery");
  2299. } else {
  2300. env.configEmitter.fire(
  2301. {
  2302. topic: "workspace-config//repo",
  2303. subscriptionId: CONFIG_SUBSCRIPTION_ID,
  2304. fromSeq: 0,
  2305. toSeq: 0,
  2306. sentAt: 2,
  2307. payload: { kind: "deltas", deltas: [] },
  2308. },
  2309. "recovery",
  2310. );
  2311. }
  2312. return {
  2313. ack: {
  2314. subscriptionId: params.subscriptionId,
  2315. mode: params.forceSnapshot ? ("snapshot" as const) : ("resume" as const),
  2316. logEpoch: "epoch-cfg",
  2317. },
  2318. };
  2319. });
  2320. const syncer = createZCodeTaskIndexSyncer({
  2321. agentService: env.agent,
  2322. taskIndexRepo: env.repo,
  2323. });
  2324. const workspaceEvents: ZCodeWorkspaceEvent[] = [];
  2325. syncer.onDynamicWorkspaceEvent({ workspacePath: "/repo" })((event) =>
  2326. workspaceEvents.push(event),
  2327. );
  2328. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2329. await vi.waitFor(() =>
  2330. expect(env.agent.resyncWorkspaceConfigV4).toHaveBeenCalledWith(
  2331. expect.objectContaining({
  2332. workspacePath: "/repo",
  2333. subscriptionId: CONFIG_SUBSCRIPTION_ID,
  2334. base: null,
  2335. forceSnapshot: true,
  2336. }),
  2337. ),
  2338. );
  2339. await vi.waitFor(() =>
  2340. expect(
  2341. workspaceEvents.some(
  2342. (event) =>
  2343. event.type === "workspace_config_options_update" &&
  2344. event.configOptions[0]?.currentValue === "anthropic/haiku",
  2345. ),
  2346. ).toBe(true),
  2347. );
  2348. syncer.disposeAll();
  2349. env.indexEmitter.dispose();
  2350. env.configEmitter.dispose();
  2351. });
  2352. it("sessions-index gap 只恢复 index,workspace-config sibling 保持可用", async () => {
  2353. const env = setupEnv({
  2354. initialSessions: [summaryOf(seedTarget.sessionId, "running")],
  2355. });
  2356. await seedRunningTask(env.repo);
  2357. const syncer = createZCodeTaskIndexSyncer({
  2358. agentService: env.agent,
  2359. taskIndexRepo: env.repo,
  2360. });
  2361. const workspaceEvents: ZCodeWorkspaceEvent[] = [];
  2362. syncer.onDynamicWorkspaceEvent({ workspacePath: "/repo" })((event) =>
  2363. workspaceEvents.push(event),
  2364. );
  2365. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2366. await subscribed(env);
  2367. env.indexEmitter.fire(
  2368. indexUpsertFrame(summaryOf(seedTarget.sessionId, "completedSuccess"), 99),
  2369. );
  2370. await vi.waitFor(() => expect(env.agent.resyncSessionsIndexV4).toHaveBeenCalledTimes(1));
  2371. expect(env.agent.resyncWorkspaceConfigV4).not.toHaveBeenCalled();
  2372. expect(env.agent.subscribeWorkspaceConfigV4).toHaveBeenCalledTimes(1);
  2373. env.configEmitter.fire(
  2374. configFrame({
  2375. configOptions: [
  2376. {
  2377. id: "model",
  2378. name: "Model",
  2379. category: "model",
  2380. type: "select",
  2381. currentValue: "anthropic/haiku",
  2382. options: [],
  2383. },
  2384. ],
  2385. slashCommands: [],
  2386. }),
  2387. );
  2388. await vi.waitFor(() =>
  2389. expect(
  2390. workspaceEvents.some((event) => event.type === "workspace_config_options_update"),
  2391. ).toBe(true),
  2392. );
  2393. syncer.disposeAll();
  2394. env.indexEmitter.dispose();
  2395. env.configEmitter.dispose();
  2396. });
  2397. it("recovery assembly fault 早于 snapshot ACK 时 fresh-subscribe index 而不悬空 flight", async () => {
  2398. const env = setupEnv({
  2399. initialSessions: [summaryOf(seedTarget.sessionId, "running")],
  2400. });
  2401. let resolveResync!: (result: IndexResyncResult) => void;
  2402. vi.mocked(env.agent.resyncSessionsIndexV4).mockImplementationOnce(
  2403. () => new Promise((resolve) => (resolveResync = resolve)),
  2404. );
  2405. const syncer = createZCodeTaskIndexSyncer({
  2406. agentService: env.agent,
  2407. taskIndexRepo: env.repo,
  2408. });
  2409. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2410. await subscribed(env);
  2411. // online gap 启动 same-sub recovery。
  2412. env.indexEmitter.fire(indexUpsertFrame(summaryOf(seedTarget.sessionId, "running"), 99));
  2413. await vi.waitFor(() => expect(env.agent.resyncSessionsIndexV4).toHaveBeenCalledTimes(1));
  2414. // 同 ordinal 不同 logical id 产生 typed fault;deliveryKind 在 fault.fault 层。
  2415. const invalidRecoveryFrame = indexUpsertFrame(
  2416. summaryOf(seedTarget.sessionId, "completedSuccess"),
  2417. 100,
  2418. );
  2419. env.indexEmitter.fireWire({
  2420. wireVersion: 3,
  2421. kind: "complete",
  2422. deliveryKind: "recovery",
  2423. logicalFrameId: "conflicting-recovery-id",
  2424. logicalFrameOrdinal: 2,
  2425. topic: invalidRecoveryFrame.topic,
  2426. subscriptionId: invalidRecoveryFrame.subscriptionId,
  2427. frame: invalidRecoveryFrame,
  2428. });
  2429. resolveResync({
  2430. ack: {
  2431. subscriptionId: INDEX_SUBSCRIPTION_ID,
  2432. mode: "snapshot",
  2433. logEpoch: "epoch-test",
  2434. },
  2435. });
  2436. await vi.waitFor(() => expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(2));
  2437. expect(env.agent.subscribeWorkspaceConfigV4).toHaveBeenCalledTimes(1);
  2438. syncer.disposeAll();
  2439. env.indexEmitter.dispose();
  2440. env.configEmitter.dispose();
  2441. });
  2442. it("recovery flight 中缺失 deliveryKind 的 owned fault 会升级强制 snapshot", async () => {
  2443. const env = setupEnv({
  2444. initialSessions: [summaryOf(seedTarget.sessionId, "running")],
  2445. });
  2446. const syncer = createZCodeTaskIndexSyncer({
  2447. agentService: env.agent,
  2448. taskIndexRepo: env.repo,
  2449. });
  2450. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2451. await subscribed(env);
  2452. env.indexEmitter.fire(indexUpsertFrame(summaryOf(seedTarget.sessionId, "running"), 99));
  2453. await vi.waitFor(() => expect(env.agent.resyncSessionsIndexV4).toHaveBeenCalledTimes(1));
  2454. const invalid = indexUpsertFrame(summaryOf(seedTarget.sessionId, "running"), 100);
  2455. env.indexEmitter.fireWire({
  2456. wireVersion: 3,
  2457. kind: "complete",
  2458. // candidate 允许先进 owned assembler 再产生 typed fault;此处故意伪造非法值。
  2459. deliveryKind: "invalid-kind",
  2460. logicalFrameId: "invalid-delivery-kind",
  2461. logicalFrameOrdinal: 3,
  2462. topic: invalid.topic,
  2463. subscriptionId: invalid.subscriptionId,
  2464. frame: invalid,
  2465. } as unknown as SessionsIndexTopicWireFrame);
  2466. await vi.waitFor(() => expect(env.agent.resyncSessionsIndexV4).toHaveBeenCalledTimes(2));
  2467. expect(vi.mocked(env.agent.resyncSessionsIndexV4).mock.calls[1]?.[0]).toMatchObject({
  2468. subscriptionId: INDEX_SUBSCRIPTION_ID,
  2469. base: null,
  2470. forceSnapshot: true,
  2471. });
  2472. syncer.disposeAll();
  2473. env.indexEmitter.dispose();
  2474. env.configEmitter.dispose();
  2475. });
  2476. it("workspace-config recovery gap 早于 snapshot ACK 时仅 fresh-subscribe config", async () => {
  2477. const env = setupEnv();
  2478. let resolveResync!: (result: ConfigResyncResult) => void;
  2479. vi.mocked(env.agent.resyncWorkspaceConfigV4).mockImplementationOnce(
  2480. () => new Promise((resolve) => (resolveResync = resolve)),
  2481. );
  2482. const syncer = createZCodeTaskIndexSyncer({
  2483. agentService: env.agent,
  2484. taskIndexRepo: env.repo,
  2485. });
  2486. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2487. await subscribed(env);
  2488. const config: WorkspaceConfigState = {
  2489. configOptions: [
  2490. {
  2491. id: "model",
  2492. name: "Model",
  2493. type: "select",
  2494. currentValue: "anthropic/haiku",
  2495. options: [],
  2496. },
  2497. ],
  2498. slashCommands: [],
  2499. };
  2500. env.configEmitter.fire(configFrame(config));
  2501. env.configEmitter.fire(configDeltaFrame(config, 99));
  2502. await vi.waitFor(() => expect(env.agent.resyncWorkspaceConfigV4).toHaveBeenCalledTimes(1));
  2503. env.configEmitter.fire(configDeltaFrame(config, 100), "recovery");
  2504. resolveResync({
  2505. ack: {
  2506. subscriptionId: CONFIG_SUBSCRIPTION_ID,
  2507. mode: "snapshot",
  2508. logEpoch: "epoch-cfg",
  2509. },
  2510. });
  2511. await vi.waitFor(() => expect(env.agent.subscribeWorkspaceConfigV4).toHaveBeenCalledTimes(2));
  2512. expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  2513. syncer.disposeAll();
  2514. env.indexEmitter.dispose();
  2515. env.configEmitter.dispose();
  2516. });
  2517. it("sessions-index duplicate delta 静默丢弃且不重复发射 terminal", async () => {
  2518. const env = setupEnv({
  2519. initialSessions: [summaryOf(seedTarget.sessionId, "running")],
  2520. });
  2521. await seedRunningTask(env.repo);
  2522. const syncer = createZCodeTaskIndexSyncer({
  2523. agentService: env.agent,
  2524. taskIndexRepo: env.repo,
  2525. });
  2526. const terminals: string[] = [];
  2527. syncer.onSessionTerminalEvent((event) => terminals.push(event.kind));
  2528. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2529. await subscribed(env);
  2530. env.indexEmitter.fire(indexUpsertFrame(summaryOf(seedTarget.sessionId, "completedSuccess"), 2));
  2531. await vi.waitFor(() => expect(terminals).toEqual(["turn.completed"]));
  2532. env.indexEmitter.fire(indexUpsertFrame(summaryOf(seedTarget.sessionId, "error"), 2));
  2533. await new Promise((resolve) => setImmediate(resolve));
  2534. expect(terminals).toEqual(["turn.completed"]);
  2535. expect(env.agent.resyncSessionsIndexV4).not.toHaveBeenCalled();
  2536. syncer.disposeAll();
  2537. env.indexEmitter.dispose();
  2538. env.configEmitter.dispose();
  2539. });
  2540. it("sessions-index recovery 后同 read residual online gap 启动 successor", async () => {
  2541. const env = setupEnv({
  2542. initialSessions: [summaryOf(seedTarget.sessionId, "running")],
  2543. });
  2544. await seedRunningTask(env.repo);
  2545. let attempt = 0;
  2546. vi.mocked(env.agent.resyncSessionsIndexV4).mockImplementation(async (params) => {
  2547. attempt += 1;
  2548. if (attempt === 1) {
  2549. env.indexEmitter.fire(
  2550. indexUpsertFrame(summaryOf(seedTarget.sessionId, "completedSuccess"), 2),
  2551. "recovery",
  2552. );
  2553. env.indexEmitter.fire(
  2554. indexUpsertFrame(summaryOf(seedTarget.sessionId, "completedSuccess"), 4),
  2555. "online",
  2556. );
  2557. } else {
  2558. env.indexEmitter.fire(
  2559. {
  2560. topic: "sessions-index//repo",
  2561. subscriptionId: INDEX_SUBSCRIPTION_ID,
  2562. fromSeq: 2,
  2563. toSeq: 2,
  2564. sentAt: 4,
  2565. payload: { kind: "deltas", deltas: [] },
  2566. },
  2567. "recovery",
  2568. );
  2569. }
  2570. return {
  2571. ack: {
  2572. subscriptionId: params.subscriptionId,
  2573. mode: "resume" as const,
  2574. logEpoch: "epoch-test",
  2575. },
  2576. };
  2577. });
  2578. const syncer = createZCodeTaskIndexSyncer({
  2579. agentService: env.agent,
  2580. taskIndexRepo: env.repo,
  2581. });
  2582. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2583. await subscribed(env);
  2584. env.indexEmitter.fire(indexUpsertFrame(summaryOf(seedTarget.sessionId, "completedSuccess"), 3));
  2585. await vi.waitFor(async () => {
  2586. expect(env.agent.resyncSessionsIndexV4).toHaveBeenCalledTimes(2);
  2587. expect(
  2588. (
  2589. await env.repo.getTaskMeta({
  2590. workspacePath: seedTarget.workspacePath,
  2591. taskId: seedTarget.sessionId,
  2592. })
  2593. )?.status,
  2594. ).toBe("completed");
  2595. });
  2596. expect(vi.mocked(env.agent.resyncSessionsIndexV4).mock.calls[1]?.[0]).toMatchObject({
  2597. subscriptionId: INDEX_SUBSCRIPTION_ID,
  2598. base: { logEpoch: "epoch-test", seq: 2 },
  2599. });
  2600. expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  2601. syncer.disposeAll();
  2602. env.indexEmitter.dispose();
  2603. env.configEmitter.dispose();
  2604. });
  2605. it("workspace-config recovery 后 residual online gap 只启动 config successor", async () => {
  2606. const env = setupEnv();
  2607. const config: WorkspaceConfigState = {
  2608. configOptions: [
  2609. {
  2610. id: "model",
  2611. name: "Model",
  2612. type: "select",
  2613. currentValue: "anthropic/haiku",
  2614. options: [],
  2615. },
  2616. ],
  2617. slashCommands: [],
  2618. };
  2619. let attempt = 0;
  2620. vi.mocked(env.agent.resyncWorkspaceConfigV4).mockImplementation(async (params) => {
  2621. attempt += 1;
  2622. if (attempt === 1) {
  2623. env.configEmitter.fire(configDeltaFrame(config, 2), "recovery");
  2624. env.configEmitter.fire(configDeltaFrame(config, 4), "online");
  2625. } else {
  2626. env.configEmitter.fire(
  2627. {
  2628. topic: "workspace-config//repo",
  2629. subscriptionId: CONFIG_SUBSCRIPTION_ID,
  2630. fromSeq: 2,
  2631. toSeq: 2,
  2632. sentAt: 5,
  2633. payload: { kind: "deltas", deltas: [] },
  2634. },
  2635. "recovery",
  2636. );
  2637. }
  2638. return {
  2639. ack: { subscriptionId: params.subscriptionId, mode: "resume", logEpoch: "epoch-cfg" },
  2640. };
  2641. });
  2642. const syncer = createZCodeTaskIndexSyncer({
  2643. agentService: env.agent,
  2644. taskIndexRepo: env.repo,
  2645. });
  2646. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2647. await subscribed(env);
  2648. env.configEmitter.fire(configFrame(config, 1));
  2649. env.configEmitter.fire(configDeltaFrame(config, 3));
  2650. await vi.waitFor(() => expect(env.agent.resyncWorkspaceConfigV4).toHaveBeenCalledTimes(2));
  2651. expect(vi.mocked(env.agent.resyncWorkspaceConfigV4).mock.calls[1]?.[0]).toMatchObject({
  2652. subscriptionId: CONFIG_SUBSCRIPTION_ID,
  2653. base: { logEpoch: "epoch-cfg", seq: 2 },
  2654. });
  2655. expect(env.agent.resyncSessionsIndexV4).not.toHaveBeenCalled();
  2656. syncer.disposeAll();
  2657. env.indexEmitter.dispose();
  2658. env.configEmitter.dispose();
  2659. });
  2660. it("online snapshot 覆盖在途 recovery 后,重复 recovery 可正常收口", async () => {
  2661. const env = setupEnv({
  2662. initialSessions: [summaryOf(seedTarget.sessionId, "running")],
  2663. });
  2664. let resolveRecovery!: (result: IndexResyncResult) => void;
  2665. vi.mocked(env.agent.resyncSessionsIndexV4).mockImplementationOnce(
  2666. () => new Promise((resolve) => (resolveRecovery = resolve)),
  2667. );
  2668. const syncer = createZCodeTaskIndexSyncer({
  2669. agentService: env.agent,
  2670. taskIndexRepo: env.repo,
  2671. });
  2672. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2673. await subscribed(env);
  2674. env.indexEmitter.fire(indexUpsertFrame(summaryOf(seedTarget.sessionId, "running"), 3));
  2675. await vi.waitFor(() => expect(env.agent.resyncSessionsIndexV4).toHaveBeenCalledTimes(1));
  2676. env.indexEmitter.fire(indexSnapshotFrame([summaryOf(seedTarget.sessionId, "running")], 5));
  2677. env.indexEmitter.fire(
  2678. {
  2679. topic: "sessions-index//repo",
  2680. subscriptionId: INDEX_SUBSCRIPTION_ID,
  2681. fromSeq: 1,
  2682. toSeq: 5,
  2683. sentAt: 5,
  2684. payload: {
  2685. kind: "deltas",
  2686. deltas: [{ op: "session.upserted", session: summaryOf(seedTarget.sessionId, "running") }],
  2687. },
  2688. },
  2689. "recovery",
  2690. );
  2691. resolveRecovery({
  2692. ack: { subscriptionId: INDEX_SUBSCRIPTION_ID, mode: "resume", logEpoch: "epoch-test" },
  2693. });
  2694. await new Promise((resolve) => setImmediate(resolve));
  2695. expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  2696. expect(env.agent.resyncSessionsIndexV4).toHaveBeenCalledTimes(1);
  2697. syncer.disposeAll();
  2698. env.indexEmitter.dispose();
  2699. env.configEmitter.dispose();
  2700. });
  2701. it("index/config recovery ACK 后零 wire:30s 强制一次,再超时 topic-local fresh", async () => {
  2702. const env = setupEnv({
  2703. initialSessions: [summaryOf(seedTarget.sessionId, "running")],
  2704. });
  2705. const config: WorkspaceConfigState = {
  2706. configOptions: [
  2707. { id: "model", name: "Model", type: "select", currentValue: "m", options: [] },
  2708. ],
  2709. slashCommands: [],
  2710. };
  2711. const syncer = createZCodeTaskIndexSyncer({
  2712. agentService: env.agent,
  2713. taskIndexRepo: env.repo,
  2714. });
  2715. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2716. await subscribed(env);
  2717. env.configEmitter.fire(configFrame(config, 1));
  2718. vi.useFakeTimers();
  2719. try {
  2720. env.indexEmitter.fire(indexUpsertFrame(summaryOf(seedTarget.sessionId, "running"), 99));
  2721. env.configEmitter.fire(configDeltaFrame(config, 99));
  2722. await Promise.resolve();
  2723. await Promise.resolve();
  2724. expect(env.agent.resyncSessionsIndexV4).toHaveBeenCalledTimes(1);
  2725. expect(env.agent.resyncWorkspaceConfigV4).toHaveBeenCalledTimes(1);
  2726. await vi.advanceTimersByTimeAsync(PROTOCOL_V4_LIMITS.logicalFrameAssemblyTimeoutMs);
  2727. expect(env.agent.resyncSessionsIndexV4).toHaveBeenCalledTimes(2);
  2728. expect(env.agent.resyncWorkspaceConfigV4).toHaveBeenCalledTimes(2);
  2729. expect(vi.mocked(env.agent.resyncSessionsIndexV4).mock.calls[1]?.[0]).toMatchObject({
  2730. forceSnapshot: true,
  2731. });
  2732. expect(vi.mocked(env.agent.resyncWorkspaceConfigV4).mock.calls[1]?.[0]).toMatchObject({
  2733. forceSnapshot: true,
  2734. });
  2735. await vi.advanceTimersByTimeAsync(PROTOCOL_V4_LIMITS.logicalFrameAssemblyTimeoutMs);
  2736. expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(2);
  2737. expect(env.agent.subscribeWorkspaceConfigV4).toHaveBeenCalledTimes(2);
  2738. } finally {
  2739. syncer.disposeAll();
  2740. vi.useRealTimers();
  2741. env.indexEmitter.dispose();
  2742. env.configEmitter.dispose();
  2743. }
  2744. });
  2745. it("provider/model 未就绪时不写 warn,低频探测后自动恢复两个 topic", async () => {
  2746. const env = setupEnv();
  2747. const providerNotReadyError = Object.assign(
  2748. new Error("当前没有可用的模型供应商和模型,请先登录或配置 API Key。"),
  2749. { code: ZCODE_AGENT_PROVIDER_NOT_READY_CODE },
  2750. );
  2751. vi.mocked(env.agent.subscribeSessionsIndexV4).mockRejectedValueOnce(providerNotReadyError);
  2752. vi.mocked(env.agent.subscribeWorkspaceConfigV4).mockRejectedValueOnce(providerNotReadyError);
  2753. const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined);
  2754. const syncer = createZCodeTaskIndexSyncer({
  2755. agentService: env.agent,
  2756. taskIndexRepo: env.repo,
  2757. });
  2758. vi.useFakeTimers();
  2759. try {
  2760. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2761. await vi.advanceTimersByTimeAsync(0);
  2762. expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  2763. expect(env.agent.subscribeWorkspaceConfigV4).toHaveBeenCalledTimes(1);
  2764. expect(warnSpy).not.toHaveBeenCalled();
  2765. await vi.advanceTimersByTimeAsync(4_999);
  2766. expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  2767. expect(env.agent.subscribeWorkspaceConfigV4).toHaveBeenCalledTimes(1);
  2768. await vi.advanceTimersByTimeAsync(1);
  2769. expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(2);
  2770. expect(env.agent.subscribeWorkspaceConfigV4).toHaveBeenCalledTimes(2);
  2771. expect(warnSpy).not.toHaveBeenCalled();
  2772. } finally {
  2773. syncer.disposeAll();
  2774. vi.useRealTimers();
  2775. warnSpy.mockRestore();
  2776. env.indexEmitter.dispose();
  2777. env.configEmitter.dispose();
  2778. }
  2779. });
  2780. it("持续订阅故障使用固定 retry reason,并将相同 topic 的 warn 限频到每分钟一次", async () => {
  2781. const env = setupEnv();
  2782. const persistentError = new Error("persistent topic failure");
  2783. vi.mocked(env.agent.subscribeSessionsIndexV4).mockRejectedValue(persistentError);
  2784. vi.mocked(env.agent.subscribeWorkspaceConfigV4).mockRejectedValue(persistentError);
  2785. const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined);
  2786. const syncer = createZCodeTaskIndexSyncer({
  2787. agentService: env.agent,
  2788. taskIndexRepo: env.repo,
  2789. });
  2790. vi.useFakeTimers();
  2791. try {
  2792. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2793. await vi.advanceTimersByTimeAsync(0);
  2794. expect(warnSpy).toHaveBeenCalledTimes(2);
  2795. await vi.advanceTimersByTimeAsync(59_999);
  2796. expect(warnSpy).toHaveBeenCalledTimes(2);
  2797. await vi.advanceTimersByTimeAsync(1_000);
  2798. expect(warnSpy).toHaveBeenCalledTimes(4);
  2799. const messages = warnSpy.mock.calls.map((call) => String(call[1]));
  2800. expect(messages.filter((message) => message.includes("reason=initial"))).toHaveLength(2);
  2801. expect(messages.filter((message) => message.includes("reason=retry"))).toHaveLength(2);
  2802. expect(messages.every((message) => !message.includes("retry:retry"))).toBe(true);
  2803. } finally {
  2804. syncer.disposeAll();
  2805. vi.useRealTimers();
  2806. warnSpy.mockRestore();
  2807. env.indexEmitter.dispose();
  2808. env.configEmitter.dispose();
  2809. }
  2810. });
  2811. // M5 ③-2(CLI 重连重订):进程换代后订阅静默失活,syncer 必须重发 subscribe
  2812. // 并按新 subscriptionId 闸门继续摄入帧。
  2813. it("re-subscribes workspace topics after an agent runtime restart and accepts new-generation frames", async () => {
  2814. const env = setupEnv({
  2815. initialSessions: [summaryOf(seedTarget.sessionId, "running")],
  2816. });
  2817. await seedRunningTask(env.repo);
  2818. const restartEmitter = new Emitter<{ workspaceKey: string }>();
  2819. (env.agent as { onAgentRuntimeRestarted?: unknown }).onAgentRuntimeRestarted =
  2820. restartEmitter.event;
  2821. // 第二代订阅换 id:重启后旧 id 的帧必须被闸门丢弃,新 id 的帧被接受。
  2822. vi.mocked(env.agent.subscribeSessionsIndexV4)
  2823. .mockImplementationOnce(async () => {
  2824. env.indexEmitter.fire(indexSnapshotFrame([summaryOf(seedTarget.sessionId, "running")]));
  2825. return {
  2826. ack: {
  2827. subscriptionId: INDEX_SUBSCRIPTION_ID,
  2828. mode: "snapshot" as const,
  2829. logEpoch: "epoch-test",
  2830. },
  2831. };
  2832. })
  2833. .mockImplementationOnce(async () => {
  2834. env.indexEmitter.fire({
  2835. ...indexSnapshotFrame([summaryOf(seedTarget.sessionId, "running")]),
  2836. subscriptionId: "six-test-2",
  2837. });
  2838. return {
  2839. ack: {
  2840. subscriptionId: "six-test-2",
  2841. mode: "snapshot" as const,
  2842. logEpoch: "epoch-test-2",
  2843. },
  2844. };
  2845. });
  2846. const syncer = createZCodeTaskIndexSyncer({
  2847. agentService: env.agent,
  2848. taskIndexRepo: env.repo,
  2849. });
  2850. syncer.ensureSessionSubscription(seedTarget);
  2851. await subscribed(env);
  2852. expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  2853. restartEmitter.fire({ workspaceKey: seedTarget.workspacePath });
  2854. await vi.waitFor(() => {
  2855. expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(2);
  2856. expect(env.agent.subscribeWorkspaceConfigV4).toHaveBeenCalledTimes(2);
  2857. });
  2858. await new Promise((resolve) => setImmediate(resolve));
  2859. // 新代际帧(新 subscriptionId)驱动终态写入。
  2860. env.indexEmitter.fire({
  2861. ...indexUpsertFrame(summaryOf(seedTarget.sessionId, "completedSuccess")),
  2862. subscriptionId: "six-test-2",
  2863. });
  2864. await vi.waitFor(async () => {
  2865. const meta = await env.repo.getTaskMeta({
  2866. workspacePath: seedTarget.workspacePath,
  2867. taskId: seedTarget.sessionId,
  2868. });
  2869. expect(meta?.status).toBe("completed");
  2870. });
  2871. syncer.disposeAll();
  2872. restartEmitter.dispose();
  2873. env.indexEmitter.dispose();
  2874. env.configEmitter.dispose();
  2875. });
  2876. it("runtime restart 后 sessions-index 暂态失败独立重试,config 不被撤销", async () => {
  2877. const env = setupEnv({
  2878. initialSessions: [summaryOf(seedTarget.sessionId, "running")],
  2879. });
  2880. const restartEmitter = new Emitter<{ workspaceKey: string }>();
  2881. (env.agent as { onAgentRuntimeRestarted?: unknown }).onAgentRuntimeRestarted =
  2882. restartEmitter.event;
  2883. vi.mocked(env.agent.subscribeSessionsIndexV4)
  2884. .mockImplementationOnce(async () => {
  2885. env.indexEmitter.fire(
  2886. indexSnapshotFrame([summaryOf(seedTarget.sessionId, "running")]),
  2887. "initial",
  2888. );
  2889. return {
  2890. ack: {
  2891. subscriptionId: INDEX_SUBSCRIPTION_ID,
  2892. mode: "snapshot" as const,
  2893. logEpoch: "epoch-test",
  2894. },
  2895. };
  2896. })
  2897. .mockRejectedValueOnce(new Error("transient restart failure"))
  2898. .mockImplementationOnce(async () => {
  2899. env.indexEmitter.fire(
  2900. {
  2901. ...indexSnapshotFrame([summaryOf(seedTarget.sessionId, "running")]),
  2902. subscriptionId: "six-test-3",
  2903. },
  2904. "initial",
  2905. );
  2906. return {
  2907. ack: {
  2908. subscriptionId: "six-test-3",
  2909. mode: "snapshot" as const,
  2910. logEpoch: "epoch-test-3",
  2911. },
  2912. };
  2913. });
  2914. const syncer = createZCodeTaskIndexSyncer({
  2915. agentService: env.agent,
  2916. taskIndexRepo: env.repo,
  2917. });
  2918. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2919. await subscribed(env);
  2920. restartEmitter.fire({ workspaceKey: "/repo" });
  2921. await vi.waitFor(() => {
  2922. expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(3);
  2923. expect(env.agent.subscribeWorkspaceConfigV4).toHaveBeenCalledTimes(2);
  2924. });
  2925. // config 一次就成功,不跟随 index retry 重订。
  2926. await new Promise((resolve) => setTimeout(resolve, 75));
  2927. expect(env.agent.subscribeWorkspaceConfigV4).toHaveBeenCalledTimes(2);
  2928. syncer.disposeAll();
  2929. restartEmitter.dispose();
  2930. env.indexEmitter.dispose();
  2931. env.configEmitter.dispose();
  2932. });
  2933. it("ignores ensureSessionSubscription after disposeAll", () => {
  2934. const env = setupEnv();
  2935. const syncer = createZCodeTaskIndexSyncer({
  2936. agentService: env.agent,
  2937. taskIndexRepo: env.repo,
  2938. });
  2939. syncer.disposeAll();
  2940. syncer.ensureSessionSubscription(seedTarget);
  2941. expect(env.agent.subscribeSessionsIndexV4).not.toHaveBeenCalled();
  2942. env.indexEmitter.dispose();
  2943. env.configEmitter.dispose();
  2944. });
  2945. it("shares the same workspace emitter across getWorkspaceEmitter and onDynamicWorkspaceEvent", () => {
  2946. const env = setupEnv();
  2947. const syncer = createZCodeTaskIndexSyncer({
  2948. agentService: env.agent,
  2949. taskIndexRepo: env.repo,
  2950. });
  2951. const received: ZCodeWorkspaceEvent[] = [];
  2952. const subscription = syncer.onDynamicWorkspaceEvent({
  2953. workspacePath: "/repo",
  2954. })((event) => received.push(event));
  2955. // adapter 通过 getWorkspaceEmitter 直接 fire 其他类型事件时,订阅者也应该能收到
  2956. syncer.getWorkspaceEmitter({ workspacePath: "/repo" }).fire({
  2957. type: "workspace_config_options_update",
  2958. workspacePath: "/repo",
  2959. configOptions: [],
  2960. } as ZCodeWorkspaceEvent);
  2961. expect(received.length).toBe(1);
  2962. expect(received[0].type).toBe("workspace_config_options_update");
  2963. subscription.dispose();
  2964. syncer.disposeAll();
  2965. });
  2966. });