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

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