sessions-index-projection.test.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. // SessionsIndexProjection / SessionsIndexPublisher 黄金测试(M5 ①,14-sessions-index):
  2. // 多会话 ConversationSnapshot → SessionSummary 派生 + upsert/remove delta + conflation + 帧记账。
  3. import { describe, expect, it } from "vitest";
  4. import type {
  5. EventId,
  6. SessionEvent,
  7. SessionEventType as SessionEventTypeUnion,
  8. SessionId,
  9. TraceId,
  10. TurnId,
  11. } from "@zcode/contracts";
  12. import { SessionEventType } from "@zcode/contracts";
  13. import {
  14. sessionsIndexSnapshotSchema,
  15. sessionsIndexTopicFrameSchema,
  16. } from "@zcode/shared/zcode-protocol-v4";
  17. import { ProductProjection } from "../src/zcode-protocol-v4/index.js";
  18. import {
  19. SessionsIndexProjection,
  20. deriveSessionSummary,
  21. } from "../src/zcode-protocol-v4/sessions-index-projection.js";
  22. import { SessionsIndexPublisher } from "../src/zcode-protocol-v4/sessions-index-publisher.js";
  23. function buildEvents(
  24. sessionId: string,
  25. build: (push: (type: SessionEventTypeUnion, payload: unknown, turnId?: string) => void) => void,
  26. ): SessionEvent[] {
  27. const events: SessionEvent[] = [];
  28. let seq = 0;
  29. build((type, payload, turnId) => {
  30. seq += 1;
  31. events.push({
  32. id: `event-${sessionId}-${seq}` as EventId,
  33. sessionId: sessionId as SessionId,
  34. turnId: turnId as TurnId | undefined,
  35. type,
  36. timestamp: new Date(1_700_000_000_000 + seq * 1000),
  37. traceId: "trace-1" as TraceId,
  38. sequenceNumber: seq,
  39. payload,
  40. });
  41. });
  42. return events;
  43. }
  44. function projectionFor(sessionId: string, events: SessionEvent[]): ProductProjection {
  45. const projection = new ProductProjection(sessionId, "epoch-1");
  46. for (const event of events) projection.applyEvent(event);
  47. return projection;
  48. }
  49. describe("SessionsIndexProjection 黄金测试(L1)", () => {
  50. it("裁剪正文不改变持久化 lastOutcome,实时 phase 也不推导历史结果", () => {
  51. const snapshot = projectionFor("s1", []).getSnapshot();
  52. const summary = deriveSessionSummary(snapshot, {
  53. workspaceId: "/repo",
  54. createdAt: 1,
  55. lastActivityAt: 2,
  56. lastOutcome: "error",
  57. });
  58. expect(summary.lastOutcome).toBe("error");
  59. expect(summary.phase).toBe("draft");
  60. });
  61. it("派生:title/phase/goal/hasBackgroundWork/preview 从会话快照取值", () => {
  62. const events = buildEvents("s1", (push) => {
  63. push(SessionEventType.SessionCreated, {
  64. mode: "default",
  65. contextWindow: 200_000,
  66. });
  67. push(SessionEventType.SessionTitleUpdated, {
  68. previousTitle: "",
  69. source: "custom",
  70. title: "我的会话",
  71. });
  72. push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi", inputId: "query-1" }, "t1");
  73. push(
  74. SessionEventType.ModelStreaming,
  75. { kind: "text_start", delta: "", done: false, assistantMessageId: "m1" },
  76. "t1",
  77. );
  78. push(
  79. SessionEventType.ModelStreaming,
  80. {
  81. kind: "text_delta",
  82. delta: "你好世界",
  83. done: false,
  84. assistantMessageId: "m1",
  85. },
  86. "t1",
  87. );
  88. push(SessionEventType.ModelStreaming, { kind: "text_end", delta: "", done: false }, "t1");
  89. push(
  90. SessionEventType.TurnComplete,
  91. {
  92. response: "",
  93. tokenCount: 0,
  94. toolCallCount: 0,
  95. duration: 0,
  96. resultType: "success",
  97. historyRoundCount: 2,
  98. },
  99. "t1",
  100. );
  101. });
  102. const snapshot = projectionFor("s1", events).getSnapshot();
  103. const summary = deriveSessionSummary(snapshot, {
  104. workspaceId: "ws-1",
  105. createdAt: 1000,
  106. lastActivityAt: 2000,
  107. lastOutcome: "completed",
  108. });
  109. expect(summary.sessionId).toBe("s1");
  110. expect(summary.workspaceId).toBe("ws-1");
  111. expect(summary.title).toBe("我的会话");
  112. expect(summary.titleSource).toBe("custom");
  113. expect(summary.phase).toBe("completedSuccess");
  114. expect(summary.lastOutcome).toBe("completed");
  115. // control.sessionEnded 由 onTurnComplete 置为 phase!=="error"(M2 既有语义,summary 忠实透传)。
  116. expect(summary.sessionEnded).toBe(true);
  117. expect(summary.hasBackgroundWork).toBe(false);
  118. expect(summary.lastAssistantPreview).toContain("你好世界");
  119. expect(summary.createdAt).toBe(1000);
  120. expect(summary.lastActivityAt).toBe(2000);
  121. });
  122. it("hasBackgroundWork:有 running 后台任务时为 true", () => {
  123. const events = buildEvents("s2", (push) => {
  124. push(SessionEventType.SessionCreated, {
  125. mode: "default",
  126. contextWindow: 200_000,
  127. });
  128. push(SessionEventType.BackgroundTaskStarted, {
  129. taskId: "bg-1",
  130. toolName: "Bash",
  131. command: "sleep 100",
  132. status: "running",
  133. });
  134. });
  135. const snapshot = projectionFor("s2", events).getSnapshot();
  136. const summary = deriveSessionSummary(snapshot, {
  137. workspaceId: "ws-1",
  138. createdAt: 1,
  139. lastActivityAt: 2,
  140. });
  141. expect(summary.hasBackgroundWork).toBe(true);
  142. });
  143. it("workflowActivity:从 workflowRuns + workflow 后台工作派生;活动时间不变时只改 node 的事件判等,phase 翻转必产帧", () => {
  144. const runProgress = (
  145. push: (type: SessionEventTypeUnion, payload: unknown) => void,
  146. sequence: number,
  147. eventType: string,
  148. payload: Record<string, unknown>,
  149. ) =>
  150. push(SessionEventType.DynamicWorkflowRunProgress, {
  151. runId: "run-1",
  152. toolCallId: "tool-1",
  153. sequence,
  154. eventType,
  155. payload,
  156. });
  157. const events = buildEvents("s-wf", (push) => {
  158. push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  159. push(SessionEventType.BackgroundTaskStarted, {
  160. taskId: "run-1",
  161. toolName: "CreateWorkflow",
  162. taskKind: "workflow",
  163. description: "Deep research",
  164. status: "running",
  165. });
  166. runProgress(push, 0, "run-started", { runId: "run-1", caps: { maxConcurrency: 4 } });
  167. runProgress(push, 1, "run-launched", {
  168. inputId: "in-1",
  169. phaseNames: ["Research", "Write"],
  170. // 进入 Write 时 Research 的 strand 还在跑:侧栏据此把两站之间画成双线段。
  171. phaseAlongside: [[], [0]],
  172. });
  173. runProgress(push, 2, "phase-entered", { name: "Research", ordinal: 1 });
  174. runProgress(push, 3, "actor-created", {
  175. actor: { siteId: "actor#1", ordinal: 1 },
  176. name: "Scout",
  177. });
  178. runProgress(push, 4, "node-queued", {
  179. instance: { siteId: "ask#1", ordinal: 1 },
  180. kind: "ask",
  181. actor: { siteId: "actor#1", ordinal: 1 },
  182. });
  183. runProgress(push, 5, "node-executing", { instance: { siteId: "ask#1", ordinal: 1 } });
  184. });
  185. const projection = projectionFor("s-wf", events);
  186. const summary = deriveSessionSummary(projection.getSnapshot(), {
  187. workspaceId: "ws-1",
  188. createdAt: 1,
  189. lastActivityAt: 2,
  190. });
  191. expect(summary.hasBackgroundWork).toBe(true);
  192. expect(summary.workflowActivity).toEqual({
  193. runs: [
  194. {
  195. runId: "run-1",
  196. toolCallId: "tool-1",
  197. name: "Deep research",
  198. status: "running",
  199. startedAt: expect.any(Number),
  200. phases: [
  201. { name: "Research", status: "running" },
  202. { name: "Write", status: "pending", alongside: [0] },
  203. ],
  204. currentPhase: "Research",
  205. agentsWorking: 1,
  206. },
  207. ],
  208. });
  209. // 同一 run 再来只改 node / 用量、不改 phase / status / 子代理数的事件:摘要判等,不产侧栏帧。
  210. const index = new SessionsIndexProjection("ws-1", "epoch-1");
  211. expect(
  212. index.upsertFromConversation(projection.getSnapshot(), { createdAt: 1, lastActivityAt: 2 }),
  213. ).toHaveLength(1);
  214. const nodeOnly = buildEvents("s-wf", (push) => {
  215. runProgress(push, 6, "node-queued", {
  216. instance: { siteId: "ask#2", ordinal: 1 },
  217. kind: "ask",
  218. actor: { siteId: "actor#1", ordinal: 1 },
  219. });
  220. runProgress(push, 7, "usage-updated", { spentTokens: 120 });
  221. });
  222. for (const event of nodeOnly) projection.applyEvent(event);
  223. expect(
  224. index.upsertFromConversation(projection.getSnapshot(), { createdAt: 1, lastActivityAt: 2 }),
  225. ).toEqual([]);
  226. // 进入下一个 phase 则产 delta,且站点灯随之翻转。
  227. const [phase] = buildEvents("s-wf", (push) =>
  228. runProgress(push, 8, "phase-entered", { name: "Write", ordinal: 1 }),
  229. );
  230. projection.applyEvent(phase!);
  231. const deltas = index.upsertFromConversation(projection.getSnapshot(), {
  232. createdAt: 1,
  233. lastActivityAt: 2,
  234. });
  235. expect(deltas).toHaveLength(1);
  236. const delta = deltas[0]!;
  237. if (delta.op !== "session.upserted") throw new Error("expected upsert");
  238. expect(delta.session.workflowActivity?.runs[0]?.phases.map((p) => p.status)).toEqual([
  239. "done",
  240. "running",
  241. ]);
  242. });
  243. it("projects the head interaction auto-resolution state into the lightweight summary", () => {
  244. const events = buildEvents("s-ask", (push) => {
  245. push(SessionEventType.SessionCreated, {
  246. mode: "default",
  247. contextWindow: 200_000,
  248. });
  249. push(SessionEventType.PermissionRequested, {
  250. requestId: "ask-1",
  251. toolCallId: "tool-1",
  252. toolName: "AskUserQuestion",
  253. riskLevel: "low",
  254. reason: "Need input",
  255. input: {
  256. questions: [
  257. {
  258. header: "Choice",
  259. question: "Choose?",
  260. options: [
  261. { label: "A", description: "a" },
  262. { label: "B", description: "b" },
  263. ],
  264. },
  265. ],
  266. },
  267. });
  268. push(SessionEventType.UserInputAutoResolutionUpdated, {
  269. interactionId: "ask-1",
  270. toolCallId: "tool-1",
  271. autoResolution: {
  272. state: "visibleCountdown",
  273. startedAt: 1_000,
  274. visibleAt: 61_000,
  275. deadlineAt: 301_000,
  276. },
  277. });
  278. });
  279. const summary = deriveSessionSummary(projectionFor("s-ask", events).getSnapshot(), {
  280. workspaceId: "ws-1",
  281. createdAt: 1,
  282. lastActivityAt: 2,
  283. });
  284. expect(summary.pendingInteraction).toEqual({
  285. interactionId: "ask-1",
  286. kind: "userInput",
  287. toolName: "AskUserQuestion",
  288. autoResolution: {
  289. state: "visibleCountdown",
  290. startedAt: 1_000,
  291. visibleAt: 61_000,
  292. deadlineAt: 301_000,
  293. },
  294. });
  295. });
  296. it("只投影 pending interaction 的 kind/count,不下发 payload", () => {
  297. const events = buildEvents("s-interactions", (push) => {
  298. push(SessionEventType.SessionCreated, {
  299. mode: "default",
  300. contextWindow: 200_000,
  301. });
  302. });
  303. const baseSnapshot = projectionFor("s-interactions", events).getSnapshot();
  304. const summary = deriveSessionSummary(
  305. {
  306. ...baseSnapshot,
  307. pendingInteractions: [
  308. { kind: "permission" } as never,
  309. { kind: "permission" } as never,
  310. { kind: "userInput" } as never,
  311. ],
  312. },
  313. {
  314. workspaceId: "ws-1",
  315. createdAt: 1,
  316. lastActivityAt: 2,
  317. },
  318. );
  319. expect(summary.pendingInteractionSummary).toEqual({
  320. permissionCount: 2,
  321. userInputCount: 1,
  322. });
  323. expect(summary).not.toHaveProperty("pendingInteractions");
  324. });
  325. it("不把 workspace Hook review 降级成 permission/userInput 侧栏状态", () => {
  326. const events = buildEvents("s-workspace-review", (push) => {
  327. push(SessionEventType.SessionCreated, {
  328. mode: "default",
  329. contextWindow: 200_000,
  330. });
  331. });
  332. const baseSnapshot = projectionFor("s-workspace-review", events).getSnapshot();
  333. const summary = deriveSessionSummary(
  334. {
  335. ...baseSnapshot,
  336. pendingInteractions: [
  337. {
  338. interactionId: "workspace-review-1",
  339. kind: "workspaceHookReview",
  340. payload: { kind: "workspaceHookReview" },
  341. } as never,
  342. ],
  343. },
  344. {
  345. workspaceId: "ws-1",
  346. createdAt: 1,
  347. lastActivityAt: 2,
  348. },
  349. );
  350. expect(summary).not.toHaveProperty("pendingInteraction");
  351. expect(summary).not.toHaveProperty("pendingInteractionSummary");
  352. });
  353. it("index:upsert 变化才产 delta(conflation),remove 命中产 delta", () => {
  354. const index = new SessionsIndexProjection("ws-1", "list-epoch-1");
  355. const events = buildEvents("s1", (push) => {
  356. push(SessionEventType.SessionCreated, {
  357. mode: "default",
  358. contextWindow: 200_000,
  359. });
  360. });
  361. const snapshot = projectionFor("s1", events).getSnapshot();
  362. const extra = { createdAt: 1, lastActivityAt: 2 };
  363. // 首次 upsert 产 delta
  364. const d1 = index.upsertFromConversation(snapshot, extra);
  365. expect(d1).toHaveLength(1);
  366. expect(d1[0]).toMatchObject({ op: "session.upserted" });
  367. // 相同 snapshot + extra → 幂等无 delta
  368. const d2 = index.upsertFromConversation(snapshot, extra);
  369. expect(d2).toHaveLength(0);
  370. // lastActivityAt 变化 → 再产 upsert
  371. const d3 = index.upsertFromConversation(snapshot, {
  372. createdAt: 1,
  373. lastActivityAt: 3,
  374. });
  375. expect(d3).toHaveLength(1);
  376. // 快照含该会话
  377. expect(index.getSnapshot().sessions.map((s) => s.sessionId)).toEqual(["s1"]);
  378. // remove 命中产 delta,再 remove 幂等
  379. expect(index.remove("s1")).toHaveLength(1);
  380. expect(index.remove("s1")).toHaveLength(0);
  381. expect(index.getSnapshot().sessions).toHaveLength(0);
  382. });
  383. it("index:stored→live 降级防御——live 空标题/新时间不得覆盖 store 种子", () => {
  384. const index = new SessionsIndexProjection("ws-1", "list-epoch-1");
  385. // store 种子:带标题与原始时间(模拟侧栏冷启动)。
  386. index.seed({
  387. sessionId: "s1",
  388. workspaceId: "ws-1",
  389. title: "项目分析与优化",
  390. phase: "completedSuccess",
  391. sessionEnded: true,
  392. hasBackgroundWork: false,
  393. lastActivityAt: 100,
  394. lastAssistantPreview: "旧预览",
  395. createdAt: 10,
  396. });
  397. // 冷恢复的 live 投影:hydration 前 meta.title 为空、record 时间被 resume 重置为"现在"。
  398. const events = buildEvents("s1", (push) => {
  399. push(SessionEventType.SessionCreated, {
  400. mode: "default",
  401. contextWindow: 200_000,
  402. });
  403. });
  404. const snapshot = projectionFor("s1", events).getSnapshot();
  405. index.upsertFromConversation(snapshot, {
  406. createdAt: 9_999,
  407. lastActivityAt: 9_999,
  408. });
  409. const merged = index.getSnapshot().sessions.find((s) => s.sessionId === "s1");
  410. expect(merged?.title).toBe("项目分析与优化");
  411. expect(merged?.createdAt).toBe(10);
  412. expect(merged?.lastAssistantPreview).toBe("旧预览");
  413. // Bugfix 断言:hydration 前的 live 投影 phase 是初始 draft,不得把终态基线降级。
  414. expect(merged?.phase).toBe("completedSuccess");
  415. expect(merged?.sessionEnded).toBe(true);
  416. });
  417. it("index:冷恢复 draft 窗口快照与基线等价时不产 delta(打开历史任务不刷列表)", () => {
  418. const index = new SessionsIndexProjection("ws-1", "list-epoch-1");
  419. index.seed({
  420. sessionId: "s1",
  421. workspaceId: "ws-1",
  422. title: "项目分析与优化",
  423. phase: "completedSuccess",
  424. sessionEnded: true,
  425. hasBackgroundWork: false,
  426. lastActivityAt: 100,
  427. lastAssistantPreview: "旧预览",
  428. createdAt: 10,
  429. });
  430. // 冷恢复 live 投影(hydration 未完成):phase=draft、无标题/预览;
  431. // record 时间已由 resume 路径回填 store 真实时间(lastActivityAt 一致)。
  432. const events = buildEvents("s1", (push) => {
  433. push(SessionEventType.SessionCreated, {
  434. mode: "default",
  435. contextWindow: 200_000,
  436. });
  437. });
  438. const snapshot = projectionFor("s1", events).getSnapshot();
  439. const deltas = index.upsertFromConversation(snapshot, {
  440. createdAt: 10,
  441. lastActivityAt: 100,
  442. });
  443. // 所有字段被降级防御保住 → summariesEqual → 零 delta,UI 列表不动。
  444. expect(deltas).toHaveLength(0);
  445. });
  446. it("index:多会话快照 schema 合法 + 无序聚合", () => {
  447. const index = new SessionsIndexProjection("ws-1", "list-epoch-1");
  448. for (const sid of ["a", "b", "c"]) {
  449. const events = buildEvents(sid, (push) => {
  450. push(SessionEventType.SessionCreated, {
  451. mode: "default",
  452. contextWindow: 200_000,
  453. });
  454. });
  455. index.upsertFromConversation(projectionFor(sid, events).getSnapshot(), {
  456. createdAt: 1,
  457. lastActivityAt: 2,
  458. });
  459. }
  460. const snap = index.getSnapshot();
  461. expect(snap.sessions).toHaveLength(3);
  462. expect(new Set(snap.sessions.map((s) => s.sessionId))).toEqual(new Set(["a", "b", "c"]));
  463. // 帧 schema 合法性
  464. expect(() => sessionsIndexSnapshotSchema.parse(snap)).not.toThrow();
  465. });
  466. it("fork:parentSessionId 透传", () => {
  467. const events = buildEvents("child", (push) => {
  468. push(SessionEventType.SessionCreated, {
  469. mode: "default",
  470. contextWindow: 200_000,
  471. });
  472. });
  473. const snapshot = projectionFor("child", events).getSnapshot();
  474. const summary = deriveSessionSummary(snapshot, {
  475. workspaceId: "ws-1",
  476. createdAt: 1,
  477. lastActivityAt: 2,
  478. parentSessionId: "parent",
  479. });
  480. expect(summary.parentSessionId).toBe("parent");
  481. });
  482. });
  483. describe("SessionsIndexPublisher 单测(帧记账)", () => {
  484. let clock = 1000;
  485. const now = () => (clock += 1);
  486. function snap(sessionId: string): ReturnType<ProductProjection["getSnapshot"]> {
  487. const events = buildEvents(sessionId, (push) => {
  488. push(SessionEventType.SessionCreated, {
  489. mode: "default",
  490. contextWindow: 200_000,
  491. });
  492. });
  493. return projectionFor(sessionId, events).getSnapshot();
  494. }
  495. it("subscribe → snapshot 帧(fromSeq=0),帧 schema 合法", () => {
  496. const pub = new SessionsIndexPublisher("ws-1", "epoch-1", now);
  497. pub.ingestConversation(snap("a"), { createdAt: 1, lastActivityAt: 2 });
  498. const res = pub.subscribe("conn-1");
  499. expect(res.mode).toBe("snapshot");
  500. expect(res.frame?.payload.kind).toBe("snapshot");
  501. expect(res.frame?.fromSeq).toBe(0);
  502. expect(() => sessionsIndexTopicFrameSchema.parse(res.frame)).not.toThrow();
  503. });
  504. it("订阅后 ingest → flush 出增量帧((fromSeq, toSeq])", () => {
  505. const pub = new SessionsIndexPublisher("ws-1", "epoch-1", now);
  506. const res = pub.subscribe("conn-1");
  507. const baseSeq = res.frame?.toSeq ?? 0;
  508. // 新会话进入 → 有变化
  509. expect(pub.ingestConversation(snap("a"), { createdAt: 1, lastActivityAt: 2 })).toBe(true);
  510. const frame = pub.flush(res.subscriptionId);
  511. expect(frame?.payload.kind).toBe("deltas");
  512. expect(frame?.fromSeq).toBe(baseSeq);
  513. expect(frame?.toSeq).toBe(pub.seq);
  514. if (frame?.payload.kind === "deltas") {
  515. expect(frame.payload.deltas[0]).toMatchObject({ op: "session.upserted" });
  516. }
  517. // 已排空 → 再 flush 为 null
  518. expect(pub.flush(res.subscriptionId)).toBeNull();
  519. });
  520. it("幂等 ingest 不产帧;resume base=当前 seq → frame null", () => {
  521. const pub = new SessionsIndexPublisher("ws-1", "epoch-1", now);
  522. pub.ingestConversation(snap("a"), { createdAt: 1, lastActivityAt: 2 });
  523. // 同快照再进 → 无变化
  524. expect(pub.ingestConversation(snap("a"), { createdAt: 1, lastActivityAt: 2 })).toBe(false);
  525. const res = pub.subscribe("conn-1", { logEpoch: "epoch-1", seq: pub.seq });
  526. expect(res.mode).toBe("resume");
  527. expect(res.frame).toBeNull();
  528. });
  529. it("removeSession → remove delta 帧", () => {
  530. const pub = new SessionsIndexPublisher("ws-1", "epoch-1", now);
  531. pub.ingestConversation(snap("a"), { createdAt: 1, lastActivityAt: 2 });
  532. const res = pub.subscribe("conn-1");
  533. expect(pub.removeSession("a")).toBe(true);
  534. const frame = pub.flush(res.subscriptionId);
  535. if (frame?.payload.kind === "deltas") {
  536. expect(frame.payload.deltas[0]).toMatchObject({
  537. op: "session.removed",
  538. sessionId: "a",
  539. });
  540. } else {
  541. throw new Error("expected deltas frame");
  542. }
  543. });
  544. it("异代际 base → 退化 snapshot;重订阅替换旧代际(同 connection 新 subscriptionId)", () => {
  545. const pub = new SessionsIndexPublisher("ws-1", "epoch-1", now);
  546. pub.ingestConversation(snap("a"), { createdAt: 1, lastActivityAt: 2 });
  547. const stale = pub.subscribe("conn-1", { logEpoch: "other-epoch", seq: 1 });
  548. expect(stale.mode).toBe("snapshot");
  549. expect(stale.frame?.payload.kind).toBe("snapshot");
  550. const replaced = pub.subscribe("conn-1");
  551. expect(replaced.subscriptionId).not.toBe(stale.subscriptionId);
  552. expect(pub.subscriptionIds()).toEqual([replaced.subscriptionId]);
  553. });
  554. });