zcodeTaskIndexSyncer.test.ts 112 KB

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