zcodeTaskIndexSyncer.test.ts 112 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334
  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("SAT29: 只清理明确属于当前 workspace 的 subagent 索引,保留 fork 与未确认记录", async () => {
  1013. const env = setupEnv();
  1014. for (const taskId of ["child", "fork", "unknown"]) {
  1015. await seedTaskIndex(env.repo, {
  1016. meta: {
  1017. ...snapshotWith(taskId, "/repo").session,
  1018. taskId,
  1019. traceId: "trace",
  1020. title: taskId,
  1021. workspacePath: "/repo",
  1022. createdAt: 1,
  1023. updatedAt: 2,
  1024. mode: "build",
  1025. provider: "glm",
  1026. status: "completed",
  1027. },
  1028. });
  1029. }
  1030. await seedTaskIndex(env.repo, {
  1031. meta: {
  1032. taskId: "child",
  1033. traceId: "trace",
  1034. title: "foreign",
  1035. workspacePath: "/repo",
  1036. workspaceIdentity: "remote:ssh:foreign:22:user:/repo",
  1037. createdAt: 1,
  1038. updatedAt: 2,
  1039. mode: "build",
  1040. provider: "glm",
  1041. status: "completed",
  1042. },
  1043. });
  1044. vi.mocked(env.agent.listSessions).mockResolvedValue([
  1045. { ...snapshotWith("child", "/repo").session, sessionKind: "subagent_child" },
  1046. { ...snapshotWith("fork", "/repo").session, sessionKind: "fork", parentSessionId: "parent" },
  1047. ]);
  1048. const syncer = createZCodeTaskIndexSyncer({ agentService: env.agent, taskIndexRepo: env.repo });
  1049. const changed = vi.fn();
  1050. const listener = syncer.onDynamicWorkspaceEvent("/repo")(changed);
  1051. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  1052. await vi.waitFor(async () =>
  1053. expect(await env.repo.getTaskMeta({ workspacePath: "/repo", taskId: "child" })).toBeNull(),
  1054. );
  1055. expect(await env.repo.getTaskMeta({ workspacePath: "/repo", taskId: "fork" })).not.toBeNull();
  1056. expect(
  1057. await env.repo.getTaskMeta({ workspacePath: "/repo", taskId: "unknown" }),
  1058. ).not.toBeNull();
  1059. expect(
  1060. await env.repo.getTaskMeta({
  1061. workspacePath: "/repo",
  1062. workspaceIdentity: "remote:ssh:foreign:22:user:/repo",
  1063. taskId: "child",
  1064. }),
  1065. ).not.toBeNull();
  1066. expect(env.agent.listSessions).toHaveBeenCalledWith(
  1067. expect.objectContaining({
  1068. workspacePath: "/repo",
  1069. sessionIds: expect.arrayContaining(["child", "fork", "unknown"]),
  1070. }),
  1071. );
  1072. expect(env.agent.resumeSession).not.toHaveBeenCalled();
  1073. expect(changed).toHaveBeenCalled();
  1074. listener.dispose();
  1075. syncer.disposeAll();
  1076. });
  1077. it.each(["failure", "disposed"] as const)(
  1078. "SAT29: 身份查询 %s 时保留既有索引",
  1079. async (failure) => {
  1080. const env = setupEnv();
  1081. await seedTaskIndex(env.repo, {
  1082. meta: { ...(await seedRunningTask(env.repo)), provider: "glm" },
  1083. });
  1084. let finish:
  1085. | ((value: Awaited<ReturnType<IZCodeAgentService["listSessions"]>>) => void)
  1086. | undefined;
  1087. vi.mocked(env.agent.listSessions).mockImplementation(() =>
  1088. failure === "failure"
  1089. ? Promise.reject(new Error("remote unavailable"))
  1090. : new Promise((resolve) => {
  1091. finish = resolve;
  1092. }),
  1093. );
  1094. const syncer = createZCodeTaskIndexSyncer({
  1095. agentService: env.agent,
  1096. taskIndexRepo: env.repo,
  1097. });
  1098. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  1099. await vi.waitFor(() => expect(env.agent.listSessions).toHaveBeenCalled());
  1100. syncer.disposeAll();
  1101. finish?.([
  1102. { ...snapshotWith(seedTarget.sessionId, "/repo").session, sessionKind: "subagent_child" },
  1103. ]);
  1104. await new Promise((resolve) => setImmediate(resolve));
  1105. expect(
  1106. await env.repo.getTaskMeta({ workspacePath: "/repo", taskId: seedTarget.sessionId }),
  1107. ).not.toBeNull();
  1108. },
  1109. );
  1110. it("SAT28: child 完整快照不重新写入主列表", async () => {
  1111. const env = setupEnv();
  1112. const syncer = createZCodeTaskIndexSyncer({ agentService: env.agent, taskIndexRepo: env.repo });
  1113. const snapshot = snapshotWith("child", "/repo", { userMessageText: "child prompt" });
  1114. snapshot.session.sessionKind = "subagent_child";
  1115. await syncer.syncSnapshotAndBroadcast(snapshot, { broadcastReason: "task_status_changed" });
  1116. expect(await env.repo.getTaskMeta({ workspacePath: "/repo", taskId: "child" })).toBeNull();
  1117. syncer.disposeAll();
  1118. });
  1119. it("does not overwrite existing product-shell state during initial snapshot reconciliation", async () => {
  1120. const env = setupEnv({
  1121. initialSessions: [
  1122. summaryOf("sess_existing", "completedSuccess", {
  1123. title: "Agent 标题",
  1124. titleSource: "generated",
  1125. lastActivityAt: 999,
  1126. }),
  1127. ],
  1128. });
  1129. await seedTaskIndex(env.repo, {
  1130. meta: {
  1131. taskId: "sess_existing",
  1132. traceId: "trace-existing",
  1133. title: "用户标题",
  1134. titleOverridden: true,
  1135. workspacePath: "/repo",
  1136. createdAt: 1,
  1137. updatedAt: 100,
  1138. mode: "build",
  1139. model: "anthropic/haiku-4.5",
  1140. provider: "glm",
  1141. status: "completed",
  1142. },
  1143. pinned: true,
  1144. titleOverridden: true,
  1145. });
  1146. const syncer = createZCodeTaskIndexSyncer({
  1147. agentService: env.agent,
  1148. taskIndexRepo: env.repo,
  1149. });
  1150. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  1151. await subscribed(env);
  1152. const [meta] = await env.repo.listTaskMetas({ workspacePath: "/repo", pinned: true });
  1153. expect(meta).toMatchObject({
  1154. taskId: "sess_existing",
  1155. title: "用户标题",
  1156. titleOverridden: true,
  1157. updatedAt: 999,
  1158. mode: "build",
  1159. model: "anthropic/haiku-4.5",
  1160. });
  1161. syncer.disposeAll();
  1162. env.indexEmitter.dispose();
  1163. env.configEmitter.dispose();
  1164. });
  1165. it("seeds remote rows under workspaceIdentity instead of the shared workspacePath", async () => {
  1166. const workspaceIdentity = "remote:ssh:dev.example:22:codegeex:/repo";
  1167. const env = setupEnv({
  1168. workspaceKey: workspaceIdentity,
  1169. initialSessions: [
  1170. summaryOf("sess_remote", "completedSuccess", {
  1171. workspaceId: workspaceIdentity,
  1172. title: "远端会话",
  1173. }),
  1174. ],
  1175. });
  1176. const syncer = createZCodeTaskIndexSyncer({
  1177. agentService: env.agent,
  1178. taskIndexRepo: env.repo,
  1179. });
  1180. syncer.onDynamicWorkspaceEvent({
  1181. workspacePath: "/repo",
  1182. workspaceIdentity,
  1183. })(() => {});
  1184. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo", workspaceIdentity });
  1185. await subscribed(env);
  1186. await vi.waitFor(async () => {
  1187. const remoteMeta = await env.repo.getTaskMeta({
  1188. workspacePath: "/repo",
  1189. workspaceIdentity,
  1190. taskId: "sess_remote",
  1191. });
  1192. expect(remoteMeta?.workspaceIdentity).toBe(workspaceIdentity);
  1193. });
  1194. expect(
  1195. await env.repo.getTaskMeta({ workspacePath: "/repo", taskId: "sess_remote" }),
  1196. ).toBeNull();
  1197. syncer.disposeAll();
  1198. env.indexEmitter.dispose();
  1199. env.configEmitter.dispose();
  1200. });
  1201. it("forwards v4 workspace-config frames as workspace_config_options_update and drops empty catalogs", async () => {
  1202. const env = setupEnv();
  1203. const syncer = createZCodeTaskIndexSyncer({
  1204. agentService: env.agent,
  1205. taskIndexRepo: env.repo,
  1206. });
  1207. const broadcasts: ZCodeWorkspaceEvent[] = [];
  1208. const subscription = syncer.onDynamicWorkspaceEvent({
  1209. workspacePath: "/repo",
  1210. })((event) => broadcasts.push(event));
  1211. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  1212. await subscribed(env);
  1213. // 空目录(无 live session 的订阅种子)不下发,避免清掉工具栏模型目录。
  1214. env.configEmitter.fire(configFrame({ configOptions: [], slashCommands: [] }));
  1215. expect(broadcasts.length).toBe(0);
  1216. env.configEmitter.fire(
  1217. configFrame(
  1218. {
  1219. configOptions: [
  1220. {
  1221. id: "model",
  1222. name: "Model",
  1223. category: "model",
  1224. type: "select",
  1225. currentValue: "anthropic/haiku-4.5",
  1226. options: [{ value: "anthropic/haiku-4.5", name: "Haiku 4.5" }],
  1227. },
  1228. ],
  1229. slashCommands: [{ name: "compact", description: "Compact" }],
  1230. },
  1231. 2,
  1232. ),
  1233. );
  1234. expect(broadcasts.length).toBe(1);
  1235. const event = broadcasts[0];
  1236. expect(event.type).toBe("workspace_config_options_update");
  1237. if (event.type === "workspace_config_options_update") {
  1238. expect(event.workspacePath).toBe("/repo");
  1239. expect(event.configOptions).toHaveLength(1);
  1240. expect(event.configOptions[0]?.id).toBe("model");
  1241. }
  1242. subscription.dispose();
  1243. syncer.disposeAll();
  1244. env.indexEmitter.dispose();
  1245. env.configEmitter.dispose();
  1246. });
  1247. it("refreshes CLI facts before indexing presentation and ignores contradictory snapshot facts", async () => {
  1248. const env = setupEnv();
  1249. env.agent.reconcileSessionsIndexV4 = vi.fn(async () => ({
  1250. sessions: [
  1251. {
  1252. sessionId: "fact-owner",
  1253. exists: true,
  1254. deleted: false,
  1255. title: "CLI title",
  1256. titleSource: "generated",
  1257. createdAt: 10,
  1258. updatedAt: 20,
  1259. lastOutcome: "interrupted",
  1260. },
  1261. ],
  1262. }));
  1263. const syncer = createZCodeTaskIndexSyncer({ agentService: env.agent, taskIndexRepo: env.repo });
  1264. const meta = await syncer.syncSnapshotAndBroadcast(
  1265. snapshotWith("fact-owner", "/repo", {
  1266. title: "Snapshot title",
  1267. userMessageText: "searchable text",
  1268. createdAt: 90,
  1269. updatedAt: 99,
  1270. sessionStatus: "error",
  1271. }),
  1272. { broadcastReason: "task_model_changed" },
  1273. );
  1274. expect(meta).toMatchObject({
  1275. title: "CLI title",
  1276. createdAt: 10,
  1277. updatedAt: 20,
  1278. status: "completed",
  1279. });
  1280. expect(
  1281. (
  1282. await env.repo.queryTaskList({
  1283. workspaceScopes: [{ workspacePath: "/repo" }],
  1284. kind: "active",
  1285. search: "searchable text",
  1286. })
  1287. ).items,
  1288. ).toHaveLength(1);
  1289. syncer.disposeAll();
  1290. });
  1291. it("syncSnapshotAndBroadcast writes meta and fires workspace_task_list_changed", async () => {
  1292. const env = setupEnv({
  1293. initialSessions: [
  1294. summaryOf("sess_new", "running", {
  1295. title: "fix the bug in checkout flow",
  1296. lastActivityAt: 999,
  1297. }),
  1298. ],
  1299. });
  1300. const syncer = createZCodeTaskIndexSyncer({
  1301. agentService: env.agent,
  1302. taskIndexRepo: env.repo,
  1303. });
  1304. const broadcasts: ZCodeWorkspaceEvent[] = [];
  1305. const subscription = syncer.onDynamicWorkspaceEvent({
  1306. workspacePath: "/repo",
  1307. })((event) => broadcasts.push(event));
  1308. const meta = await syncer.syncSnapshotAndBroadcast(
  1309. snapshotWith("sess_new", "/repo", {
  1310. title: "", // 快照未带标题,使用 CLI 事实
  1311. userMessageText: "fix the bug in checkout flow",
  1312. updatedAt: 999,
  1313. }),
  1314. { broadcastReason: "task_meta_changed" },
  1315. );
  1316. // 标题来自 CLI reconcile,Host 只索引正文。
  1317. expect(meta.title).toBe("fix the bug in checkout flow");
  1318. expect(meta.updatedAt).toBe(999);
  1319. const persisted = await env.repo.getTaskMeta({
  1320. workspacePath: "/repo",
  1321. taskId: "sess_new",
  1322. });
  1323. expect(persisted?.title).toBe("fix the bug in checkout flow");
  1324. expect(broadcasts.length).toBe(1);
  1325. const evt = broadcasts[0];
  1326. if (evt.type === "workspace_task_list_changed") {
  1327. expect(evt.taskId).toBe("sess_new");
  1328. expect(evt.taskMeta?.title).toBe("fix the bug in checkout flow");
  1329. } else {
  1330. throw new Error("expected workspace_task_list_changed");
  1331. }
  1332. subscription.dispose();
  1333. syncer.disposeAll();
  1334. });
  1335. it("syncSnapshotAndBroadcast 对 index profile 裁剪后的 snapshot 产出与 full 完全一致的索引写入", async () => {
  1336. const big = "z".repeat(256 * 1024);
  1337. const full = snapshotWith("sess_profile", "/repo", {
  1338. title: "",
  1339. userMessageText: "排查订单列表慢查询",
  1340. assistantMessageText: "根因是缺少索引",
  1341. assistantCompletedAt: 50,
  1342. sessionStatus: "completed",
  1343. updatedAt: 60,
  1344. });
  1345. // 固定 traceId:缺省时 buildMetaFromSnapshot 会随机生成,与裁剪无关。
  1346. full.session.traceId = "trace_profile";
  1347. const assistant = full.messages.find((message) => message.info.role === "assistant");
  1348. if (!assistant) throw new Error("fixture assistant missing");
  1349. assistant.parts.unshift(
  1350. { partId: "p_reason", type: "reasoning", text: big } as never,
  1351. {
  1352. partId: "p_tool",
  1353. type: "tool",
  1354. callId: "call_profile",
  1355. tool: "bash",
  1356. state: {
  1357. status: "completed",
  1358. input: { command: big },
  1359. output: big,
  1360. title: "bash",
  1361. metadata: { output: big },
  1362. startedAt: 40,
  1363. completedAt: 41,
  1364. },
  1365. } as never,
  1366. );
  1367. const elided = elideSessionSnapshotForIndex(full);
  1368. expect(JSON.stringify(elided).length).toBeLessThan(big.length / 10);
  1369. const capture = async (snapshot: ZCodeSessionStateSnapshot) => {
  1370. const env = setupEnv({
  1371. initialSessions: [
  1372. summaryOf(snapshot.session.sessionId, "completedSuccess", {
  1373. title: snapshot.session.title,
  1374. }),
  1375. ],
  1376. });
  1377. const writes: unknown[] = [];
  1378. const original = env.repo.updateTaskPresentation.bind(env.repo);
  1379. vi.spyOn(env.repo, "updateTaskPresentation").mockImplementation(async (input) => {
  1380. writes.push(structuredClone(input));
  1381. return await original(input);
  1382. });
  1383. const syncer = createZCodeTaskIndexSyncer({
  1384. agentService: env.agent,
  1385. taskIndexRepo: env.repo,
  1386. });
  1387. const broadcasts: ZCodeWorkspaceEvent[] = [];
  1388. const subscription = syncer.onDynamicWorkspaceEvent({ workspacePath: "/repo" })((event) =>
  1389. broadcasts.push(event),
  1390. );
  1391. const meta = await syncer.syncSnapshotAndBroadcast(snapshot, {
  1392. broadcastReason: "task_status_changed",
  1393. });
  1394. subscription.dispose();
  1395. syncer.disposeAll();
  1396. return { meta, writes, broadcasts };
  1397. };
  1398. const fromFull = await capture(full);
  1399. const fromIndex = await capture(elided);
  1400. expect(fromFull.writes).toHaveLength(1);
  1401. expect(fromFull.writes[0]).toMatchObject({
  1402. searchableText: "排查订单列表慢查询\n根因是缺少索引",
  1403. });
  1404. expect(fromIndex.writes).toEqual(fromFull.writes);
  1405. expect(fromIndex.meta).toEqual(fromFull.meta);
  1406. expect(fromIndex.broadcasts).toEqual(fromFull.broadcasts);
  1407. });
  1408. it("syncSnapshotAndBroadcast prefers structured projection error code in task meta", async () => {
  1409. const env = setupEnv({
  1410. initialSessions: [
  1411. summaryOf("sess_error", "running", { title: "stale model", lastActivityAt: 999 }),
  1412. ],
  1413. });
  1414. const syncer = createZCodeTaskIndexSyncer({
  1415. agentService: env.agent,
  1416. taskIndexRepo: env.repo,
  1417. });
  1418. const restored = snapshotWith("sess_error", "/repo", {
  1419. title: "stale model",
  1420. updatedAt: 999,
  1421. });
  1422. const meta = await syncer.syncSnapshotAndBroadcast(
  1423. {
  1424. ...restored,
  1425. session: {
  1426. ...restored.session,
  1427. status: "error",
  1428. },
  1429. projection: {
  1430. ...restored.projection,
  1431. lastError: {
  1432. type: "MODEL_ERROR",
  1433. code: "provider_not_found",
  1434. message: "Model provider is not configured: stale-provider",
  1435. detail: "stale-provider/gpt-5.5",
  1436. attribution: {
  1437. source: "runtime",
  1438. reason: "provider_not_configured",
  1439. providerId: "account:zai-individual-coding-plan",
  1440. },
  1441. },
  1442. },
  1443. },
  1444. { broadcastReason: "task_status_changed" },
  1445. );
  1446. expect(meta.lastError).toEqual({
  1447. code: "provider_not_found",
  1448. detail: "stale-provider/gpt-5.5",
  1449. message: "Model provider is not configured: stale-provider",
  1450. attribution: {
  1451. source: "runtime",
  1452. reason: "provider_not_configured",
  1453. providerId: "account:zai-individual-coding-plan",
  1454. },
  1455. });
  1456. syncer.disposeAll();
  1457. });
  1458. it("syncSnapshotAndBroadcast stores the latest message model when settings current is polluted", async () => {
  1459. const env = setupEnv({
  1460. initialSessions: [
  1461. summaryOf("sess_model", "running", { title: "model", lastActivityAt: 100 }),
  1462. ],
  1463. });
  1464. const syncer = createZCodeTaskIndexSyncer({
  1465. agentService: env.agent,
  1466. taskIndexRepo: env.repo,
  1467. });
  1468. const meta = await syncer.syncSnapshotAndBroadcast(
  1469. snapshotWith("sess_model", "/repo", {
  1470. title: "historical model",
  1471. userMessageText: "fix perf",
  1472. settingsModel: {
  1473. providerId: "36965ea6-734a-46a8-8851-3dfec026589e",
  1474. modelId: "glm-5.1-highspeed",
  1475. },
  1476. messageModel: {
  1477. providerId: "default-deepseek",
  1478. modelId: "deepseek-v4-flash",
  1479. },
  1480. }),
  1481. { broadcastReason: "task_meta_changed" },
  1482. );
  1483. expect(meta.model).toBe("default-deepseek/deepseek-v4-flash");
  1484. await expect(
  1485. env.repo.getTaskMeta({
  1486. workspacePath: "/repo",
  1487. taskId: "sess_model",
  1488. }),
  1489. ).resolves.toMatchObject({
  1490. model: "default-deepseek/deepseek-v4-flash",
  1491. });
  1492. syncer.disposeAll();
  1493. });
  1494. it("syncSnapshotAndBroadcast can override task model for explicit model switches", async () => {
  1495. const env = setupEnv({
  1496. initialSessions: [
  1497. summaryOf("sess_model_override", "running", { title: "model", lastActivityAt: 100 }),
  1498. ],
  1499. });
  1500. const syncer = createZCodeTaskIndexSyncer({
  1501. agentService: env.agent,
  1502. taskIndexRepo: env.repo,
  1503. });
  1504. const meta = await syncer.syncSnapshotAndBroadcast(
  1505. snapshotWith("sess_model_override", "/repo", {
  1506. title: "historical model",
  1507. userMessageText: "continue with visible model",
  1508. settingsModel: {
  1509. providerId: "current-provider",
  1510. modelId: "current-model",
  1511. },
  1512. messageModel: {
  1513. providerId: "removed-provider",
  1514. modelId: "removed-model",
  1515. },
  1516. }),
  1517. { modelOverride: "current-provider/current-model", broadcastReason: "task_meta_changed" },
  1518. );
  1519. expect(meta.model).toBe("current-provider/current-model");
  1520. await expect(
  1521. env.repo.getTaskMeta({
  1522. workspacePath: "/repo",
  1523. taskId: "sess_model_override",
  1524. }),
  1525. ).resolves.toMatchObject({
  1526. model: "current-provider/current-model",
  1527. });
  1528. syncer.disposeAll();
  1529. });
  1530. it("syncSnapshotAndBroadcast can override task thought level for explicit resume", async () => {
  1531. const env = setupEnv({
  1532. initialSessions: [
  1533. summaryOf("sess_thought_override", "running", { title: "thought", lastActivityAt: 100 }),
  1534. ],
  1535. });
  1536. const syncer = createZCodeTaskIndexSyncer({
  1537. agentService: env.agent,
  1538. taskIndexRepo: env.repo,
  1539. });
  1540. const meta = await syncer.syncSnapshotAndBroadcast(
  1541. snapshotWith("sess_thought_override", "/repo", {
  1542. title: "historical thought level",
  1543. userMessageText: "continue with task-local thought level",
  1544. thoughtLevel: "high",
  1545. }),
  1546. { thoughtLevelOverride: "max", broadcastReason: "task_meta_changed" },
  1547. );
  1548. expect(meta.thoughtLevel).toBe("max");
  1549. await expect(
  1550. env.repo.getTaskMeta({
  1551. workspacePath: "/repo",
  1552. taskId: "sess_thought_override",
  1553. }),
  1554. ).resolves.toMatchObject({
  1555. thoughtLevel: "max",
  1556. });
  1557. syncer.disposeAll();
  1558. });
  1559. it("syncTaskModel updates only the persisted task model", async () => {
  1560. const env = setupEnv();
  1561. const syncer = createZCodeTaskIndexSyncer({
  1562. agentService: env.agent,
  1563. taskIndexRepo: env.repo,
  1564. });
  1565. await seedTaskIndex(env.repo, {
  1566. meta: {
  1567. taskId: "sess_model_patch",
  1568. traceId: "trace_model_patch",
  1569. title: "Existing task",
  1570. workspacePath: "/repo",
  1571. createdAt: 1,
  1572. updatedAt: 2,
  1573. mode: "build",
  1574. model: "removed-provider/removed-model",
  1575. status: "completed",
  1576. },
  1577. });
  1578. await expect(
  1579. syncer.syncTaskModel(
  1580. {
  1581. workspacePath: "/repo",
  1582. sessionId: "sess_model_patch",
  1583. },
  1584. "current-provider/current-model",
  1585. ),
  1586. ).resolves.toMatchObject({
  1587. model: "current-provider/current-model",
  1588. status: "completed",
  1589. title: "Existing task",
  1590. });
  1591. syncer.disposeAll();
  1592. });
  1593. it("syncSnapshotAndBroadcast titles /goal sessions without indexing continuation reminders", async () => {
  1594. const env = setupEnv({
  1595. initialSessions: [
  1596. summaryOf("sess_goal", "running", { title: "优化性能到 60fps", lastActivityAt: 100 }),
  1597. ],
  1598. });
  1599. const syncer = createZCodeTaskIndexSyncer({
  1600. agentService: env.agent,
  1601. taskIndexRepo: env.repo,
  1602. });
  1603. const internalGoalPrompt = [
  1604. '<system-reminder source="goal-continuation">',
  1605. "Continue working toward the active session goal.",
  1606. "",
  1607. "<untrusted_objective>",
  1608. "优化性能到 60fps",
  1609. "</untrusted_objective>",
  1610. "</system-reminder>",
  1611. ].join("\n");
  1612. const meta = await syncer.syncSnapshotAndBroadcast(
  1613. snapshotWith("sess_goal", "/repo", {
  1614. title: internalGoalPrompt,
  1615. userMessageText: internalGoalPrompt,
  1616. target: {
  1617. sessionId: "sess_goal",
  1618. targetId: "goal_1",
  1619. objective: "优化性能到 60fps",
  1620. summaryTitle: "优化性能到 60fps",
  1621. status: "active",
  1622. tokenBudget: null,
  1623. tokensUsed: 0,
  1624. timeUsedSeconds: 0,
  1625. createdAt: 1,
  1626. updatedAt: 1,
  1627. },
  1628. }),
  1629. { broadcastReason: "task_meta_changed" },
  1630. );
  1631. // Bugfix: /goal 自动续跑的内部 reminder wrapper 只是模型输入,不是用户可见 query。
  1632. // 标题可以回退到真实 goal objective,但正文搜索索引不能写入内部安全封装文本。
  1633. expect(meta.title).toBe("优化性能到 60fps");
  1634. expect(meta.target).toMatchObject({
  1635. objective: "优化性能到 60fps",
  1636. summaryTitle: "优化性能到 60fps",
  1637. targetID: "goal_1",
  1638. });
  1639. const objectiveResult = await env.repo.queryTaskList({
  1640. workspaceScopes: [{ workspacePath: "/repo" }],
  1641. search: "60fps",
  1642. });
  1643. expect(objectiveResult.total).toBe(1);
  1644. const persisted = await env.repo.getTaskMeta({
  1645. workspacePath: "/repo",
  1646. taskId: "sess_goal",
  1647. });
  1648. expect(persisted?.target).toMatchObject({
  1649. objective: "优化性能到 60fps",
  1650. summaryTitle: "优化性能到 60fps",
  1651. targetID: "goal_1",
  1652. });
  1653. const internalPromptResult = await env.repo.queryTaskList({
  1654. workspaceScopes: [{ workspacePath: "/repo" }],
  1655. search: "system-reminder",
  1656. });
  1657. expect(internalPromptResult.total).toBe(0);
  1658. syncer.disposeAll();
  1659. });
  1660. it("syncSnapshotAndBroadcast preserves indexed goal when snapshot omits target", async () => {
  1661. const env = setupEnv({
  1662. initialSessions: [
  1663. summaryOf("sess_goal_preserve", "running", { title: "goal", lastActivityAt: 100 }),
  1664. ],
  1665. });
  1666. const syncer = createZCodeTaskIndexSyncer({
  1667. agentService: env.agent,
  1668. taskIndexRepo: env.repo,
  1669. });
  1670. await syncer.syncSnapshotAndBroadcast(
  1671. snapshotWith("sess_goal_preserve", "/repo", {
  1672. target: {
  1673. sessionId: "sess_goal_preserve",
  1674. targetId: "goal_keep",
  1675. objective: "保留历史目标",
  1676. summaryTitle: null,
  1677. status: "active",
  1678. tokenBudget: null,
  1679. tokensUsed: 0,
  1680. timeUsedSeconds: 0,
  1681. createdAt: 1,
  1682. updatedAt: 1,
  1683. },
  1684. }),
  1685. { broadcastReason: "task_meta_changed" },
  1686. );
  1687. const omittedTargetSnapshot = snapshotWith("sess_goal_preserve", "/repo", {
  1688. title: "继续处理历史任务",
  1689. userMessageText: "继续处理历史任务",
  1690. });
  1691. delete omittedTargetSnapshot.projection.target;
  1692. await syncer.syncSnapshotAndBroadcast(omittedTargetSnapshot, {
  1693. broadcastReason: "task_meta_changed",
  1694. });
  1695. expect(
  1696. (
  1697. await env.repo.getTaskMeta({
  1698. workspacePath: "/repo",
  1699. taskId: "sess_goal_preserve",
  1700. })
  1701. )?.target,
  1702. ).toMatchObject({
  1703. objective: "保留历史目标",
  1704. targetID: "goal_keep",
  1705. });
  1706. await syncer.syncSnapshotAndBroadcast(
  1707. snapshotWith("sess_goal_preserve", "/repo", {
  1708. title: "明确清空历史目标",
  1709. userMessageText: "明确清空历史目标",
  1710. target: null,
  1711. }),
  1712. { broadcastReason: "task_meta_changed" },
  1713. );
  1714. expect(
  1715. (
  1716. await env.repo.getTaskMeta({
  1717. workspacePath: "/repo",
  1718. taskId: "sess_goal_preserve",
  1719. })
  1720. )?.target,
  1721. ).toBeNull();
  1722. syncer.disposeAll();
  1723. });
  1724. it("does not create an index row or broadcast for an unpersisted empty draft", async () => {
  1725. // Bugfix: createSession 刚返回时 snapshot 既没有 title 也没有 user message,
  1726. // 此时不应该广播 workspace_task_list_changed,否则侧边栏会先闪一下 "New session" 占位符。
  1727. // 真实 CLI facts 到达前不得创建持久列表行。
  1728. const env = setupEnv();
  1729. const syncer = createZCodeTaskIndexSyncer({
  1730. agentService: env.agent,
  1731. taskIndexRepo: env.repo,
  1732. });
  1733. const broadcasts: ZCodeWorkspaceEvent[] = [];
  1734. const subscription = syncer.onDynamicWorkspaceEvent({
  1735. workspacePath: "/repo",
  1736. })((event) => broadcasts.push(event));
  1737. await syncer.syncSnapshotAndBroadcast(
  1738. snapshotWith("sess_empty", "/repo", {
  1739. title: "",
  1740. // 不带 userMessageText → snapshot.messages 为空
  1741. updatedAt: 1,
  1742. }),
  1743. { broadcastReason: "task_meta_changed" },
  1744. );
  1745. expect(broadcasts.length).toBe(0);
  1746. // 后续 sessions-index 负责创建持久行。
  1747. const persisted = await env.repo.getTaskMeta({
  1748. workspacePath: "/repo",
  1749. taskId: "sess_empty",
  1750. });
  1751. expect(persisted).toBeNull();
  1752. subscription.dispose();
  1753. syncer.disposeAll();
  1754. });
  1755. it("does not reorder an existing task when duplicate first-snapshot sync finishes late", async () => {
  1756. const env = setupEnv();
  1757. const syncer = createZCodeTaskIndexSyncer({
  1758. agentService: env.agent,
  1759. taskIndexRepo: env.repo,
  1760. });
  1761. const firstTask = snapshotWith("first-task", "/repo", {
  1762. title: "First task",
  1763. userMessageText: "First task",
  1764. createdAt: 10,
  1765. updatedAt: 10,
  1766. });
  1767. const secondTask = snapshotWith("second-task", "/repo", {
  1768. title: "Second task",
  1769. userMessageText: "Second task",
  1770. createdAt: 20,
  1771. updatedAt: 20,
  1772. });
  1773. for (const snapshot of [firstTask, secondTask]) {
  1774. await env.repo.applyCliFacts({
  1775. meta: {
  1776. taskId: snapshot.session.sessionId,
  1777. workspacePath: "/repo",
  1778. traceId: "seed",
  1779. provider: "glm",
  1780. title: snapshot.session.title,
  1781. mode: "default",
  1782. createdAt: snapshot.session.createdAt,
  1783. updatedAt: snapshot.session.updatedAt,
  1784. },
  1785. lastOutcome: "completed",
  1786. });
  1787. }
  1788. await syncer.syncSnapshotAndBroadcast(firstTask, {
  1789. broadcastReason: "task_status_changed",
  1790. });
  1791. await syncer.syncSnapshotAndBroadcast(secondTask, {
  1792. broadcastReason: "task_status_changed",
  1793. });
  1794. // 历史 bug:迟到首帧曾再次置顶旧任务;现在顺序仅由 CLI 活动镜像决定。
  1795. await syncer.syncSnapshotAndBroadcast(firstTask, {
  1796. broadcastReason: "task_status_changed",
  1797. });
  1798. const view = (await env.repo.getProjectRepository()).readTree();
  1799. expect(view.tasks.slice(0, 2).map((task) => task.taskId)).toEqual([
  1800. "second-task",
  1801. "first-task",
  1802. ]);
  1803. syncer.disposeAll();
  1804. });
  1805. it("syncSnapshotAndBroadcast preserves a newer sqlite updated_at (no regression)", async () => {
  1806. // Bugfix: snapshot 的 session.updatedAt 是 runtime sessionStore 里的"结构变更时间",
  1807. // 不一定包含 session.titleUpdated / turn.completed 这些事件触发的 Date.now() 增量。
  1808. // 如果直接用 snapshot.updatedAt 覆盖会让刚被 applyAgentPatch 写入的更新时间倒退,
  1809. // 表现就是新会话第一次 prompt 后又被压到列表底部。
  1810. const env = setupEnv();
  1811. const syncer = createZCodeTaskIndexSyncer({
  1812. agentService: env.agent,
  1813. taskIndexRepo: env.repo,
  1814. });
  1815. // 先写一条 sqlite 行,updated_at 是较新的时间戳(模拟 applyAgentPatch 已经写过一次 Date.now())
  1816. await seedTaskIndex(env.repo, {
  1817. meta: {
  1818. taskId: "sess_regress",
  1819. traceId: "trace_seed",
  1820. title: "你好",
  1821. workspacePath: "/repo",
  1822. createdAt: 100,
  1823. updatedAt: 99999,
  1824. mode: "build",
  1825. },
  1826. });
  1827. // 用一个较旧的 snapshot.updatedAt 触发 sync
  1828. await syncer.syncSnapshotAndBroadcast(
  1829. snapshotWith("sess_regress", "/repo", {
  1830. title: "你好",
  1831. userMessageText: "你好",
  1832. createdAt: 100,
  1833. updatedAt: 100, // 远小于 sqlite 已有的 99999
  1834. }),
  1835. { broadcastReason: "task_meta_changed" },
  1836. );
  1837. const persisted = await env.repo.getTaskMeta({
  1838. workspacePath: "/repo",
  1839. taskId: "sess_regress",
  1840. });
  1841. // 期望 updated_at 不会倒退
  1842. expect(persisted?.updatedAt).toBe(99999);
  1843. syncer.disposeAll();
  1844. });
  1845. it("syncSnapshotAndBroadcast does not downgrade newer terminal status with an older running snapshot", async () => {
  1846. const env = setupEnv();
  1847. const syncer = createZCodeTaskIndexSyncer({
  1848. agentService: env.agent,
  1849. taskIndexRepo: env.repo,
  1850. });
  1851. await seedTaskIndex(env.repo, {
  1852. meta: {
  1853. taskId: "sess_terminal_status",
  1854. traceId: "trace_complete",
  1855. title: "阅读这个项目",
  1856. workspacePath: "/repo",
  1857. createdAt: 100,
  1858. updatedAt: 99_999,
  1859. mode: "build",
  1860. status: "completed",
  1861. },
  1862. });
  1863. await syncer.syncSnapshotAndBroadcast(
  1864. snapshotWith("sess_terminal_status", "/repo", {
  1865. title: "阅读这个项目",
  1866. userMessageText: "阅读这个项目",
  1867. createdAt: 100,
  1868. updatedAt: 100,
  1869. }),
  1870. { broadcastReason: "task_meta_changed" },
  1871. );
  1872. const persisted = await env.repo.getTaskMeta({
  1873. workspacePath: "/repo",
  1874. taskId: "sess_terminal_status",
  1875. });
  1876. expect(persisted?.updatedAt).toBe(99_999);
  1877. expect(persisted?.status).toBe("completed");
  1878. syncer.disposeAll();
  1879. });
  1880. it("syncSnapshotAndBroadcast does not infer durable outcome from assistant messages", async () => {
  1881. const env = setupEnv();
  1882. const syncer = createZCodeTaskIndexSyncer({
  1883. agentService: env.agent,
  1884. taskIndexRepo: env.repo,
  1885. });
  1886. await seedTaskIndex(env.repo, {
  1887. meta: {
  1888. taskId: "sess_repair_terminal",
  1889. traceId: "trace_running",
  1890. title: "阅读这个项目",
  1891. workspacePath: "/repo",
  1892. createdAt: 100,
  1893. updatedAt: 100,
  1894. mode: "build",
  1895. status: "running",
  1896. },
  1897. });
  1898. await syncer.syncSnapshotAndBroadcast(
  1899. snapshotWith("sess_repair_terminal", "/repo", {
  1900. title: "阅读这个项目",
  1901. userMessageText: "阅读这个项目",
  1902. assistantMessageText: "以下是该项目的完整概览。",
  1903. assistantCompletedAt: 130,
  1904. createdAt: 100,
  1905. updatedAt: 120,
  1906. }),
  1907. { broadcastReason: "task_meta_changed" },
  1908. );
  1909. const persisted = await env.repo.getTaskMeta({
  1910. workspacePath: "/repo",
  1911. taskId: "sess_repair_terminal",
  1912. });
  1913. expect(persisted?.status).toBeUndefined();
  1914. syncer.disposeAll();
  1915. });
  1916. it("syncSnapshotAndBroadcast does not infer durable outcome from idle runtime", async () => {
  1917. const env = setupEnv();
  1918. const syncer = createZCodeTaskIndexSyncer({
  1919. agentService: env.agent,
  1920. taskIndexRepo: env.repo,
  1921. });
  1922. await seedTaskIndex(env.repo, {
  1923. meta: {
  1924. taskId: "sess_idle_completed",
  1925. traceId: "trace_idle_completed",
  1926. title: "切换项目后继续对话",
  1927. workspacePath: "/repo",
  1928. createdAt: 100,
  1929. updatedAt: 100,
  1930. mode: "build",
  1931. status: "running",
  1932. },
  1933. });
  1934. await syncer.syncSnapshotAndBroadcast(
  1935. snapshotWith("sess_idle_completed", "/repo", {
  1936. title: "切换项目后继续对话",
  1937. userMessageText: "继续",
  1938. assistantMessageText: "已经处理完成。",
  1939. assistantCompletedAt: 130,
  1940. sessionStatus: "idle",
  1941. createdAt: 100,
  1942. updatedAt: 130,
  1943. }),
  1944. { broadcastReason: "task_meta_changed" },
  1945. );
  1946. const persisted = await env.repo.getTaskMeta({
  1947. workspacePath: "/repo",
  1948. taskId: "sess_idle_completed",
  1949. });
  1950. expect(persisted?.status).toBeUndefined();
  1951. syncer.disposeAll();
  1952. });
  1953. it("only subscribes the workspace once even across many sessions", async () => {
  1954. const env = setupEnv();
  1955. const syncer = createZCodeTaskIndexSyncer({
  1956. agentService: env.agent,
  1957. taskIndexRepo: env.repo,
  1958. });
  1959. syncer.ensureSessionSubscription(seedTarget);
  1960. syncer.ensureSessionSubscription(seedTarget);
  1961. syncer.ensureSessionSubscription({
  1962. workspacePath: seedTarget.workspacePath,
  1963. sessionId: "another_session",
  1964. });
  1965. syncer.ensureWorkspaceSubscription({ workspacePath: seedTarget.workspacePath });
  1966. await subscribed(env);
  1967. expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  1968. expect(env.agent.subscribeWorkspaceConfigV4).toHaveBeenCalledTimes(1);
  1969. // 与 renderer 侧栏共 topic 不同代际:syncer 必须带独立 subscriberScope。
  1970. expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledWith(
  1971. expect.objectContaining({ subscriberScope: "task-index" }),
  1972. );
  1973. syncer.disposeAll();
  1974. env.indexEmitter.dispose();
  1975. env.configEmitter.dispose();
  1976. });
  1977. it("stages same-read index/config initial notifications and releases only the ACK subId", async () => {
  1978. const env = setupEnv();
  1979. await seedRunningTask(env.repo);
  1980. let resolveIndex!: (result: IndexSubscribeResult) => void;
  1981. vi.mocked(env.agent.subscribeSessionsIndexV4).mockImplementationOnce(
  1982. () => new Promise((resolve) => (resolveIndex = resolve)),
  1983. );
  1984. vi.mocked(env.agent.subscribeWorkspaceConfigV4).mockImplementationOnce(async () => {
  1985. env.configEmitter.fire(
  1986. configFrame({
  1987. configOptions: [
  1988. {
  1989. id: "model",
  1990. name: "Model",
  1991. category: "model",
  1992. type: "select",
  1993. currentValue: "anthropic/haiku-4.5",
  1994. options: [{ value: "anthropic/haiku-4.5", name: "Haiku 4.5" }],
  1995. },
  1996. ],
  1997. slashCommands: [],
  1998. }),
  1999. );
  2000. return {
  2001. ack: {
  2002. subscriptionId: CONFIG_SUBSCRIPTION_ID,
  2003. mode: "snapshot" as const,
  2004. logEpoch: "epoch-cfg",
  2005. },
  2006. };
  2007. });
  2008. const syncer = createZCodeTaskIndexSyncer({
  2009. agentService: env.agent,
  2010. taskIndexRepo: env.repo,
  2011. });
  2012. const workspaceEvents: ZCodeWorkspaceEvent[] = [];
  2013. const terminalEvents: string[] = [];
  2014. const workspaceSubscription = syncer.onDynamicWorkspaceEvent({ workspacePath: "/repo" })(
  2015. (event) => workspaceEvents.push(event),
  2016. );
  2017. const terminalSubscription = syncer.onSessionTerminalEvent((event) =>
  2018. terminalEvents.push(event.target.sessionId),
  2019. );
  2020. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2021. await vi.waitFor(() => expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1));
  2022. env.indexEmitter.fire({
  2023. ...indexSnapshotFrame([summaryOf(seedTarget.sessionId, "completedSuccess")]),
  2024. subscriptionId: "foreign-sub",
  2025. });
  2026. env.indexEmitter.fire(indexSnapshotFrame([summaryOf(seedTarget.sessionId, "running")]));
  2027. resolveIndex({
  2028. ack: {
  2029. subscriptionId: INDEX_SUBSCRIPTION_ID,
  2030. mode: "snapshot",
  2031. logEpoch: "epoch-test",
  2032. },
  2033. });
  2034. await new Promise((resolve) => setImmediate(resolve));
  2035. env.indexEmitter.fire(indexUpsertFrame(summaryOf(seedTarget.sessionId, "completedSuccess")));
  2036. await vi.waitFor(async () => {
  2037. const meta = await env.repo.getTaskMeta({
  2038. workspacePath: seedTarget.workspacePath,
  2039. taskId: seedTarget.sessionId,
  2040. });
  2041. expect(meta?.status).toBe("completed");
  2042. });
  2043. expect(terminalEvents).toEqual([seedTarget.sessionId]);
  2044. expect(workspaceEvents.some((event) => event.type === "workspace_config_options_update")).toBe(
  2045. true,
  2046. );
  2047. terminalSubscription.dispose();
  2048. workspaceSubscription.dispose();
  2049. syncer.disposeAll();
  2050. env.indexEmitter.dispose();
  2051. env.configEmitter.dispose();
  2052. });
  2053. it("physical sessions-index 分片在最后一片前不修改 task index,齐片后只 apply 一次", async () => {
  2054. const env = setupEnv({
  2055. initialSessions: [summaryOf(seedTarget.sessionId, "running")],
  2056. });
  2057. await seedRunningTask(env.repo);
  2058. const syncer = createZCodeTaskIndexSyncer({
  2059. agentService: env.agent,
  2060. taskIndexRepo: env.repo,
  2061. });
  2062. const terminalEvents: string[] = [];
  2063. const terminalSubscription = syncer.onSessionTerminalEvent((event) =>
  2064. terminalEvents.push(event.target.sessionId),
  2065. );
  2066. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2067. await subscribed(env);
  2068. const logical = indexUpsertFrame(
  2069. summaryOf(seedTarget.sessionId, "completedSuccess", { title: "中文🙂".repeat(300) }),
  2070. );
  2071. const wires = encodeTopicWireFrames(logical, {
  2072. topic: logical.topic,
  2073. subscriptionId: logical.subscriptionId,
  2074. logicalFrameId: "logical-index-fragmented",
  2075. logicalFrameOrdinal: 1_000,
  2076. deliveryKind: "online",
  2077. maxPhysicalFrameBytes: 500,
  2078. measurePhysicalFrameBytes: utf8JsonByteLength,
  2079. }) as SessionsIndexTopicWireFrame[];
  2080. expect(wires.length).toBeGreaterThan(2);
  2081. for (const wire of wires.slice(0, -1)) {
  2082. env.indexEmitter.fireWire(wire);
  2083. }
  2084. await new Promise((resolve) => setImmediate(resolve));
  2085. expect(
  2086. (
  2087. await env.repo.getTaskMeta({
  2088. workspacePath: seedTarget.workspacePath,
  2089. taskId: seedTarget.sessionId,
  2090. })
  2091. )?.status,
  2092. ).toBeUndefined();
  2093. expect(terminalEvents).toEqual([]);
  2094. env.indexEmitter.fireWire(wires.at(-1)!);
  2095. await vi.waitFor(async () => {
  2096. expect(
  2097. (
  2098. await env.repo.getTaskMeta({
  2099. workspacePath: seedTarget.workspacePath,
  2100. taskId: seedTarget.sessionId,
  2101. })
  2102. )?.status,
  2103. ).toBe("completed");
  2104. });
  2105. expect(terminalEvents).toEqual([seedTarget.sessionId]);
  2106. terminalSubscription.dispose();
  2107. syncer.disposeAll();
  2108. env.indexEmitter.dispose();
  2109. env.configEmitter.dispose();
  2110. });
  2111. it("physical superseded fault 与 newer complete 同批出现时 task index fail closed", async () => {
  2112. const env = setupEnv({
  2113. initialSessions: [summaryOf(seedTarget.sessionId, "running")],
  2114. });
  2115. await seedRunningTask(env.repo);
  2116. const syncer = createZCodeTaskIndexSyncer({
  2117. agentService: env.agent,
  2118. taskIndexRepo: env.repo,
  2119. });
  2120. const terminalEvents: string[] = [];
  2121. const terminalSubscription = syncer.onSessionTerminalEvent((event) =>
  2122. terminalEvents.push(event.target.sessionId),
  2123. );
  2124. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2125. await subscribed(env);
  2126. const oldLogical = indexUpsertFrame(
  2127. summaryOf(seedTarget.sessionId, "completedSuccess", { title: "old".repeat(500) }),
  2128. );
  2129. const oldWires = encodeTopicWireFrames(oldLogical, {
  2130. topic: oldLogical.topic,
  2131. subscriptionId: oldLogical.subscriptionId,
  2132. logicalFrameId: "logical-index-old-partial",
  2133. logicalFrameOrdinal: 1_000,
  2134. deliveryKind: "online",
  2135. maxPhysicalFrameBytes: 500,
  2136. measurePhysicalFrameBytes: utf8JsonByteLength,
  2137. }) as SessionsIndexTopicWireFrame[];
  2138. env.indexEmitter.fireWire(oldWires[0]!);
  2139. const newer = indexUpsertFrame(summaryOf(seedTarget.sessionId, "completedSuccess"));
  2140. env.indexEmitter.fireWire({
  2141. wireVersion: 3,
  2142. kind: "complete",
  2143. deliveryKind: "online",
  2144. logicalFrameId: "logical-index-newer",
  2145. logicalFrameOrdinal: 1_001,
  2146. topic: newer.topic,
  2147. subscriptionId: newer.subscriptionId,
  2148. frame: newer,
  2149. });
  2150. await new Promise((resolve) => setImmediate(resolve));
  2151. expect(
  2152. (
  2153. await env.repo.getTaskMeta({
  2154. workspacePath: seedTarget.workspacePath,
  2155. taskId: seedTarget.sessionId,
  2156. })
  2157. )?.status,
  2158. ).toBeUndefined();
  2159. expect(terminalEvents).toEqual([]);
  2160. terminalSubscription.dispose();
  2161. syncer.disposeAll();
  2162. env.indexEmitter.dispose();
  2163. env.configEmitter.dispose();
  2164. });
  2165. it("stale subscribe ACK cannot replace the new generation and is unsubscribed", async () => {
  2166. const env = setupEnv();
  2167. await seedRunningTask(env.repo);
  2168. const restartEmitter = new Emitter<{ workspaceKey: string }>();
  2169. (env.agent as { onAgentRuntimeRestarted?: unknown }).onAgentRuntimeRestarted =
  2170. restartEmitter.event;
  2171. const resolvers: Array<(result: IndexSubscribeResult) => void> = [];
  2172. vi.mocked(env.agent.subscribeSessionsIndexV4).mockImplementation(
  2173. () => new Promise((resolve) => resolvers.push(resolve)),
  2174. );
  2175. const syncer = createZCodeTaskIndexSyncer({
  2176. agentService: env.agent,
  2177. taskIndexRepo: env.repo,
  2178. });
  2179. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2180. await vi.waitFor(() => expect(resolvers).toHaveLength(1));
  2181. env.indexEmitter.fire(indexSnapshotFrame([summaryOf(seedTarget.sessionId, "running")]));
  2182. restartEmitter.fire({ workspaceKey: "/repo" });
  2183. await vi.waitFor(() => expect(resolvers).toHaveLength(2));
  2184. env.indexEmitter.fire({
  2185. ...indexSnapshotFrame([summaryOf(seedTarget.sessionId, "running")]),
  2186. subscriptionId: "six-test-2",
  2187. });
  2188. resolvers[1]!({
  2189. ack: {
  2190. subscriptionId: "six-test-2",
  2191. mode: "snapshot",
  2192. logEpoch: "epoch-test-2",
  2193. },
  2194. });
  2195. await new Promise((resolve) => setImmediate(resolve));
  2196. resolvers[0]!({
  2197. ack: {
  2198. subscriptionId: INDEX_SUBSCRIPTION_ID,
  2199. mode: "snapshot",
  2200. logEpoch: "epoch-test",
  2201. },
  2202. });
  2203. await vi.waitFor(() =>
  2204. expect(env.agent.unsubscribeSessionsIndexV4).toHaveBeenCalledWith(
  2205. expect.objectContaining({ subscriptionId: INDEX_SUBSCRIPTION_ID }),
  2206. ),
  2207. );
  2208. env.indexEmitter.fire({
  2209. ...indexUpsertFrame(summaryOf(seedTarget.sessionId, "completedSuccess")),
  2210. subscriptionId: "six-test-2",
  2211. });
  2212. await vi.waitFor(async () => {
  2213. const meta = await env.repo.getTaskMeta({
  2214. workspacePath: seedTarget.workspacePath,
  2215. taskId: seedTarget.sessionId,
  2216. });
  2217. expect(meta?.status).toBe("completed");
  2218. });
  2219. syncer.disposeAll();
  2220. restartEmitter.dispose();
  2221. env.indexEmitter.dispose();
  2222. env.configEmitter.dispose();
  2223. });
  2224. it("dispose clears staged frames and unsubscribes ACKs that resolve after close", async () => {
  2225. const env = setupEnv();
  2226. let resolveIndex!: (result: IndexSubscribeResult) => void;
  2227. vi.mocked(env.agent.subscribeSessionsIndexV4).mockImplementationOnce(
  2228. () => new Promise((resolve) => (resolveIndex = resolve)),
  2229. );
  2230. const syncer = createZCodeTaskIndexSyncer({
  2231. agentService: env.agent,
  2232. taskIndexRepo: env.repo,
  2233. });
  2234. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2235. await vi.waitFor(() => expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1));
  2236. env.indexEmitter.fire(indexSnapshotFrame([summaryOf("staged-after-close", "running")]));
  2237. syncer.disposeAll();
  2238. resolveIndex({
  2239. ack: {
  2240. subscriptionId: INDEX_SUBSCRIPTION_ID,
  2241. mode: "snapshot",
  2242. logEpoch: "epoch-test",
  2243. },
  2244. });
  2245. await vi.waitFor(() => {
  2246. expect(env.agent.unsubscribeSessionsIndexV4).toHaveBeenCalledWith(
  2247. expect.objectContaining({ subscriptionId: INDEX_SUBSCRIPTION_ID }),
  2248. );
  2249. expect(env.agent.unsubscribeWorkspaceConfigV4).toHaveBeenCalledWith(
  2250. expect.objectContaining({ subscriptionId: CONFIG_SUBSCRIPTION_ID }),
  2251. );
  2252. });
  2253. env.indexEmitter.dispose();
  2254. env.configEmitter.dispose();
  2255. });
  2256. it("staging overflow 自动恢复且不会永久 freeze", async () => {
  2257. const env = setupEnv({
  2258. initialSessions: [summaryOf(seedTarget.sessionId, "running")],
  2259. });
  2260. await seedRunningTask(env.repo);
  2261. let resolveIndex!: (result: IndexSubscribeResult) => void;
  2262. vi.mocked(env.agent.subscribeSessionsIndexV4).mockImplementationOnce(
  2263. () => new Promise((resolve) => (resolveIndex = resolve)),
  2264. );
  2265. const syncer = createZCodeTaskIndexSyncer({
  2266. agentService: env.agent,
  2267. taskIndexRepo: env.repo,
  2268. });
  2269. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2270. await vi.waitFor(() => expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1));
  2271. for (let index = 0; index < 1_025; index += 1) {
  2272. env.indexEmitter.fire({
  2273. ...indexSnapshotFrame([summaryOf(seedTarget.sessionId, "running")]),
  2274. toSeq: index,
  2275. });
  2276. }
  2277. resolveIndex({
  2278. ack: {
  2279. subscriptionId: INDEX_SUBSCRIPTION_ID,
  2280. mode: "snapshot",
  2281. logEpoch: "epoch-test",
  2282. },
  2283. });
  2284. await new Promise((resolve) => setImmediate(resolve));
  2285. // pre-ACK overflow 没有可证明 base,必须仅换代 index topic 的 fresh snapshot。
  2286. await vi.waitFor(() => expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(2));
  2287. expect(env.agent.resyncSessionsIndexV4).not.toHaveBeenCalled();
  2288. expect(env.agent.subscribeWorkspaceConfigV4).toHaveBeenCalledTimes(1);
  2289. expect(env.agent.subscribeSessionsIndexV4).toHaveBeenLastCalledWith(
  2290. expect.objectContaining({
  2291. workspacePath: "/repo",
  2292. visibility: "background",
  2293. subscriberScope: "task-index",
  2294. runtimePolicy: "existing-only",
  2295. }),
  2296. );
  2297. env.indexEmitter.fire(indexUpsertFrame(summaryOf(seedTarget.sessionId, "completedSuccess"), 2));
  2298. await vi.waitFor(async () => {
  2299. const meta = await env.repo.getTaskMeta({
  2300. workspacePath: seedTarget.workspacePath,
  2301. taskId: seedTarget.sessionId,
  2302. });
  2303. expect(meta?.status).toBe("completed");
  2304. });
  2305. syncer.disposeAll();
  2306. env.indexEmitter.dispose();
  2307. env.configEmitter.dispose();
  2308. });
  2309. it("sessions-index initial assembly fault 不拿 ACK epoch 伪造 base,强制恢复冷 baseline", async () => {
  2310. const cold = summaryOf(seedTarget.sessionId, "running");
  2311. const env = setupEnv();
  2312. await seedRunningTask(env.repo);
  2313. vi.mocked(env.agent.subscribeSessionsIndexV4).mockImplementationOnce(async () => {
  2314. // ACK 前到达但 logical payload 非法:activation 后 assembler 产 typed fault,
  2315. // 这时客户端尚未原子 apply 任何 snapshot,ACK 本身不能证明 base=(epoch,0)。
  2316. env.indexEmitter.fire(
  2317. {
  2318. topic: "sessions-index//repo",
  2319. subscriptionId: INDEX_SUBSCRIPTION_ID,
  2320. fromSeq: 0,
  2321. toSeq: 0,
  2322. sentAt: 1,
  2323. payload: { kind: "deltas", deltas: [{ op: "invalid" }] },
  2324. } as unknown as SessionsIndexTopicFrame,
  2325. "initial",
  2326. );
  2327. return {
  2328. ack: {
  2329. subscriptionId: INDEX_SUBSCRIPTION_ID,
  2330. mode: "snapshot" as const,
  2331. logEpoch: "epoch-test",
  2332. },
  2333. };
  2334. });
  2335. let releaseRecovery!: () => void;
  2336. vi.mocked(env.agent.resyncSessionsIndexV4).mockImplementationOnce(
  2337. (params) =>
  2338. new Promise<IndexResyncResult>((resolve) => {
  2339. releaseRecovery = () => {
  2340. env.indexEmitter.fire(indexSnapshotFrame([cold], 1), "recovery");
  2341. resolve({
  2342. ack: {
  2343. subscriptionId: params.subscriptionId,
  2344. mode: "snapshot",
  2345. logEpoch: "epoch-test",
  2346. },
  2347. });
  2348. };
  2349. }),
  2350. );
  2351. const syncer = createZCodeTaskIndexSyncer({
  2352. agentService: env.agent,
  2353. taskIndexRepo: env.repo,
  2354. });
  2355. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2356. await vi.waitFor(() =>
  2357. expect(env.agent.resyncSessionsIndexV4).toHaveBeenCalledWith(
  2358. expect.objectContaining({
  2359. workspacePath: "/repo",
  2360. subscriptionId: INDEX_SUBSCRIPTION_ID,
  2361. base: null,
  2362. forceSnapshot: true,
  2363. }),
  2364. ),
  2365. );
  2366. // 整个 initial batch 丢失后,数值上衔接的 online delta 也不能抢先建立 baseline。
  2367. env.indexEmitter.fire(indexUpsertFrame(summaryOf(seedTarget.sessionId, "completedSuccess"), 1));
  2368. await new Promise((resolve) => setImmediate(resolve));
  2369. expect(
  2370. (
  2371. await env.repo.getTaskMeta({
  2372. workspacePath: seedTarget.workspacePath,
  2373. taskId: seedTarget.sessionId,
  2374. })
  2375. )?.status,
  2376. ).toBeUndefined();
  2377. releaseRecovery();
  2378. await new Promise((resolve) => setImmediate(resolve));
  2379. env.indexEmitter.fire(indexUpsertFrame(summaryOf(seedTarget.sessionId, "completedSuccess"), 2));
  2380. await vi.waitFor(async () => {
  2381. expect(
  2382. (
  2383. await env.repo.getTaskMeta({
  2384. workspacePath: seedTarget.workspacePath,
  2385. taskId: seedTarget.sessionId,
  2386. })
  2387. )?.status,
  2388. ).toBe("completed");
  2389. });
  2390. syncer.disposeAll();
  2391. env.indexEmitter.dispose();
  2392. env.configEmitter.dispose();
  2393. });
  2394. it("workspace-config initial assembly fault 仅以已 apply 状态为 base", async () => {
  2395. const env = setupEnv();
  2396. const recoveredConfig: WorkspaceConfigState = {
  2397. configOptions: [
  2398. {
  2399. id: "model",
  2400. name: "Model",
  2401. type: "select",
  2402. currentValue: "anthropic/haiku",
  2403. options: [],
  2404. },
  2405. ],
  2406. slashCommands: [],
  2407. };
  2408. vi.mocked(env.agent.subscribeWorkspaceConfigV4).mockImplementationOnce(async () => {
  2409. env.configEmitter.fire(
  2410. {
  2411. topic: "workspace-config//repo",
  2412. subscriptionId: CONFIG_SUBSCRIPTION_ID,
  2413. fromSeq: 0,
  2414. toSeq: 0,
  2415. sentAt: 1,
  2416. payload: { kind: "deltas", deltas: [{ op: "invalid" }] },
  2417. } as unknown as WorkspaceConfigTopicFrame,
  2418. "initial",
  2419. );
  2420. return {
  2421. ack: {
  2422. subscriptionId: CONFIG_SUBSCRIPTION_ID,
  2423. mode: "snapshot" as const,
  2424. logEpoch: "epoch-cfg",
  2425. },
  2426. };
  2427. });
  2428. vi.mocked(env.agent.resyncWorkspaceConfigV4).mockImplementationOnce(async (params) => {
  2429. if (params.forceSnapshot) {
  2430. env.configEmitter.fire(configFrame(recoveredConfig, 1), "recovery");
  2431. } else {
  2432. env.configEmitter.fire(
  2433. {
  2434. topic: "workspace-config//repo",
  2435. subscriptionId: CONFIG_SUBSCRIPTION_ID,
  2436. fromSeq: 0,
  2437. toSeq: 0,
  2438. sentAt: 2,
  2439. payload: { kind: "deltas", deltas: [] },
  2440. },
  2441. "recovery",
  2442. );
  2443. }
  2444. return {
  2445. ack: {
  2446. subscriptionId: params.subscriptionId,
  2447. mode: params.forceSnapshot ? ("snapshot" as const) : ("resume" as const),
  2448. logEpoch: "epoch-cfg",
  2449. },
  2450. };
  2451. });
  2452. const syncer = createZCodeTaskIndexSyncer({
  2453. agentService: env.agent,
  2454. taskIndexRepo: env.repo,
  2455. });
  2456. const workspaceEvents: ZCodeWorkspaceEvent[] = [];
  2457. syncer.onDynamicWorkspaceEvent({ workspacePath: "/repo" })((event) =>
  2458. workspaceEvents.push(event),
  2459. );
  2460. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2461. await vi.waitFor(() =>
  2462. expect(env.agent.resyncWorkspaceConfigV4).toHaveBeenCalledWith(
  2463. expect.objectContaining({
  2464. workspacePath: "/repo",
  2465. subscriptionId: CONFIG_SUBSCRIPTION_ID,
  2466. base: null,
  2467. forceSnapshot: true,
  2468. }),
  2469. ),
  2470. );
  2471. await vi.waitFor(() =>
  2472. expect(
  2473. workspaceEvents.some(
  2474. (event) =>
  2475. event.type === "workspace_config_options_update" &&
  2476. event.configOptions[0]?.currentValue === "anthropic/haiku",
  2477. ),
  2478. ).toBe(true),
  2479. );
  2480. syncer.disposeAll();
  2481. env.indexEmitter.dispose();
  2482. env.configEmitter.dispose();
  2483. });
  2484. it("sessions-index gap 只恢复 index,workspace-config sibling 保持可用", async () => {
  2485. const env = setupEnv({
  2486. initialSessions: [summaryOf(seedTarget.sessionId, "running")],
  2487. });
  2488. await seedRunningTask(env.repo);
  2489. const syncer = createZCodeTaskIndexSyncer({
  2490. agentService: env.agent,
  2491. taskIndexRepo: env.repo,
  2492. });
  2493. const workspaceEvents: ZCodeWorkspaceEvent[] = [];
  2494. syncer.onDynamicWorkspaceEvent({ workspacePath: "/repo" })((event) =>
  2495. workspaceEvents.push(event),
  2496. );
  2497. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2498. await subscribed(env);
  2499. env.indexEmitter.fire(
  2500. indexUpsertFrame(summaryOf(seedTarget.sessionId, "completedSuccess"), 99),
  2501. );
  2502. await vi.waitFor(() => expect(env.agent.resyncSessionsIndexV4).toHaveBeenCalledTimes(1));
  2503. expect(env.agent.resyncWorkspaceConfigV4).not.toHaveBeenCalled();
  2504. expect(env.agent.subscribeWorkspaceConfigV4).toHaveBeenCalledTimes(1);
  2505. env.configEmitter.fire(
  2506. configFrame({
  2507. configOptions: [
  2508. {
  2509. id: "model",
  2510. name: "Model",
  2511. category: "model",
  2512. type: "select",
  2513. currentValue: "anthropic/haiku",
  2514. options: [],
  2515. },
  2516. ],
  2517. slashCommands: [],
  2518. }),
  2519. );
  2520. await vi.waitFor(() =>
  2521. expect(
  2522. workspaceEvents.some((event) => event.type === "workspace_config_options_update"),
  2523. ).toBe(true),
  2524. );
  2525. syncer.disposeAll();
  2526. env.indexEmitter.dispose();
  2527. env.configEmitter.dispose();
  2528. });
  2529. it("recovery assembly fault 早于 snapshot ACK 时 fresh-subscribe index 而不悬空 flight", async () => {
  2530. const env = setupEnv({
  2531. initialSessions: [summaryOf(seedTarget.sessionId, "running")],
  2532. });
  2533. let resolveResync!: (result: IndexResyncResult) => void;
  2534. vi.mocked(env.agent.resyncSessionsIndexV4).mockImplementationOnce(
  2535. () => new Promise((resolve) => (resolveResync = resolve)),
  2536. );
  2537. const syncer = createZCodeTaskIndexSyncer({
  2538. agentService: env.agent,
  2539. taskIndexRepo: env.repo,
  2540. });
  2541. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2542. await subscribed(env);
  2543. // online gap 启动 same-sub recovery。
  2544. env.indexEmitter.fire(indexUpsertFrame(summaryOf(seedTarget.sessionId, "running"), 99));
  2545. await vi.waitFor(() => expect(env.agent.resyncSessionsIndexV4).toHaveBeenCalledTimes(1));
  2546. // 同 ordinal 不同 logical id 产生 typed fault;deliveryKind 在 fault.fault 层。
  2547. const invalidRecoveryFrame = indexUpsertFrame(
  2548. summaryOf(seedTarget.sessionId, "completedSuccess"),
  2549. 100,
  2550. );
  2551. env.indexEmitter.fireWire({
  2552. wireVersion: 3,
  2553. kind: "complete",
  2554. deliveryKind: "recovery",
  2555. logicalFrameId: "conflicting-recovery-id",
  2556. logicalFrameOrdinal: 2,
  2557. topic: invalidRecoveryFrame.topic,
  2558. subscriptionId: invalidRecoveryFrame.subscriptionId,
  2559. frame: invalidRecoveryFrame,
  2560. });
  2561. resolveResync({
  2562. ack: {
  2563. subscriptionId: INDEX_SUBSCRIPTION_ID,
  2564. mode: "snapshot",
  2565. logEpoch: "epoch-test",
  2566. },
  2567. });
  2568. await vi.waitFor(() => expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(2));
  2569. expect(env.agent.subscribeWorkspaceConfigV4).toHaveBeenCalledTimes(1);
  2570. syncer.disposeAll();
  2571. env.indexEmitter.dispose();
  2572. env.configEmitter.dispose();
  2573. });
  2574. it("recovery flight 中缺失 deliveryKind 的 owned fault 会升级强制 snapshot", async () => {
  2575. const env = setupEnv({
  2576. initialSessions: [summaryOf(seedTarget.sessionId, "running")],
  2577. });
  2578. const syncer = createZCodeTaskIndexSyncer({
  2579. agentService: env.agent,
  2580. taskIndexRepo: env.repo,
  2581. });
  2582. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2583. await subscribed(env);
  2584. env.indexEmitter.fire(indexUpsertFrame(summaryOf(seedTarget.sessionId, "running"), 99));
  2585. await vi.waitFor(() => expect(env.agent.resyncSessionsIndexV4).toHaveBeenCalledTimes(1));
  2586. const invalid = indexUpsertFrame(summaryOf(seedTarget.sessionId, "running"), 100);
  2587. env.indexEmitter.fireWire({
  2588. wireVersion: 3,
  2589. kind: "complete",
  2590. // candidate 允许先进 owned assembler 再产生 typed fault;此处故意伪造非法值。
  2591. deliveryKind: "invalid-kind",
  2592. logicalFrameId: "invalid-delivery-kind",
  2593. logicalFrameOrdinal: 3,
  2594. topic: invalid.topic,
  2595. subscriptionId: invalid.subscriptionId,
  2596. frame: invalid,
  2597. } as unknown as SessionsIndexTopicWireFrame);
  2598. await vi.waitFor(() => expect(env.agent.resyncSessionsIndexV4).toHaveBeenCalledTimes(2));
  2599. expect(vi.mocked(env.agent.resyncSessionsIndexV4).mock.calls[1]?.[0]).toMatchObject({
  2600. subscriptionId: INDEX_SUBSCRIPTION_ID,
  2601. base: null,
  2602. forceSnapshot: true,
  2603. });
  2604. syncer.disposeAll();
  2605. env.indexEmitter.dispose();
  2606. env.configEmitter.dispose();
  2607. });
  2608. it("workspace-config recovery gap 早于 snapshot ACK 时仅 fresh-subscribe config", async () => {
  2609. const env = setupEnv();
  2610. let resolveResync!: (result: ConfigResyncResult) => void;
  2611. vi.mocked(env.agent.resyncWorkspaceConfigV4).mockImplementationOnce(
  2612. () => new Promise((resolve) => (resolveResync = resolve)),
  2613. );
  2614. const syncer = createZCodeTaskIndexSyncer({
  2615. agentService: env.agent,
  2616. taskIndexRepo: env.repo,
  2617. });
  2618. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2619. await subscribed(env);
  2620. const config: WorkspaceConfigState = {
  2621. configOptions: [
  2622. {
  2623. id: "model",
  2624. name: "Model",
  2625. type: "select",
  2626. currentValue: "anthropic/haiku",
  2627. options: [],
  2628. },
  2629. ],
  2630. slashCommands: [],
  2631. };
  2632. env.configEmitter.fire(configFrame(config));
  2633. env.configEmitter.fire(configDeltaFrame(config, 99));
  2634. await vi.waitFor(() => expect(env.agent.resyncWorkspaceConfigV4).toHaveBeenCalledTimes(1));
  2635. env.configEmitter.fire(configDeltaFrame(config, 100), "recovery");
  2636. resolveResync({
  2637. ack: {
  2638. subscriptionId: CONFIG_SUBSCRIPTION_ID,
  2639. mode: "snapshot",
  2640. logEpoch: "epoch-cfg",
  2641. },
  2642. });
  2643. await vi.waitFor(() => expect(env.agent.subscribeWorkspaceConfigV4).toHaveBeenCalledTimes(2));
  2644. expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  2645. syncer.disposeAll();
  2646. env.indexEmitter.dispose();
  2647. env.configEmitter.dispose();
  2648. });
  2649. it("sessions-index duplicate delta 静默丢弃且不重复发射 terminal", async () => {
  2650. const env = setupEnv({
  2651. initialSessions: [summaryOf(seedTarget.sessionId, "running")],
  2652. });
  2653. await seedRunningTask(env.repo);
  2654. const syncer = createZCodeTaskIndexSyncer({
  2655. agentService: env.agent,
  2656. taskIndexRepo: env.repo,
  2657. });
  2658. const terminals: string[] = [];
  2659. syncer.onSessionTerminalEvent((event) => terminals.push(event.kind));
  2660. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2661. await subscribed(env);
  2662. env.indexEmitter.fire(indexUpsertFrame(summaryOf(seedTarget.sessionId, "completedSuccess"), 2));
  2663. await vi.waitFor(() => expect(terminals).toEqual(["turn.completed"]));
  2664. env.indexEmitter.fire(indexUpsertFrame(summaryOf(seedTarget.sessionId, "error"), 2));
  2665. await new Promise((resolve) => setImmediate(resolve));
  2666. expect(terminals).toEqual(["turn.completed"]);
  2667. expect(env.agent.resyncSessionsIndexV4).not.toHaveBeenCalled();
  2668. syncer.disposeAll();
  2669. env.indexEmitter.dispose();
  2670. env.configEmitter.dispose();
  2671. });
  2672. it("sessions-index recovery 后同 read residual online gap 启动 successor", async () => {
  2673. const env = setupEnv({
  2674. initialSessions: [summaryOf(seedTarget.sessionId, "running")],
  2675. });
  2676. await seedRunningTask(env.repo);
  2677. let attempt = 0;
  2678. vi.mocked(env.agent.resyncSessionsIndexV4).mockImplementation(async (params) => {
  2679. attempt += 1;
  2680. if (attempt === 1) {
  2681. env.indexEmitter.fire(
  2682. indexUpsertFrame(summaryOf(seedTarget.sessionId, "completedSuccess"), 2),
  2683. "recovery",
  2684. );
  2685. env.indexEmitter.fire(
  2686. indexUpsertFrame(summaryOf(seedTarget.sessionId, "completedSuccess"), 4),
  2687. "online",
  2688. );
  2689. } else {
  2690. env.indexEmitter.fire(
  2691. {
  2692. topic: "sessions-index//repo",
  2693. subscriptionId: INDEX_SUBSCRIPTION_ID,
  2694. fromSeq: 2,
  2695. toSeq: 2,
  2696. sentAt: 4,
  2697. payload: { kind: "deltas", deltas: [] },
  2698. },
  2699. "recovery",
  2700. );
  2701. }
  2702. return {
  2703. ack: {
  2704. subscriptionId: params.subscriptionId,
  2705. mode: "resume" as const,
  2706. logEpoch: "epoch-test",
  2707. },
  2708. };
  2709. });
  2710. const syncer = createZCodeTaskIndexSyncer({
  2711. agentService: env.agent,
  2712. taskIndexRepo: env.repo,
  2713. });
  2714. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2715. await subscribed(env);
  2716. env.indexEmitter.fire(indexUpsertFrame(summaryOf(seedTarget.sessionId, "completedSuccess"), 3));
  2717. await vi.waitFor(async () => {
  2718. expect(env.agent.resyncSessionsIndexV4).toHaveBeenCalledTimes(2);
  2719. expect(
  2720. (
  2721. await env.repo.getTaskMeta({
  2722. workspacePath: seedTarget.workspacePath,
  2723. taskId: seedTarget.sessionId,
  2724. })
  2725. )?.status,
  2726. ).toBe("completed");
  2727. });
  2728. expect(vi.mocked(env.agent.resyncSessionsIndexV4).mock.calls[1]?.[0]).toMatchObject({
  2729. subscriptionId: INDEX_SUBSCRIPTION_ID,
  2730. base: { logEpoch: "epoch-test", seq: 2 },
  2731. });
  2732. expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  2733. syncer.disposeAll();
  2734. env.indexEmitter.dispose();
  2735. env.configEmitter.dispose();
  2736. });
  2737. it("workspace-config recovery 后 residual online gap 只启动 config successor", async () => {
  2738. const env = setupEnv();
  2739. const config: WorkspaceConfigState = {
  2740. configOptions: [
  2741. {
  2742. id: "model",
  2743. name: "Model",
  2744. type: "select",
  2745. currentValue: "anthropic/haiku",
  2746. options: [],
  2747. },
  2748. ],
  2749. slashCommands: [],
  2750. };
  2751. let attempt = 0;
  2752. vi.mocked(env.agent.resyncWorkspaceConfigV4).mockImplementation(async (params) => {
  2753. attempt += 1;
  2754. if (attempt === 1) {
  2755. env.configEmitter.fire(configDeltaFrame(config, 2), "recovery");
  2756. env.configEmitter.fire(configDeltaFrame(config, 4), "online");
  2757. } else {
  2758. env.configEmitter.fire(
  2759. {
  2760. topic: "workspace-config//repo",
  2761. subscriptionId: CONFIG_SUBSCRIPTION_ID,
  2762. fromSeq: 2,
  2763. toSeq: 2,
  2764. sentAt: 5,
  2765. payload: { kind: "deltas", deltas: [] },
  2766. },
  2767. "recovery",
  2768. );
  2769. }
  2770. return {
  2771. ack: { subscriptionId: params.subscriptionId, mode: "resume", logEpoch: "epoch-cfg" },
  2772. };
  2773. });
  2774. const syncer = createZCodeTaskIndexSyncer({
  2775. agentService: env.agent,
  2776. taskIndexRepo: env.repo,
  2777. });
  2778. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2779. await subscribed(env);
  2780. env.configEmitter.fire(configFrame(config, 1));
  2781. env.configEmitter.fire(configDeltaFrame(config, 3));
  2782. await vi.waitFor(() => expect(env.agent.resyncWorkspaceConfigV4).toHaveBeenCalledTimes(2));
  2783. expect(vi.mocked(env.agent.resyncWorkspaceConfigV4).mock.calls[1]?.[0]).toMatchObject({
  2784. subscriptionId: CONFIG_SUBSCRIPTION_ID,
  2785. base: { logEpoch: "epoch-cfg", seq: 2 },
  2786. });
  2787. expect(env.agent.resyncSessionsIndexV4).not.toHaveBeenCalled();
  2788. syncer.disposeAll();
  2789. env.indexEmitter.dispose();
  2790. env.configEmitter.dispose();
  2791. });
  2792. it("online snapshot 覆盖在途 recovery 后,重复 recovery 可正常收口", async () => {
  2793. const env = setupEnv({
  2794. initialSessions: [summaryOf(seedTarget.sessionId, "running")],
  2795. });
  2796. let resolveRecovery!: (result: IndexResyncResult) => void;
  2797. vi.mocked(env.agent.resyncSessionsIndexV4).mockImplementationOnce(
  2798. () => new Promise((resolve) => (resolveRecovery = resolve)),
  2799. );
  2800. const syncer = createZCodeTaskIndexSyncer({
  2801. agentService: env.agent,
  2802. taskIndexRepo: env.repo,
  2803. });
  2804. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2805. await subscribed(env);
  2806. env.indexEmitter.fire(indexUpsertFrame(summaryOf(seedTarget.sessionId, "running"), 3));
  2807. await vi.waitFor(() => expect(env.agent.resyncSessionsIndexV4).toHaveBeenCalledTimes(1));
  2808. env.indexEmitter.fire(indexSnapshotFrame([summaryOf(seedTarget.sessionId, "running")], 5));
  2809. env.indexEmitter.fire(
  2810. {
  2811. topic: "sessions-index//repo",
  2812. subscriptionId: INDEX_SUBSCRIPTION_ID,
  2813. fromSeq: 1,
  2814. toSeq: 5,
  2815. sentAt: 5,
  2816. payload: {
  2817. kind: "deltas",
  2818. deltas: [{ op: "session.upserted", session: summaryOf(seedTarget.sessionId, "running") }],
  2819. },
  2820. },
  2821. "recovery",
  2822. );
  2823. resolveRecovery({
  2824. ack: { subscriptionId: INDEX_SUBSCRIPTION_ID, mode: "resume", logEpoch: "epoch-test" },
  2825. });
  2826. await new Promise((resolve) => setImmediate(resolve));
  2827. expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  2828. expect(env.agent.resyncSessionsIndexV4).toHaveBeenCalledTimes(1);
  2829. syncer.disposeAll();
  2830. env.indexEmitter.dispose();
  2831. env.configEmitter.dispose();
  2832. });
  2833. it("index/config recovery ACK 后零 wire:30s 强制一次,再超时 topic-local fresh", async () => {
  2834. const env = setupEnv({
  2835. initialSessions: [summaryOf(seedTarget.sessionId, "running")],
  2836. });
  2837. const config: WorkspaceConfigState = {
  2838. configOptions: [
  2839. { id: "model", name: "Model", type: "select", currentValue: "m", options: [] },
  2840. ],
  2841. slashCommands: [],
  2842. };
  2843. const syncer = createZCodeTaskIndexSyncer({
  2844. agentService: env.agent,
  2845. taskIndexRepo: env.repo,
  2846. });
  2847. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2848. await subscribed(env);
  2849. env.configEmitter.fire(configFrame(config, 1));
  2850. vi.useFakeTimers();
  2851. try {
  2852. env.indexEmitter.fire(indexUpsertFrame(summaryOf(seedTarget.sessionId, "running"), 99));
  2853. env.configEmitter.fire(configDeltaFrame(config, 99));
  2854. await Promise.resolve();
  2855. await Promise.resolve();
  2856. expect(env.agent.resyncSessionsIndexV4).toHaveBeenCalledTimes(1);
  2857. expect(env.agent.resyncWorkspaceConfigV4).toHaveBeenCalledTimes(1);
  2858. await vi.advanceTimersByTimeAsync(PROTOCOL_V4_LIMITS.logicalFrameAssemblyTimeoutMs);
  2859. expect(env.agent.resyncSessionsIndexV4).toHaveBeenCalledTimes(2);
  2860. expect(env.agent.resyncWorkspaceConfigV4).toHaveBeenCalledTimes(2);
  2861. expect(vi.mocked(env.agent.resyncSessionsIndexV4).mock.calls[1]?.[0]).toMatchObject({
  2862. forceSnapshot: true,
  2863. });
  2864. expect(vi.mocked(env.agent.resyncWorkspaceConfigV4).mock.calls[1]?.[0]).toMatchObject({
  2865. forceSnapshot: true,
  2866. });
  2867. await vi.advanceTimersByTimeAsync(PROTOCOL_V4_LIMITS.logicalFrameAssemblyTimeoutMs);
  2868. expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(2);
  2869. expect(env.agent.subscribeWorkspaceConfigV4).toHaveBeenCalledTimes(2);
  2870. } finally {
  2871. syncer.disposeAll();
  2872. vi.useRealTimers();
  2873. env.indexEmitter.dispose();
  2874. env.configEmitter.dispose();
  2875. }
  2876. });
  2877. it("provider/model 未就绪时不写 warn,低频探测后自动恢复两个 topic", async () => {
  2878. const env = setupEnv();
  2879. const providerNotReadyError = Object.assign(
  2880. new Error("当前没有可用的模型供应商和模型,请先登录或配置 API Key。"),
  2881. { code: ZCODE_AGENT_PROVIDER_NOT_READY_CODE },
  2882. );
  2883. vi.mocked(env.agent.subscribeSessionsIndexV4).mockRejectedValueOnce(providerNotReadyError);
  2884. vi.mocked(env.agent.subscribeWorkspaceConfigV4).mockRejectedValueOnce(providerNotReadyError);
  2885. const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined);
  2886. const syncer = createZCodeTaskIndexSyncer({
  2887. agentService: env.agent,
  2888. taskIndexRepo: env.repo,
  2889. });
  2890. vi.useFakeTimers();
  2891. try {
  2892. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2893. await vi.advanceTimersByTimeAsync(0);
  2894. expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  2895. expect(env.agent.subscribeWorkspaceConfigV4).toHaveBeenCalledTimes(1);
  2896. expect(warnSpy).not.toHaveBeenCalled();
  2897. await vi.advanceTimersByTimeAsync(4_999);
  2898. expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  2899. expect(env.agent.subscribeWorkspaceConfigV4).toHaveBeenCalledTimes(1);
  2900. await vi.advanceTimersByTimeAsync(1);
  2901. expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(2);
  2902. expect(env.agent.subscribeWorkspaceConfigV4).toHaveBeenCalledTimes(2);
  2903. expect(warnSpy).not.toHaveBeenCalled();
  2904. } finally {
  2905. syncer.disposeAll();
  2906. vi.useRealTimers();
  2907. warnSpy.mockRestore();
  2908. env.indexEmitter.dispose();
  2909. env.configEmitter.dispose();
  2910. }
  2911. });
  2912. it("持续订阅故障使用固定 retry reason,并将相同 topic 的 warn 限频到每分钟一次", async () => {
  2913. const env = setupEnv();
  2914. const persistentError = new Error("persistent topic failure");
  2915. vi.mocked(env.agent.subscribeSessionsIndexV4).mockRejectedValue(persistentError);
  2916. vi.mocked(env.agent.subscribeWorkspaceConfigV4).mockRejectedValue(persistentError);
  2917. const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined);
  2918. const syncer = createZCodeTaskIndexSyncer({
  2919. agentService: env.agent,
  2920. taskIndexRepo: env.repo,
  2921. });
  2922. vi.useFakeTimers();
  2923. try {
  2924. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  2925. await vi.advanceTimersByTimeAsync(0);
  2926. expect(warnSpy).toHaveBeenCalledTimes(2);
  2927. await vi.advanceTimersByTimeAsync(59_999);
  2928. expect(warnSpy).toHaveBeenCalledTimes(2);
  2929. await vi.advanceTimersByTimeAsync(1_000);
  2930. expect(warnSpy).toHaveBeenCalledTimes(4);
  2931. const messages = warnSpy.mock.calls.map((call) => String(call[1]));
  2932. expect(messages.filter((message) => message.includes("reason=initial"))).toHaveLength(2);
  2933. expect(messages.filter((message) => message.includes("reason=retry"))).toHaveLength(2);
  2934. expect(messages.every((message) => !message.includes("retry:retry"))).toBe(true);
  2935. } finally {
  2936. syncer.disposeAll();
  2937. vi.useRealTimers();
  2938. warnSpy.mockRestore();
  2939. env.indexEmitter.dispose();
  2940. env.configEmitter.dispose();
  2941. }
  2942. });
  2943. // M5 ③-2(CLI 重连重订):进程换代后订阅静默失活,syncer 必须重发 subscribe
  2944. // 并按新 subscriptionId 闸门继续摄入帧。
  2945. it("re-subscribes workspace topics after an agent runtime restart and accepts new-generation frames", async () => {
  2946. const env = setupEnv({
  2947. initialSessions: [summaryOf(seedTarget.sessionId, "running")],
  2948. });
  2949. await seedRunningTask(env.repo);
  2950. const restartEmitter = new Emitter<{ workspaceKey: string }>();
  2951. (env.agent as { onAgentRuntimeRestarted?: unknown }).onAgentRuntimeRestarted =
  2952. restartEmitter.event;
  2953. // 第二代订阅换 id:重启后旧 id 的帧必须被闸门丢弃,新 id 的帧被接受。
  2954. vi.mocked(env.agent.subscribeSessionsIndexV4)
  2955. .mockImplementationOnce(async () => {
  2956. env.indexEmitter.fire(indexSnapshotFrame([summaryOf(seedTarget.sessionId, "running")]));
  2957. return {
  2958. ack: {
  2959. subscriptionId: INDEX_SUBSCRIPTION_ID,
  2960. mode: "snapshot" as const,
  2961. logEpoch: "epoch-test",
  2962. },
  2963. };
  2964. })
  2965. .mockImplementationOnce(async () => {
  2966. env.indexEmitter.fire({
  2967. ...indexSnapshotFrame([summaryOf(seedTarget.sessionId, "running")]),
  2968. subscriptionId: "six-test-2",
  2969. });
  2970. return {
  2971. ack: {
  2972. subscriptionId: "six-test-2",
  2973. mode: "snapshot" as const,
  2974. logEpoch: "epoch-test-2",
  2975. },
  2976. };
  2977. });
  2978. const syncer = createZCodeTaskIndexSyncer({
  2979. agentService: env.agent,
  2980. taskIndexRepo: env.repo,
  2981. });
  2982. syncer.ensureSessionSubscription(seedTarget);
  2983. await subscribed(env);
  2984. expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(1);
  2985. restartEmitter.fire({ workspaceKey: seedTarget.workspacePath });
  2986. await vi.waitFor(() => {
  2987. expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(2);
  2988. expect(env.agent.subscribeWorkspaceConfigV4).toHaveBeenCalledTimes(2);
  2989. });
  2990. await new Promise((resolve) => setImmediate(resolve));
  2991. // 新代际帧(新 subscriptionId)驱动终态写入。
  2992. env.indexEmitter.fire({
  2993. ...indexUpsertFrame(summaryOf(seedTarget.sessionId, "completedSuccess")),
  2994. subscriptionId: "six-test-2",
  2995. });
  2996. await vi.waitFor(async () => {
  2997. const meta = await env.repo.getTaskMeta({
  2998. workspacePath: seedTarget.workspacePath,
  2999. taskId: seedTarget.sessionId,
  3000. });
  3001. expect(meta?.status).toBe("completed");
  3002. });
  3003. syncer.disposeAll();
  3004. restartEmitter.dispose();
  3005. env.indexEmitter.dispose();
  3006. env.configEmitter.dispose();
  3007. });
  3008. it("runtime restart 后 sessions-index 暂态失败独立重试,config 不被撤销", async () => {
  3009. const env = setupEnv({
  3010. initialSessions: [summaryOf(seedTarget.sessionId, "running")],
  3011. });
  3012. const restartEmitter = new Emitter<{ workspaceKey: string }>();
  3013. (env.agent as { onAgentRuntimeRestarted?: unknown }).onAgentRuntimeRestarted =
  3014. restartEmitter.event;
  3015. vi.mocked(env.agent.subscribeSessionsIndexV4)
  3016. .mockImplementationOnce(async () => {
  3017. env.indexEmitter.fire(
  3018. indexSnapshotFrame([summaryOf(seedTarget.sessionId, "running")]),
  3019. "initial",
  3020. );
  3021. return {
  3022. ack: {
  3023. subscriptionId: INDEX_SUBSCRIPTION_ID,
  3024. mode: "snapshot" as const,
  3025. logEpoch: "epoch-test",
  3026. },
  3027. };
  3028. })
  3029. .mockRejectedValueOnce(new Error("transient restart failure"))
  3030. .mockImplementationOnce(async () => {
  3031. env.indexEmitter.fire(
  3032. {
  3033. ...indexSnapshotFrame([summaryOf(seedTarget.sessionId, "running")]),
  3034. subscriptionId: "six-test-3",
  3035. },
  3036. "initial",
  3037. );
  3038. return {
  3039. ack: {
  3040. subscriptionId: "six-test-3",
  3041. mode: "snapshot" as const,
  3042. logEpoch: "epoch-test-3",
  3043. },
  3044. };
  3045. });
  3046. const syncer = createZCodeTaskIndexSyncer({
  3047. agentService: env.agent,
  3048. taskIndexRepo: env.repo,
  3049. });
  3050. syncer.ensureWorkspaceSubscription({ workspacePath: "/repo" });
  3051. await subscribed(env);
  3052. restartEmitter.fire({ workspaceKey: "/repo" });
  3053. await vi.waitFor(() => {
  3054. expect(env.agent.subscribeSessionsIndexV4).toHaveBeenCalledTimes(3);
  3055. expect(env.agent.subscribeWorkspaceConfigV4).toHaveBeenCalledTimes(2);
  3056. });
  3057. // config 一次就成功,不跟随 index retry 重订。
  3058. await new Promise((resolve) => setTimeout(resolve, 75));
  3059. expect(env.agent.subscribeWorkspaceConfigV4).toHaveBeenCalledTimes(2);
  3060. syncer.disposeAll();
  3061. restartEmitter.dispose();
  3062. env.indexEmitter.dispose();
  3063. env.configEmitter.dispose();
  3064. });
  3065. it("ignores ensureSessionSubscription after disposeAll", () => {
  3066. const env = setupEnv();
  3067. const syncer = createZCodeTaskIndexSyncer({
  3068. agentService: env.agent,
  3069. taskIndexRepo: env.repo,
  3070. });
  3071. syncer.disposeAll();
  3072. syncer.ensureSessionSubscription(seedTarget);
  3073. expect(env.agent.subscribeSessionsIndexV4).not.toHaveBeenCalled();
  3074. env.indexEmitter.dispose();
  3075. env.configEmitter.dispose();
  3076. });
  3077. it("shares the same workspace emitter across getWorkspaceEmitter and onDynamicWorkspaceEvent", () => {
  3078. const env = setupEnv();
  3079. const syncer = createZCodeTaskIndexSyncer({
  3080. agentService: env.agent,
  3081. taskIndexRepo: env.repo,
  3082. });
  3083. const received: ZCodeWorkspaceEvent[] = [];
  3084. const subscription = syncer.onDynamicWorkspaceEvent({
  3085. workspacePath: "/repo",
  3086. })((event) => received.push(event));
  3087. // adapter 通过 getWorkspaceEmitter 直接 fire 其他类型事件时,订阅者也应该能收到
  3088. syncer.getWorkspaceEmitter({ workspacePath: "/repo" }).fire({
  3089. type: "workspace_config_options_update",
  3090. workspacePath: "/repo",
  3091. configOptions: [],
  3092. } as ZCodeWorkspaceEvent);
  3093. expect(received.length).toBe(1);
  3094. expect(received[0].type).toBe("workspace_config_options_update");
  3095. subscription.dispose();
  3096. syncer.disposeAll();
  3097. });
  3098. });