v4-gateway-sessions-index.test.ts 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192
  1. // ConversationV4Gateway 的 sessions-index 集成测试(M5 ①,14-sessions-index):
  2. // 1. subscribeSessionsIndex:store 摘要种子 + 已加载会话 live 投影覆盖 → snapshot 帧
  3. // 2. ingest 非流式事件 → 列表订阅者收到 session.upserted 增量帧(流式 ModelStreaming 不触发)
  4. // 3. disposeSession → session.removed 增量帧
  5. // 4. 无 getSessionWorkspaceId 的旧宿主 → sessions-index 路径整体 no-op,不影响 conversation
  6. // 5. unsubscribeSessionsIndex 后不再收帧
  7. // 6. DynamicWorkflowRunProgress 按 leading + trailing 窗口节流(14-sessions-index「事件 fan-out 节奏」)
  8. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  9. import type {
  10. EventId,
  11. SessionEvent,
  12. SessionEventType as SessionEventTypeUnion,
  13. SessionId,
  14. TraceId,
  15. TurnId,
  16. } from "@zcode/contracts";
  17. import { SessionEventType } from "@zcode/contracts";
  18. import type {
  19. ConversationTopicFrame,
  20. SessionSummary,
  21. SessionsIndexTopicFrame,
  22. } from "@zcode/shared/zcode-protocol-v4";
  23. import { ConversationV4Gateway } from "../src/zcode-protocol-v4/index.js";
  24. type AnyFrame = ConversationTopicFrame | SessionsIndexTopicFrame;
  25. function event(
  26. sessionId: string,
  27. seq: number,
  28. type: SessionEventTypeUnion,
  29. payload: unknown,
  30. turnId?: string,
  31. ): SessionEvent {
  32. return {
  33. id: `event-${sessionId}-${seq}` as EventId,
  34. sessionId: sessionId as SessionId,
  35. turnId: turnId as TurnId | undefined,
  36. type,
  37. timestamp: new Date(1_700_000_000_000 + seq * 1000),
  38. traceId: "trace-1" as TraceId,
  39. sequenceNumber: seq,
  40. payload,
  41. };
  42. }
  43. function storedSummary(sessionId: string): SessionSummary {
  44. return {
  45. sessionId,
  46. workspaceId: "ws-1",
  47. title: `stored-${sessionId}`,
  48. phase: "completedSuccess",
  49. sessionEnded: true,
  50. hasBackgroundWork: false,
  51. lastActivityAt: 50,
  52. createdAt: 10,
  53. };
  54. }
  55. interface Stub {
  56. frames: AnyFrame[];
  57. sessions: Set<string>;
  58. sessionWorkspace: Map<string, string>;
  59. stored: SessionSummary[];
  60. /** 模拟 record.updatedAt:每条活动事件都会 bump,摘要因此条条有变化。 */
  61. lastActivityAt?: number;
  62. drafts?: Set<string>;
  63. executeCommand?: ConstructorParameters<typeof ConversationV4Gateway>[0]["executeCommand"];
  64. loadPersistedEvents?: (sessionId: string) => Promise<{
  65. events: SessionEvent[];
  66. synthesized: boolean;
  67. sourceEventSeq?: number;
  68. }>;
  69. loadStored?: (
  70. workspaceId: string,
  71. legacyTaskIds?: readonly string[],
  72. ) => Promise<SessionSummary[]> | SessionSummary[];
  73. }
  74. function makeGateway(stub: Stub, opts: { withIndexHooks: boolean }) {
  75. return new ConversationV4Gateway(
  76. {
  77. sessionExists: (sessionId) => stub.sessions.has(sessionId),
  78. emitWireFrame: (wire) => {
  79. if (wire.kind !== "complete") {
  80. throw new Error("sessions-index test adapter only accepts complete wires");
  81. }
  82. stub.frames.push(wire.frame);
  83. },
  84. executeCommand: (...args) => stub.executeCommand?.(...args) ?? Promise.resolve(undefined),
  85. loadPersistedEvents: async (sessionId) =>
  86. stub.loadPersistedEvents?.(sessionId) ?? { events: [], synthesized: false },
  87. ...(opts.withIndexHooks
  88. ? {
  89. getSessionWorkspaceId: (sessionId: string) =>
  90. stub.sessionWorkspace.get(sessionId) ?? null,
  91. getSessionIndexMeta: () => ({
  92. createdAt: 10,
  93. lastActivityAt: stub.lastActivityAt ?? 99,
  94. }),
  95. listWorkspaceSessionIds: (workspaceId: string) =>
  96. [...stub.sessionWorkspace.entries()]
  97. .filter(([, ws]) => ws === workspaceId)
  98. .map(([id]) => id),
  99. getStoredSessionSummaries: (workspaceId: string) =>
  100. stub.loadStored?.(workspaceId) ?? stub.stored,
  101. refreshLegacySessionSummaries: (
  102. workspaceId: string,
  103. legacyTaskIds: readonly string[],
  104. ) => stub.loadStored?.(workspaceId, legacyTaskIds) ?? stub.stored,
  105. isDraftSession: (sessionId: string) => stub.drafts?.has(sessionId) ?? false,
  106. }
  107. : {}),
  108. },
  109. { now: () => 1_700_000_999_000, createLogEpoch: () => "epoch-1" },
  110. );
  111. }
  112. function indexFrames(stub: Stub): SessionsIndexTopicFrame[] {
  113. return stub.frames.filter((f) =>
  114. f.topic.startsWith("sessions-index/"),
  115. ) as SessionsIndexTopicFrame[];
  116. }
  117. describe("ConversationV4Gateway sessions-index 集成", () => {
  118. it.each(["sendText", "createSession"] as const)(
  119. "FSV01:%s 首发提升后不等待下一条 runtime 事件发布摘要",
  120. async (type) => {
  121. const stub: Stub = {
  122. frames: [],
  123. sessions: new Set(["live-1"]),
  124. sessionWorkspace: new Map([["live-1", "ws-1"]]),
  125. stored: [],
  126. drafts: new Set(["live-1"]),
  127. };
  128. const gateway = makeGateway(stub, { withIndexHooks: true });
  129. gateway.ingest(
  130. "live-1",
  131. event("live-1", 1, SessionEventType.SessionCreated, {
  132. mode: "default",
  133. contextWindow: 200_000,
  134. }),
  135. );
  136. await gateway.subscribeSessionsIndex({
  137. topic: "sessions-index/ws-1",
  138. connectionId: "desktop",
  139. clientMode: "desktop-continuous",
  140. });
  141. gateway.ingest(
  142. "live-1",
  143. event("live-1", 2, SessionEventType.SessionTitleUpdated, {
  144. previousTitle: "",
  145. source: "first_input",
  146. title: "first",
  147. }),
  148. );
  149. expect(indexFrames(stub)).toHaveLength(0);
  150. stub.executeCommand = async () => {
  151. stub.drafts!.delete("live-1");
  152. return type === "createSession"
  153. ? { type: "createSession", sessionId: "live-1" }
  154. : { type: "inputAccepted", inputId: "first", delivery: "startNow" };
  155. };
  156. const command = {
  157. commandId: "first",
  158. clientId: "client",
  159. sessionId: type === "createSession" ? null : "live-1",
  160. type,
  161. payload:
  162. type === "createSession"
  163. ? { workspaceId: "ws-1", firstInput: { text: "first" } }
  164. : { text: "first" },
  165. issuedAt: 1,
  166. };
  167. const ack = await gateway.handleCommand(command);
  168. expect(ack.status).toBe("accepted");
  169. expect(indexFrames(stub)).toMatchObject([
  170. {
  171. payload: {
  172. kind: "deltas",
  173. deltas: [
  174. {
  175. op: "session.upserted",
  176. session: { sessionId: "live-1", title: "first", phase: "draft" },
  177. },
  178. ],
  179. },
  180. },
  181. ]);
  182. await gateway.handleCommand(command);
  183. expect(indexFrames(stub)).toHaveLength(1);
  184. gateway.dispose();
  185. },
  186. );
  187. it("saturated mobile index subscriber does not block desktop and drains only itself", async () => {
  188. const stub: Stub = {
  189. frames: [],
  190. sessions: new Set(["live-1"]),
  191. sessionWorkspace: new Map([["live-1", "ws-1"]]),
  192. stored: [],
  193. };
  194. const gateway = makeGateway(stub, { withIndexHooks: true });
  195. gateway.ingest(
  196. "live-1",
  197. event("live-1", 1, SessionEventType.SessionCreated, {
  198. mode: "default",
  199. contextWindow: 200_000,
  200. }),
  201. );
  202. const desktop = await gateway.subscribeSessionsIndex({
  203. topic: "sessions-index/ws-1",
  204. connectionId: "desktop-index",
  205. clientMode: "desktop-continuous",
  206. });
  207. const mobile = await gateway.subscribeSessionsIndex({
  208. topic: "sessions-index/ws-1",
  209. connectionId: "mobile-index",
  210. clientMode: "web-remote-replayable",
  211. });
  212. gateway.setConnectionFlowState({ connectionId: "mobile-index", state: "saturated" });
  213. gateway.ingest(
  214. "live-1",
  215. event("live-1", 2, SessionEventType.SessionTitleUpdated, {
  216. previousTitle: "",
  217. source: "custom",
  218. title: "changed-while-paused",
  219. }),
  220. );
  221. expect(indexFrames(stub).map((frame) => frame.subscriptionId)).toEqual([
  222. desktop.ack.subscriptionId,
  223. ]);
  224. gateway.setConnectionFlowState({ connectionId: "mobile-index", state: "drained" });
  225. expect(indexFrames(stub).map((frame) => frame.subscriptionId)).toEqual([
  226. desktop.ack.subscriptionId,
  227. mobile.ack.subscriptionId,
  228. ]);
  229. });
  230. it("sessions-index recovery commit 后无新 ingest 也会 flush 在途期间增量", async () => {
  231. const stub: Stub = {
  232. frames: [],
  233. sessions: new Set(["live-1"]),
  234. sessionWorkspace: new Map([["live-1", "ws-1"]]),
  235. stored: [],
  236. };
  237. const gateway = makeGateway(stub, { withIndexHooks: true });
  238. gateway.ingest(
  239. "live-1",
  240. event("live-1", 1, SessionEventType.SessionCreated, {
  241. mode: "default",
  242. contextWindow: 200_000,
  243. }),
  244. );
  245. const subscribed = await gateway.subscribeSessionsIndex({
  246. topic: "sessions-index/ws-1",
  247. connectionId: "conn-1",
  248. clientMode: "desktop-continuous",
  249. });
  250. const recovery = gateway.resyncReserved({
  251. topic: "sessions-index/ws-1",
  252. connectionId: "conn-1",
  253. subscriptionId: subscribed.ack.subscriptionId,
  254. base: {
  255. logEpoch: subscribed.ack.logEpoch,
  256. seq: subscribed.initialFrame?.toSeq ?? 0,
  257. },
  258. });
  259. gateway.ingest(
  260. "live-1",
  261. event("live-1", 2, SessionEventType.SessionTitleUpdated, {
  262. previousTitle: "",
  263. source: "custom",
  264. title: "during-recovery",
  265. }),
  266. );
  267. expect(indexFrames(stub)).toEqual([]);
  268. expect(recovery.commit()).toBe(true);
  269. expect(indexFrames(stub)).toHaveLength(1);
  270. expect(indexFrames(stub)[0]).toMatchObject({
  271. payload: { kind: "deltas" },
  272. });
  273. });
  274. it("initial physical encode 失败会回滚 sessions-index subscription", async () => {
  275. const summary = storedSummary("oversized");
  276. summary.title = "x".repeat(17 * 1024 * 1024);
  277. const stub: Stub = {
  278. frames: [],
  279. sessions: new Set(),
  280. sessionWorkspace: new Map(),
  281. stored: [summary],
  282. };
  283. const gateway = makeGateway(stub, { withIndexHooks: true });
  284. await expect(
  285. gateway.subscribeSessionsIndex({
  286. topic: "sessions-index/ws-1",
  287. connectionId: "conn-1",
  288. clientMode: "desktop-continuous",
  289. }),
  290. ).rejects.toThrow("proto.frameAssemblyTooLarge");
  291. const publishers = (
  292. gateway as unknown as {
  293. indexPublishers: Map<string, { hasSubscribers(): boolean }>;
  294. }
  295. ).indexPublishers;
  296. expect(publishers.get("ws-1")?.hasSubscribers()).toBe(false);
  297. });
  298. it("subscribe:store 种子 + live 覆盖 → snapshot 含两会话", async () => {
  299. const stub: Stub = {
  300. frames: [],
  301. sessions: new Set(["live-1"]),
  302. sessionWorkspace: new Map([["live-1", "ws-1"]]),
  303. stored: [storedSummary("cold-1")],
  304. };
  305. const gateway = makeGateway(stub, { withIndexHooks: true });
  306. // 先让 live-1 有 conversation 投影
  307. gateway.ingest(
  308. "live-1",
  309. event("live-1", 1, SessionEventType.SessionCreated, {
  310. mode: "default",
  311. contextWindow: 200_000,
  312. }),
  313. );
  314. const res = await gateway.subscribeSessionsIndex({
  315. topic: "sessions-index/ws-1",
  316. connectionId: "conn-1",
  317. clientMode: "desktop-continuous",
  318. });
  319. expect(res.ack.mode).toBe("snapshot");
  320. expect(res.initialFrame?.payload.kind).toBe("snapshot");
  321. if (res.initialFrame?.payload.kind === "snapshot") {
  322. const ids = res.initialFrame.payload.snapshot.sessions.map((s) => s.sessionId).sort();
  323. expect(ids).toEqual(["cold-1", "live-1"]);
  324. }
  325. });
  326. it("首次无 allowlist 后可用 allowlist 重订阅:重读 store 并向已有订阅增量补齐", async () => {
  327. const storedCurrent = storedSummary("current-1");
  328. const storedLegacy = storedSummary("legacy-1");
  329. const calls: Array<readonly string[] | undefined> = [];
  330. const stub: Stub = {
  331. frames: [],
  332. sessions: new Set(),
  333. sessionWorkspace: new Map(),
  334. stored: [],
  335. loadStored: (_workspaceId, legacyTaskIds) => {
  336. calls.push(legacyTaskIds);
  337. return legacyTaskIds?.length
  338. ? [{ ...storedCurrent, title: "不能覆盖已有摘要" }, storedLegacy]
  339. : [storedCurrent];
  340. },
  341. };
  342. const gateway = makeGateway(stub, { withIndexHooks: true });
  343. const first = await gateway.subscribeSessionsIndex({
  344. topic: "sessions-index/ws-1",
  345. connectionId: "conn-old",
  346. clientMode: "desktop-continuous",
  347. });
  348. const before = indexFrames(stub).length;
  349. const retried = await gateway.subscribeSessionsIndex({
  350. topic: "sessions-index/ws-1",
  351. connectionId: "conn-new",
  352. clientMode: "desktop-continuous",
  353. legacyTaskIds: ["legacy-1"],
  354. });
  355. expect(calls).toEqual([undefined, ["legacy-1"]]);
  356. expect(first.initialFrame?.payload).toMatchObject({
  357. kind: "snapshot",
  358. snapshot: { sessions: [expect.objectContaining({ sessionId: "current-1" })] },
  359. });
  360. if (retried.initialFrame?.payload.kind === "snapshot") {
  361. expect(retried.initialFrame.payload.snapshot.sessions).toEqual([
  362. expect.objectContaining({ sessionId: "current-1", title: "stored-current-1" }),
  363. expect.objectContaining({ sessionId: "legacy-1" }),
  364. ]);
  365. } else {
  366. throw new Error("Expected retried sessions-index snapshot");
  367. }
  368. const emitted = indexFrames(stub).slice(before);
  369. expect(emitted).toEqual([
  370. expect.objectContaining({
  371. subscriptionId: first.ack.subscriptionId,
  372. payload: {
  373. kind: "deltas",
  374. deltas: [
  375. expect.objectContaining({
  376. op: "session.upserted",
  377. session: expect.objectContaining({ sessionId: "legacy-1" }),
  378. }),
  379. ],
  380. },
  381. }),
  382. ]);
  383. });
  384. it("携带 allowlist 的重读失败后不会封死后续重试", async () => {
  385. let allowlistAttempts = 0;
  386. const stub: Stub = {
  387. frames: [],
  388. sessions: new Set(),
  389. sessionWorkspace: new Map(),
  390. stored: [],
  391. loadStored: (_workspaceId, legacyTaskIds) => {
  392. if (!legacyTaskIds?.length) return [];
  393. allowlistAttempts += 1;
  394. // 模拟 bridge 将 claim/list 失败降级为空摘要;下一次订阅必须再次调用宿主钩子。
  395. return allowlistAttempts === 1 ? [] : [storedSummary("legacy-1")];
  396. },
  397. };
  398. const gateway = makeGateway(stub, { withIndexHooks: true });
  399. await gateway.subscribeSessionsIndex({
  400. topic: "sessions-index/ws-1",
  401. connectionId: "conn-initial",
  402. clientMode: "desktop-continuous",
  403. });
  404. await gateway.subscribeSessionsIndex({
  405. topic: "sessions-index/ws-1",
  406. connectionId: "conn-failed",
  407. clientMode: "desktop-continuous",
  408. legacyTaskIds: ["legacy-1"],
  409. });
  410. const recovered = await gateway.subscribeSessionsIndex({
  411. topic: "sessions-index/ws-1",
  412. connectionId: "conn-recovered",
  413. clientMode: "desktop-continuous",
  414. legacyTaskIds: ["legacy-1"],
  415. });
  416. expect(allowlistAttempts).toBe(2);
  417. if (recovered.initialFrame?.payload.kind === "snapshot") {
  418. expect(recovered.initialFrame.payload.snapshot.sessions).toEqual([
  419. expect.objectContaining({ sessionId: "legacy-1" }),
  420. ]);
  421. } else {
  422. throw new Error("Expected recovered sessions-index snapshot");
  423. }
  424. });
  425. it("同 workspace 并发初始化按顺序执行,迁移后快照不会被较早的空种子赢走", async () => {
  426. let releaseFirst!: (summaries: SessionSummary[]) => void;
  427. let secondLoadStarted = false;
  428. let loadCount = 0;
  429. const stub: Stub = {
  430. frames: [],
  431. sessions: new Set(),
  432. sessionWorkspace: new Map(),
  433. stored: [],
  434. loadStored: () => {
  435. loadCount += 1;
  436. if (loadCount === 1) {
  437. return new Promise<SessionSummary[]>((resolve) => {
  438. releaseFirst = resolve;
  439. });
  440. }
  441. secondLoadStarted = true;
  442. return [storedSummary("legacy-1")];
  443. },
  444. };
  445. const gateway = makeGateway(stub, { withIndexHooks: true });
  446. const first = gateway.subscribeSessionsIndex({
  447. topic: "sessions-index/ws-1",
  448. connectionId: "conn-first",
  449. clientMode: "desktop-continuous",
  450. });
  451. const second = gateway.subscribeSessionsIndex({
  452. topic: "sessions-index/ws-1",
  453. connectionId: "conn-second",
  454. clientMode: "desktop-continuous",
  455. legacyTaskIds: ["legacy-1"],
  456. });
  457. expect(secondLoadStarted).toBe(false);
  458. releaseFirst([]);
  459. await first;
  460. const migrated = await second;
  461. expect(secondLoadStarted).toBe(true);
  462. if (migrated.initialFrame?.payload.kind === "snapshot") {
  463. expect(migrated.initialFrame.payload.snapshot.sessions).toEqual([
  464. expect.objectContaining({ sessionId: "legacy-1" }),
  465. ]);
  466. } else {
  467. throw new Error("Expected migrated sessions-index snapshot");
  468. }
  469. });
  470. it("异步冷种子未完成时 dispose:不得在销毁后重新注册 publisher 或完成订阅", async () => {
  471. let releaseLoad!: (summaries: SessionSummary[]) => void;
  472. const stub: Stub = {
  473. frames: [],
  474. sessions: new Set(),
  475. sessionWorkspace: new Map(),
  476. stored: [],
  477. loadStored: () =>
  478. new Promise<SessionSummary[]>((resolve) => {
  479. releaseLoad = resolve;
  480. }),
  481. };
  482. const gateway = makeGateway(stub, { withIndexHooks: true });
  483. const subscribing = gateway.subscribeSessionsIndex({
  484. topic: "sessions-index/ws-1",
  485. connectionId: "conn-disposed",
  486. clientMode: "desktop-continuous",
  487. });
  488. gateway.dispose();
  489. releaseLoad([storedSummary("late-session")]);
  490. await expect(subscribing).rejects.toThrow("fault.gateway.disposed");
  491. const publishers = (
  492. gateway as unknown as {
  493. indexPublishers: { get(workspaceId: string): unknown };
  494. }
  495. ).indexPublishers;
  496. expect(publishers.get("ws-1")).toBeUndefined();
  497. expect(indexFrames(stub)).toEqual([]);
  498. });
  499. it("draft(deferred 未发首条)不进列表:种子跳过 + ingest 跳过,提升后入列", async () => {
  500. const stub: Stub = {
  501. frames: [],
  502. sessions: new Set(["draft-1"]),
  503. sessionWorkspace: new Map([["draft-1", "ws-1"]]),
  504. stored: [],
  505. drafts: new Set(["draft-1"]),
  506. };
  507. const gateway = makeGateway(stub, { withIndexHooks: true });
  508. gateway.ingest(
  509. "draft-1",
  510. event("draft-1", 1, SessionEventType.SessionCreated, {
  511. mode: "default",
  512. contextWindow: 200_000,
  513. }),
  514. );
  515. // 订阅种子:draft 不出现在 snapshot。
  516. const res = await gateway.subscribeSessionsIndex({
  517. topic: "sessions-index/ws-1",
  518. connectionId: "conn-1",
  519. clientMode: "desktop-continuous",
  520. });
  521. if (res.initialFrame?.payload.kind === "snapshot") {
  522. expect(res.initialFrame.payload.snapshot.sessions).toEqual([]);
  523. }
  524. // draft 期间的事件也不产列表帧。
  525. const framesBefore = indexFrames(stub).length;
  526. gateway.ingest(
  527. "draft-1",
  528. event("draft-1", 2, SessionEventType.SessionTitleUpdated, {
  529. previousTitle: "",
  530. source: "custom",
  531. title: "draft 期标题",
  532. }),
  533. );
  534. expect(indexFrames(stub).length).toBe(framesBefore);
  535. // 首发提升 persistence 后(draft 标记消失),事件驱动入列。
  536. stub.drafts?.delete("draft-1");
  537. gateway.ingest(
  538. "draft-1",
  539. event("draft-1", 3, SessionEventType.SessionTitleUpdated, {
  540. previousTitle: "draft 期标题",
  541. source: "custom",
  542. title: "已提升",
  543. }),
  544. );
  545. const upserts = indexFrames(stub).filter(
  546. (f) =>
  547. f.payload.kind === "deltas" &&
  548. f.payload.deltas.some(
  549. (d) => d.op === "session.upserted" && d.session.sessionId === "draft-1",
  550. ),
  551. );
  552. expect(upserts.length).toBeGreaterThan(0);
  553. });
  554. it("fork 暂态 publisher 在 hydration 后无后续事件也会发布 visible summary", async () => {
  555. const childId = "fork-child";
  556. const persistedEvents = [
  557. event(childId, 1, SessionEventType.SessionCreated, {
  558. mode: "default",
  559. contextWindow: 200_000,
  560. }),
  561. event(
  562. childId,
  563. 2,
  564. SessionEventType.TurnStarted,
  565. { turnNumber: 1, input: "继承问题" },
  566. "turn-1",
  567. ),
  568. event(
  569. childId,
  570. 3,
  571. SessionEventType.ModelStreaming,
  572. { kind: "text_delta", delta: "继承回答", done: false },
  573. "turn-1",
  574. ),
  575. event(
  576. childId,
  577. 4,
  578. SessionEventType.TurnComplete,
  579. {
  580. response: "继承回答",
  581. tokenCount: 1,
  582. toolCallCount: 0,
  583. duration: 1,
  584. resultType: "success",
  585. },
  586. "turn-1",
  587. ),
  588. ];
  589. const stub: Stub = {
  590. frames: [],
  591. sessions: new Set([childId]),
  592. sessionWorkspace: new Map([[childId, "ws-1"]]),
  593. stored: [],
  594. loadPersistedEvents: async () => ({
  595. events: persistedEvents,
  596. synthesized: true,
  597. sourceEventSeq: persistedEvents.length,
  598. }),
  599. };
  600. const gateway = makeGateway(stub, { withIndexHooks: true });
  601. // fork resume 先建立只有 SessionCreated 的暂态 publisher;此时列表基线是 draft。
  602. gateway.ingest(
  603. childId,
  604. event(childId, 1, SessionEventType.SessionCreated, {
  605. mode: "default",
  606. contextWindow: 200_000,
  607. }),
  608. );
  609. const indexSubscription = await gateway.subscribeSessionsIndex({
  610. topic: "sessions-index/ws-1",
  611. connectionId: "index-conn",
  612. clientMode: "desktop-continuous",
  613. });
  614. expect(indexSubscription.initialFrame?.payload).toMatchObject({
  615. kind: "snapshot",
  616. snapshot: {
  617. sessions: [expect.objectContaining({ sessionId: childId, phase: "draft" })],
  618. },
  619. });
  620. const framesBeforeHydration = indexFrames(stub).length;
  621. await gateway.subscribe({
  622. topic: `conversation/${childId}`,
  623. connectionId: "conversation-conn",
  624. clientMode: "desktop-continuous",
  625. });
  626. const emitted = indexFrames(stub).slice(framesBeforeHydration);
  627. expect(emitted).toEqual(
  628. expect.arrayContaining([
  629. expect.objectContaining({
  630. subscriptionId: indexSubscription.ack.subscriptionId,
  631. payload: {
  632. kind: "deltas",
  633. deltas: [
  634. expect.objectContaining({
  635. op: "session.upserted",
  636. session: expect.objectContaining({
  637. sessionId: childId,
  638. phase: "completedSuccess",
  639. }),
  640. }),
  641. ],
  642. },
  643. }),
  644. ]),
  645. );
  646. });
  647. it("ingest 非流式事件 → 列表订阅者收到 upserted 增量帧", async () => {
  648. const stub: Stub = {
  649. frames: [],
  650. sessions: new Set(["live-1"]),
  651. sessionWorkspace: new Map([["live-1", "ws-1"]]),
  652. stored: [],
  653. };
  654. const gateway = makeGateway(stub, { withIndexHooks: true });
  655. gateway.ingest(
  656. "live-1",
  657. event("live-1", 1, SessionEventType.SessionCreated, {
  658. mode: "default",
  659. contextWindow: 200_000,
  660. }),
  661. );
  662. await gateway.subscribeSessionsIndex({
  663. topic: "sessions-index/ws-1",
  664. connectionId: "conn-1",
  665. clientMode: "desktop-continuous",
  666. });
  667. const before = indexFrames(stub).length;
  668. // 标题变化(非流式)→ 应产 upserted
  669. gateway.ingest(
  670. "live-1",
  671. event("live-1", 2, SessionEventType.SessionTitleUpdated, {
  672. previousTitle: "",
  673. source: "custom",
  674. title: "新标题",
  675. }),
  676. );
  677. const emitted = indexFrames(stub).slice(before);
  678. const deltaFrame = emitted.find((f) => f.payload.kind === "deltas");
  679. expect(deltaFrame).toBeDefined();
  680. if (deltaFrame?.payload.kind === "deltas") {
  681. expect(deltaFrame.payload.deltas[0]).toMatchObject({
  682. op: "session.upserted",
  683. });
  684. }
  685. });
  686. it("ModelStreaming 高频增量不触发列表帧", async () => {
  687. const stub: Stub = {
  688. frames: [],
  689. sessions: new Set(["live-1"]),
  690. sessionWorkspace: new Map([["live-1", "ws-1"]]),
  691. stored: [],
  692. };
  693. const gateway = makeGateway(stub, { withIndexHooks: true });
  694. gateway.ingest(
  695. "live-1",
  696. event("live-1", 1, SessionEventType.SessionCreated, {
  697. mode: "default",
  698. contextWindow: 200_000,
  699. }),
  700. );
  701. await gateway.subscribeSessionsIndex({
  702. topic: "sessions-index/ws-1",
  703. connectionId: "conn-1",
  704. clientMode: "desktop-continuous",
  705. });
  706. const before = indexFrames(stub).length;
  707. gateway.ingest(
  708. "live-1",
  709. event("live-1", 2, SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, "t1"),
  710. );
  711. gateway.ingest(
  712. "live-1",
  713. event(
  714. "live-1",
  715. 3,
  716. SessionEventType.ModelStreaming,
  717. { kind: "text_start", delta: "", done: false },
  718. "t1",
  719. ),
  720. );
  721. gateway.ingest(
  722. "live-1",
  723. event(
  724. "live-1",
  725. 4,
  726. SessionEventType.ModelStreaming,
  727. { kind: "text_delta", delta: "abc", done: false },
  728. "t1",
  729. ),
  730. );
  731. const emitted = indexFrames(stub).slice(before);
  732. // TurnStarted 触发一帧(phase→running),两条 ModelStreaming 不再触发
  733. expect(emitted.length).toBe(1);
  734. });
  735. it("关闭运行实例不发删除事件,列表仍保留持久化会话", async () => {
  736. const stub: Stub = {
  737. frames: [],
  738. sessions: new Set(["live-1"]),
  739. sessionWorkspace: new Map([["live-1", "ws-1"]]),
  740. stored: [],
  741. };
  742. const gateway = makeGateway(stub, { withIndexHooks: true });
  743. gateway.ingest(
  744. "live-1",
  745. event("live-1", 1, SessionEventType.SessionCreated, {
  746. mode: "default",
  747. contextWindow: 200_000,
  748. }),
  749. );
  750. await gateway.subscribeSessionsIndex({
  751. topic: "sessions-index/ws-1",
  752. connectionId: "conn-1",
  753. clientMode: "desktop-continuous",
  754. });
  755. const before = indexFrames(stub).length;
  756. gateway.disposeSession("live-1");
  757. expect(indexFrames(stub).slice(before)).toEqual([]);
  758. const next = await gateway.subscribeSessionsIndex({
  759. topic: "sessions-index/ws-1",
  760. connectionId: "conn-2",
  761. clientMode: "web-remote-replayable",
  762. });
  763. expect(next.initialFrame?.payload).toMatchObject({
  764. kind: "snapshot",
  765. snapshot: { sessions: [expect.objectContaining({ sessionId: "live-1" })] },
  766. });
  767. });
  768. it("disposeSession → session.removed 增量帧", async () => {
  769. const stub: Stub = {
  770. frames: [],
  771. sessions: new Set(["live-1"]),
  772. sessionWorkspace: new Map([["live-1", "ws-1"]]),
  773. stored: [],
  774. };
  775. const gateway = makeGateway(stub, { withIndexHooks: true });
  776. gateway.ingest(
  777. "live-1",
  778. event("live-1", 1, SessionEventType.SessionCreated, {
  779. mode: "default",
  780. contextWindow: 200_000,
  781. }),
  782. );
  783. await gateway.subscribeSessionsIndex({
  784. topic: "sessions-index/ws-1",
  785. connectionId: "conn-1",
  786. clientMode: "desktop-continuous",
  787. });
  788. const before = indexFrames(stub).length;
  789. gateway.disposeSession("live-1", { deleted: true });
  790. const emitted = indexFrames(stub).slice(before);
  791. const removed = emitted.find(
  792. (f) =>
  793. f.payload.kind === "deltas" && f.payload.deltas.some((d) => d.op === "session.removed"),
  794. );
  795. expect(removed).toBeDefined();
  796. });
  797. it("无订阅者时 disposeSession 仍移除 index projection,重订阅 snapshot 不复活", async () => {
  798. const stub: Stub = {
  799. frames: [],
  800. sessions: new Set(["live-1"]),
  801. sessionWorkspace: new Map([["live-1", "ws-1"]]),
  802. stored: [],
  803. };
  804. const gateway = makeGateway(stub, { withIndexHooks: true });
  805. gateway.ingest(
  806. "live-1",
  807. event("live-1", 1, SessionEventType.SessionCreated, {
  808. mode: "default",
  809. contextWindow: 200_000,
  810. }),
  811. );
  812. const first = await gateway.subscribeSessionsIndex({
  813. topic: "sessions-index/ws-1",
  814. connectionId: "conn-1",
  815. clientMode: "desktop-continuous",
  816. });
  817. gateway.unsubscribe({
  818. topic: "sessions-index/ws-1",
  819. subscriptionId: first.ack.subscriptionId,
  820. connectionId: "conn-1",
  821. });
  822. // disposeSession 的删除必须更新无订阅者 publisher;否则已有 publisher 会把已删除会话
  823. // 带进下一次 snapshot,造成任务复活。
  824. gateway.disposeSession("live-1", { deleted: true });
  825. const second = await gateway.subscribeSessionsIndex({
  826. topic: "sessions-index/ws-1",
  827. connectionId: "conn-2",
  828. clientMode: "desktop-continuous",
  829. });
  830. if (second.initialFrame?.payload.kind === "snapshot") {
  831. expect(second.initialFrame.payload.snapshot.sessions).toEqual([]);
  832. } else {
  833. throw new Error("Expected sessions-index snapshot");
  834. }
  835. });
  836. it("旧宿主(无 index hooks)→ sessions-index 路径 no-op,conversation ingest 不受影响", () => {
  837. const stub: Stub = {
  838. frames: [],
  839. sessions: new Set(["live-1"]),
  840. sessionWorkspace: new Map(),
  841. stored: [],
  842. };
  843. const gateway = makeGateway(stub, { withIndexHooks: false });
  844. expect(() =>
  845. gateway.ingest(
  846. "live-1",
  847. event("live-1", 1, SessionEventType.SessionCreated, {
  848. mode: "default",
  849. contextWindow: 200_000,
  850. }),
  851. ),
  852. ).not.toThrow();
  853. expect(indexFrames(stub)).toHaveLength(0);
  854. });
  855. it("unsubscribeSessionsIndex 后 ingest 不再产列表帧", async () => {
  856. const stub: Stub = {
  857. frames: [],
  858. sessions: new Set(["live-1"]),
  859. sessionWorkspace: new Map([["live-1", "ws-1"]]),
  860. stored: [],
  861. };
  862. const gateway = makeGateway(stub, { withIndexHooks: true });
  863. gateway.ingest(
  864. "live-1",
  865. event("live-1", 1, SessionEventType.SessionCreated, {
  866. mode: "default",
  867. contextWindow: 200_000,
  868. }),
  869. );
  870. const res = await gateway.subscribeSessionsIndex({
  871. topic: "sessions-index/ws-1",
  872. connectionId: "conn-1",
  873. clientMode: "desktop-continuous",
  874. });
  875. gateway.unsubscribe({
  876. topic: "sessions-index/ws-1",
  877. subscriptionId: res.ack.subscriptionId,
  878. connectionId: "conn-1",
  879. });
  880. const before = indexFrames(stub).length;
  881. gateway.ingest(
  882. "live-1",
  883. event("live-1", 2, SessionEventType.SessionTitleUpdated, {
  884. previousTitle: "",
  885. source: "custom",
  886. title: "退订后",
  887. }),
  888. );
  889. expect(indexFrames(stub).length).toBe(before);
  890. });
  891. it("无订阅者窗口仍推进 index projection,重订阅 snapshot 返回当前 phase", async () => {
  892. const stub: Stub = {
  893. frames: [],
  894. sessions: new Set(["live-1"]),
  895. sessionWorkspace: new Map([["live-1", "ws-1"]]),
  896. stored: [],
  897. };
  898. const gateway = makeGateway(stub, { withIndexHooks: true });
  899. gateway.ingest(
  900. "live-1",
  901. event("live-1", 1, SessionEventType.SessionCreated, {
  902. mode: "default",
  903. contextWindow: 200_000,
  904. }),
  905. );
  906. const first = await gateway.subscribeSessionsIndex({
  907. topic: "sessions-index/ws-1",
  908. connectionId: "conn-1",
  909. clientMode: "desktop-continuous",
  910. });
  911. expect(first.initialFrame?.payload).toMatchObject({
  912. kind: "snapshot",
  913. snapshot: { sessions: [expect.objectContaining({ sessionId: "live-1" })] },
  914. });
  915. gateway.unsubscribe({
  916. topic: "sessions-index/ws-1",
  917. subscriptionId: first.ack.subscriptionId,
  918. connectionId: "conn-1",
  919. });
  920. // 退订窗口内没有任何列表消费者;修复前 publishCurrentSummaryToIndex 会直接
  921. // return,导致之后的 snapshot 仍停留在窗口前的 phase。
  922. gateway.ingest(
  923. "live-1",
  924. event("live-1", 2, SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, "t1"),
  925. );
  926. const second = await gateway.subscribeSessionsIndex({
  927. topic: "sessions-index/ws-1",
  928. connectionId: "conn-2",
  929. clientMode: "desktop-continuous",
  930. });
  931. expect(second.initialFrame?.payload).toMatchObject({
  932. kind: "snapshot",
  933. snapshot: {
  934. sessions: [expect.objectContaining({ sessionId: "live-1", phase: "running" })],
  935. },
  936. });
  937. });
  938. });
  939. describe("sessions-index reconciliation", () => {
  940. it("validates and delegates a bounded read without creating a conversation runtime", async () => {
  941. let received: unknown;
  942. const gateway = new ConversationV4Gateway({
  943. sessionExists: () => false,
  944. emitWireFrame: () => {},
  945. executeCommand: (...args) => stub.executeCommand?.(...args) ?? Promise.resolve(undefined),
  946. reconcileSessions: async (params) => {
  947. received = params;
  948. return {
  949. sessions: [
  950. {
  951. sessionId: "deleted",
  952. exists: true,
  953. deleted: true,
  954. title: "removed",
  955. titleSource: "custom",
  956. createdAt: 1,
  957. updatedAt: 2,
  958. lastOutcome: "error",
  959. },
  960. { sessionId: "missing", exists: false, deleted: false },
  961. ],
  962. };
  963. },
  964. });
  965. expect(
  966. await gateway.reconcileSessions({ workspaceId: "/w", sessionIds: ["deleted", "missing"] }),
  967. ).toMatchObject({ sessions: [{ deleted: true }, { exists: false }] });
  968. expect(received).toEqual({ workspaceId: "/w", sessionIds: ["deleted", "missing"] });
  969. await expect(
  970. gateway.reconcileSessions({ workspaceId: "/w", sessionIds: Array(257).fill("s") }),
  971. ).rejects.toThrow();
  972. gateway.dispose();
  973. });
  974. });
  975. // ── 工作流进度事件的 fan-out 节流(14-sessions-index「事件 fan-out 节奏」)──
  976. // 现场事故:一次 run 在 8s 内发出 4000 条 DynamicWorkflowRunProgress,每条都 bump
  977. // record.updatedAt,旧实现于是条条 flush 一帧 sessions-index 增量 → 宿主重算 task 行 →
  978. // renderer 按事件频率重拉三份任务列表。节流只改帧节奏,终态仍在一个窗口内送达。
  979. describe("ConversationV4Gateway sessions-index 工作流进度节流", () => {
  980. beforeEach(() => vi.useFakeTimers());
  981. afterEach(() => vi.useRealTimers());
  982. /** 与 WORKFLOW_PROGRESS_INDEX_FANOUT_MS 对齐;测试不导入常量,窗口值本身也是被测事实。 */
  983. const WINDOW_MS = 250;
  984. const RUN_ID = "dwfrun-1";
  985. function progress(
  986. seq: number,
  987. eventType: string,
  988. payload: Record<string, unknown>,
  989. ): SessionEvent {
  990. return event("live-1", seq, SessionEventType.DynamicWorkflowRunProgress, {
  991. runId: RUN_ID,
  992. toolCallId: "tc-1",
  993. sequence: seq,
  994. eventType,
  995. payload,
  996. });
  997. }
  998. /** 建好一个在跑的 run,并把建 run 时开的那扇窗关掉:断言从静默态开始。 */
  999. function setup(): { stub: Stub; gateway: ReturnType<typeof makeGateway> } {
  1000. const stub: Stub = {
  1001. frames: [],
  1002. sessions: new Set(["live-1"]),
  1003. sessionWorkspace: new Map([["live-1", "ws-1"]]),
  1004. stored: [],
  1005. lastActivityAt: 1000,
  1006. };
  1007. const gateway = makeGateway(stub, { withIndexHooks: true });
  1008. gateway.ingest(
  1009. "live-1",
  1010. event("live-1", 1, SessionEventType.SessionCreated, {
  1011. mode: "default",
  1012. contextWindow: 200_000,
  1013. }),
  1014. );
  1015. gateway.ingest(
  1016. "live-1",
  1017. progress(2, "run-started", { runId: RUN_ID, caps: { maxConcurrency: 4 } }),
  1018. );
  1019. vi.advanceTimersByTime(WINDOW_MS);
  1020. return { stub, gateway };
  1021. }
  1022. /** 模拟 onSessionEvent 的 record.updatedAt bump,再喂事件。 */
  1023. function ingestProgress(
  1024. stub: Stub,
  1025. gateway: ReturnType<typeof makeGateway>,
  1026. seq: number,
  1027. eventType: string,
  1028. payload: Record<string, unknown>,
  1029. ): void {
  1030. stub.lastActivityAt = (stub.lastActivityAt ?? 0) + 1;
  1031. gateway.ingest("live-1", progress(seq, eventType, payload));
  1032. }
  1033. function lastUpsertedSummary(stub: Stub): SessionSummary | undefined {
  1034. for (const frame of [...indexFrames(stub)].reverse()) {
  1035. if (frame.payload.kind !== "deltas") continue;
  1036. for (const delta of [...frame.payload.deltas].reverse()) {
  1037. if (delta.op === "session.upserted") return delta.session;
  1038. }
  1039. }
  1040. return undefined;
  1041. }
  1042. async function subscribed(stub: Stub, gateway: ReturnType<typeof makeGateway>): Promise<number> {
  1043. await gateway.subscribeSessionsIndex({
  1044. topic: "sessions-index/ws-1",
  1045. connectionId: "conn-1",
  1046. clientMode: "desktop-continuous",
  1047. });
  1048. return indexFrames(stub).length;
  1049. }
  1050. it("一窗内的 N 条进度只出 1 帧立即 + 1 帧窗末,窗末帧带最终摘要", async () => {
  1051. const { stub, gateway } = setup();
  1052. const before = await subscribed(stub, gateway);
  1053. for (let index = 1; index <= 6; index += 1) {
  1054. ingestProgress(stub, gateway, 2 + index, "phase-entered", { name: `phase-${index}` });
  1055. vi.advanceTimersByTime(10);
  1056. }
  1057. // leading edge:静默后的第一条立即到;其余 5 条合并,窗内不再发帧。
  1058. expect(indexFrames(stub).length).toBe(before + 1);
  1059. expect(lastUpsertedSummary(stub)?.workflowActivity?.runs[0]?.currentPhase).toBe("phase-1");
  1060. vi.advanceTimersByTime(WINDOW_MS);
  1061. expect(indexFrames(stub).length).toBe(before + 2);
  1062. const trailing = lastUpsertedSummary(stub);
  1063. expect(trailing?.workflowActivity?.runs[0]?.currentPhase).toBe("phase-6");
  1064. expect(trailing?.lastActivityAt).toBe(1006);
  1065. // 持续高频:窗末补发后窗口续开,下一窗同样只出 1 帧 → 侧栏运行行不超过 4Hz。
  1066. for (let index = 7; index <= 12; index += 1) {
  1067. ingestProgress(stub, gateway, 2 + index, "phase-entered", { name: `phase-${index}` });
  1068. vi.advanceTimersByTime(10);
  1069. }
  1070. expect(indexFrames(stub).length).toBe(before + 2);
  1071. vi.advanceTimersByTime(WINDOW_MS);
  1072. expect(indexFrames(stub).length).toBe(before + 3);
  1073. expect(lastUpsertedSummary(stub)?.workflowActivity?.runs[0]?.currentPhase).toBe("phase-12");
  1074. });
  1075. it("窗内的非进度事件立即发帧,并满足/取消待发的窗末帧", async () => {
  1076. const { stub, gateway } = setup();
  1077. const before = await subscribed(stub, gateway);
  1078. ingestProgress(stub, gateway, 3, "phase-entered", { name: "phase-1" });
  1079. vi.advanceTimersByTime(10);
  1080. ingestProgress(stub, gateway, 4, "phase-entered", { name: "phase-2" });
  1081. vi.advanceTimersByTime(10);
  1082. expect(indexFrames(stub).length).toBe(before + 1);
  1083. stub.lastActivityAt = (stub.lastActivityAt ?? 0) + 1;
  1084. gateway.ingest(
  1085. "live-1",
  1086. event("live-1", 5, SessionEventType.SessionTitleUpdated, {
  1087. previousTitle: "",
  1088. source: "custom",
  1089. title: "窗内改名",
  1090. }),
  1091. );
  1092. // 非进度事件照旧即时 publish,且捎带了窗内合并的进度。
  1093. expect(indexFrames(stub).length).toBe(before + 2);
  1094. const immediate = lastUpsertedSummary(stub);
  1095. expect(immediate?.title).toBe("窗内改名");
  1096. expect(immediate?.workflowActivity?.runs[0]?.currentPhase).toBe("phase-2");
  1097. // 待发的窗末帧已被它满足:窗口走完不再补一帧空增量。
  1098. vi.advanceTimersByTime(WINDOW_MS * 2);
  1099. expect(indexFrames(stub).length).toBe(before + 2);
  1100. });
  1101. it("dispose 清掉窗口定时器:不再发帧,也不拖住进程", async () => {
  1102. const { stub, gateway } = setup();
  1103. const before = await subscribed(stub, gateway);
  1104. ingestProgress(stub, gateway, 3, "phase-entered", { name: "phase-1" });
  1105. ingestProgress(stub, gateway, 4, "phase-entered", { name: "phase-2" });
  1106. expect(indexFrames(stub).length).toBe(before + 1);
  1107. gateway.dispose();
  1108. vi.advanceTimersByTime(10_000);
  1109. expect(indexFrames(stub).length).toBe(before + 1);
  1110. // 网关自己的定时器(attachment prune、flush、fan-out 窗口)必须一个不剩。
  1111. expect(vi.getTimerCount()).toBe(0);
  1112. });
  1113. it("窗内的 run-settled 在一个窗口内送达终态", async () => {
  1114. const { stub, gateway } = setup();
  1115. const before = await subscribed(stub, gateway);
  1116. ingestProgress(stub, gateway, 3, "phase-entered", { name: "phase-1" });
  1117. vi.advanceTimersByTime(10);
  1118. ingestProgress(stub, gateway, 4, "run-settled", { status: "completed" });
  1119. // 终态也在窗内被合并,所以此刻列表还停在 leading 那一帧。
  1120. expect(indexFrames(stub).length).toBe(before + 1);
  1121. expect(lastUpsertedSummary(stub)?.workflowActivity?.runs[0]?.status).toBe("running");
  1122. vi.advanceTimersByTime(WINDOW_MS);
  1123. expect(indexFrames(stub).length).toBe(before + 2);
  1124. expect(lastUpsertedSummary(stub)?.workflowActivity?.runs[0]?.status).toBe("completed");
  1125. });
  1126. });