sessions-index-projection.test.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  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("hasCompactWork:只跟踪 compact 活跃态,并在开始与结束时产出 upsert", () => {
  123. const events = buildEvents("s-compact", (push) => {
  124. push(SessionEventType.SessionCreated, {
  125. mode: "default",
  126. contextWindow: 200_000,
  127. });
  128. push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi", inputId: "query-1" }, "t1");
  129. push(
  130. SessionEventType.TurnComplete,
  131. {
  132. response: "done",
  133. tokenCount: 0,
  134. toolCallCount: 0,
  135. duration: 0,
  136. resultType: "success",
  137. historyRoundCount: 1,
  138. },
  139. "t1",
  140. );
  141. });
  142. const projection = projectionFor("s-compact", events);
  143. const index = new SessionsIndexProjection("ws-1", "epoch-1");
  144. const extra = { createdAt: 1, lastActivityAt: 2 };
  145. expect(index.upsertFromConversation(projection.getSnapshot(), extra)[0]).toMatchObject({
  146. op: "session.upserted",
  147. session: { hasCompactWork: false },
  148. });
  149. const [started] = buildEvents("s-compact", (push) =>
  150. push(SessionEventType.CompactStarted, {
  151. operationId: "op-1",
  152. messageId: "msg-1",
  153. status: "started",
  154. trigger: "manual",
  155. display: "separator",
  156. }),
  157. );
  158. projection.applyEvent(started!);
  159. expect(index.upsertFromConversation(projection.getSnapshot(), extra)[0]).toMatchObject({
  160. op: "session.upserted",
  161. session: { hasCompactWork: true },
  162. });
  163. const [completed] = buildEvents("s-compact", (push) =>
  164. push(SessionEventType.CompactCompleted, {
  165. operationId: "op-1",
  166. messageId: "msg-1",
  167. status: "completed",
  168. trigger: "manual",
  169. display: "separator",
  170. preCompactTokenCount: 800,
  171. postCompactTokenCount: 300,
  172. }),
  173. );
  174. projection.applyEvent(completed!);
  175. expect(index.upsertFromConversation(projection.getSnapshot(), extra)[0]).toMatchObject({
  176. op: "session.upserted",
  177. session: { hasCompactWork: false },
  178. });
  179. const base = projection.getSnapshot();
  180. const otherActiveWork = {
  181. ...base,
  182. control: {
  183. ...base.control,
  184. activeWorks: [{ kind: "goalVerifier" as const, startedAt: 1 }],
  185. },
  186. };
  187. expect(deriveSessionSummary(otherActiveWork, {
  188. workspaceId: "ws-1",
  189. createdAt: 1,
  190. lastActivityAt: 2,
  191. })).toMatchObject({ hasCompactWork: false });
  192. });
  193. it("old sessions-index summary without hasCompactWork remains valid and means false", () => {
  194. const summary = deriveSessionSummary(projectionFor("s-old", []).getSnapshot(), {
  195. workspaceId: "ws-1",
  196. createdAt: 1,
  197. lastActivityAt: 2,
  198. });
  199. const { hasCompactWork: _ignored, ...oldSummary } = {
  200. ...summary,
  201. hasCompactWork: false,
  202. };
  203. const parsed = sessionsIndexSnapshotSchema.parse({
  204. protocolVersion: 1,
  205. workspaceId: "ws-1",
  206. logEpoch: "epoch-1",
  207. sessions: [oldSummary],
  208. });
  209. expect(parsed.sessions[0]).not.toHaveProperty("hasCompactWork");
  210. const index = new SessionsIndexProjection("ws-1", "epoch-1");
  211. index.seed(parsed.sessions[0]!);
  212. expect(index.upsertFromConversation(projectionFor("s-old", []).getSnapshot(), {
  213. createdAt: 1,
  214. lastActivityAt: 2,
  215. })).toEqual([]);
  216. expect(sessionsIndexSnapshotSchema.parse({
  217. ...parsed,
  218. sessions: [{ ...oldSummary, hasCompactWork: true }],
  219. }).sessions[0]).toMatchObject({ hasCompactWork: true });
  220. expect(sessionsIndexSnapshotSchema.safeParse({
  221. ...parsed,
  222. sessions: [{ ...oldSummary, hasCompactWork: "true" }],
  223. }).success).toBe(false);
  224. });
  225. it("hasBackgroundWork:有 running 后台任务时为 true", () => {
  226. const events = buildEvents("s2", (push) => {
  227. push(SessionEventType.SessionCreated, {
  228. mode: "default",
  229. contextWindow: 200_000,
  230. });
  231. push(SessionEventType.BackgroundTaskStarted, {
  232. taskId: "bg-1",
  233. toolName: "Bash",
  234. command: "sleep 100",
  235. status: "running",
  236. });
  237. });
  238. const snapshot = projectionFor("s2", events).getSnapshot();
  239. const summary = deriveSessionSummary(snapshot, {
  240. workspaceId: "ws-1",
  241. createdAt: 1,
  242. lastActivityAt: 2,
  243. });
  244. expect(summary.hasBackgroundWork).toBe(true);
  245. });
  246. it("workflowActivity:从 workflowRuns + workflow 后台工作派生;活动时间不变时只改 node 的事件判等,phase 翻转必产帧", () => {
  247. const runProgress = (
  248. push: (type: SessionEventTypeUnion, payload: unknown) => void,
  249. sequence: number,
  250. eventType: string,
  251. payload: Record<string, unknown>,
  252. ) =>
  253. push(SessionEventType.DynamicWorkflowRunProgress, {
  254. runId: "run-1",
  255. toolCallId: "tool-1",
  256. sequence,
  257. eventType,
  258. payload,
  259. });
  260. const events = buildEvents("s-wf", (push) => {
  261. push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  262. push(SessionEventType.BackgroundTaskStarted, {
  263. taskId: "run-1",
  264. toolName: "CreateWorkflow",
  265. taskKind: "workflow",
  266. description: "Deep research",
  267. status: "running",
  268. });
  269. runProgress(push, 0, "run-started", { runId: "run-1", caps: { maxConcurrency: 4 } });
  270. runProgress(push, 1, "run-launched", {
  271. inputId: "in-1",
  272. phaseNames: ["Research", "Write"],
  273. // 进入 Write 时 Research 的 strand 还在跑:侧栏据此把两站之间画成双线段。
  274. phaseAlongside: [[], [0]],
  275. });
  276. runProgress(push, 2, "phase-entered", { name: "Research", ordinal: 1 });
  277. runProgress(push, 3, "actor-created", {
  278. actor: { siteId: "actor#1", ordinal: 1 },
  279. name: "Scout",
  280. });
  281. runProgress(push, 4, "node-queued", {
  282. instance: { siteId: "ask#1", ordinal: 1 },
  283. kind: "ask",
  284. actor: { siteId: "actor#1", ordinal: 1 },
  285. });
  286. runProgress(push, 5, "node-executing", { instance: { siteId: "ask#1", ordinal: 1 } });
  287. });
  288. const projection = projectionFor("s-wf", events);
  289. const summary = deriveSessionSummary(projection.getSnapshot(), {
  290. workspaceId: "ws-1",
  291. createdAt: 1,
  292. lastActivityAt: 2,
  293. });
  294. expect(summary.hasBackgroundWork).toBe(true);
  295. expect(summary.workflowActivity).toEqual({
  296. runs: [
  297. {
  298. runId: "run-1",
  299. toolCallId: "tool-1",
  300. name: "Deep research",
  301. status: "running",
  302. startedAt: expect.any(Number),
  303. phases: [
  304. { name: "Research", status: "running" },
  305. { name: "Write", status: "pending", alongside: [0] },
  306. ],
  307. currentPhase: "Research",
  308. agentsWorking: 1,
  309. },
  310. ],
  311. });
  312. // 同一 run 再来只改 node / 用量、不改 phase / status / 子代理数的事件:摘要判等,不产侧栏帧。
  313. const index = new SessionsIndexProjection("ws-1", "epoch-1");
  314. expect(
  315. index.upsertFromConversation(projection.getSnapshot(), { createdAt: 1, lastActivityAt: 2 }),
  316. ).toHaveLength(1);
  317. const nodeOnly = buildEvents("s-wf", (push) => {
  318. runProgress(push, 6, "node-queued", {
  319. instance: { siteId: "ask#2", ordinal: 1 },
  320. kind: "ask",
  321. actor: { siteId: "actor#1", ordinal: 1 },
  322. });
  323. runProgress(push, 7, "usage-updated", { spentTokens: 120 });
  324. });
  325. for (const event of nodeOnly) projection.applyEvent(event);
  326. expect(
  327. index.upsertFromConversation(projection.getSnapshot(), { createdAt: 1, lastActivityAt: 2 }),
  328. ).toEqual([]);
  329. // 进入下一个 phase 则产 delta,且站点灯随之翻转。
  330. const [phase] = buildEvents("s-wf", (push) =>
  331. runProgress(push, 8, "phase-entered", { name: "Write", ordinal: 1 }),
  332. );
  333. projection.applyEvent(phase!);
  334. const deltas = index.upsertFromConversation(projection.getSnapshot(), {
  335. createdAt: 1,
  336. lastActivityAt: 2,
  337. });
  338. expect(deltas).toHaveLength(1);
  339. const delta = deltas[0]!;
  340. if (delta.op !== "session.upserted") throw new Error("expected upsert");
  341. expect(delta.session.workflowActivity?.runs[0]?.phases.map((p) => p.status)).toEqual([
  342. "done",
  343. "running",
  344. ]);
  345. });
  346. it("projects the head interaction auto-resolution state into the lightweight summary", () => {
  347. const events = buildEvents("s-ask", (push) => {
  348. push(SessionEventType.SessionCreated, {
  349. mode: "default",
  350. contextWindow: 200_000,
  351. });
  352. push(SessionEventType.PermissionRequested, {
  353. requestId: "ask-1",
  354. toolCallId: "tool-1",
  355. toolName: "AskUserQuestion",
  356. riskLevel: "low",
  357. reason: "Need input",
  358. input: {
  359. questions: [
  360. {
  361. header: "Choice",
  362. question: "Choose?",
  363. options: [
  364. { label: "A", description: "a" },
  365. { label: "B", description: "b" },
  366. ],
  367. },
  368. ],
  369. },
  370. });
  371. push(SessionEventType.UserInputAutoResolutionUpdated, {
  372. interactionId: "ask-1",
  373. toolCallId: "tool-1",
  374. autoResolution: {
  375. state: "visibleCountdown",
  376. startedAt: 1_000,
  377. visibleAt: 61_000,
  378. deadlineAt: 301_000,
  379. },
  380. });
  381. });
  382. const summary = deriveSessionSummary(projectionFor("s-ask", events).getSnapshot(), {
  383. workspaceId: "ws-1",
  384. createdAt: 1,
  385. lastActivityAt: 2,
  386. });
  387. expect(summary.pendingInteraction).toEqual({
  388. interactionId: "ask-1",
  389. kind: "userInput",
  390. toolName: "AskUserQuestion",
  391. autoResolution: {
  392. state: "visibleCountdown",
  393. startedAt: 1_000,
  394. visibleAt: 61_000,
  395. deadlineAt: 301_000,
  396. },
  397. });
  398. });
  399. it("只投影 pending interaction 的 kind/count,不下发 payload", () => {
  400. const events = buildEvents("s-interactions", (push) => {
  401. push(SessionEventType.SessionCreated, {
  402. mode: "default",
  403. contextWindow: 200_000,
  404. });
  405. });
  406. const baseSnapshot = projectionFor("s-interactions", events).getSnapshot();
  407. const summary = deriveSessionSummary(
  408. {
  409. ...baseSnapshot,
  410. pendingInteractions: [
  411. { kind: "permission" } as never,
  412. { kind: "permission" } as never,
  413. { kind: "userInput" } as never,
  414. ],
  415. },
  416. {
  417. workspaceId: "ws-1",
  418. createdAt: 1,
  419. lastActivityAt: 2,
  420. },
  421. );
  422. expect(summary.pendingInteractionSummary).toEqual({
  423. permissionCount: 2,
  424. userInputCount: 1,
  425. });
  426. expect(summary).not.toHaveProperty("pendingInteractions");
  427. });
  428. it("不把 workspace Hook review 降级成 permission/userInput 侧栏状态", () => {
  429. const events = buildEvents("s-workspace-review", (push) => {
  430. push(SessionEventType.SessionCreated, {
  431. mode: "default",
  432. contextWindow: 200_000,
  433. });
  434. });
  435. const baseSnapshot = projectionFor("s-workspace-review", events).getSnapshot();
  436. const summary = deriveSessionSummary(
  437. {
  438. ...baseSnapshot,
  439. pendingInteractions: [
  440. {
  441. interactionId: "workspace-review-1",
  442. kind: "workspaceHookReview",
  443. payload: { kind: "workspaceHookReview" },
  444. } as never,
  445. ],
  446. },
  447. {
  448. workspaceId: "ws-1",
  449. createdAt: 1,
  450. lastActivityAt: 2,
  451. },
  452. );
  453. expect(summary).not.toHaveProperty("pendingInteraction");
  454. expect(summary).not.toHaveProperty("pendingInteractionSummary");
  455. });
  456. it("index:upsert 变化才产 delta(conflation),remove 命中产 delta", () => {
  457. const index = new SessionsIndexProjection("ws-1", "list-epoch-1");
  458. const events = buildEvents("s1", (push) => {
  459. push(SessionEventType.SessionCreated, {
  460. mode: "default",
  461. contextWindow: 200_000,
  462. });
  463. });
  464. const snapshot = projectionFor("s1", events).getSnapshot();
  465. const extra = { createdAt: 1, lastActivityAt: 2 };
  466. // 首次 upsert 产 delta
  467. const d1 = index.upsertFromConversation(snapshot, extra);
  468. expect(d1).toHaveLength(1);
  469. expect(d1[0]).toMatchObject({ op: "session.upserted" });
  470. // 相同 snapshot + extra → 幂等无 delta
  471. const d2 = index.upsertFromConversation(snapshot, extra);
  472. expect(d2).toHaveLength(0);
  473. // lastActivityAt 变化 → 再产 upsert
  474. const d3 = index.upsertFromConversation(snapshot, {
  475. createdAt: 1,
  476. lastActivityAt: 3,
  477. });
  478. expect(d3).toHaveLength(1);
  479. // 快照含该会话
  480. expect(index.getSnapshot().sessions.map((s) => s.sessionId)).toEqual(["s1"]);
  481. // remove 命中产 delta,再 remove 幂等
  482. expect(index.remove("s1")).toHaveLength(1);
  483. expect(index.remove("s1")).toHaveLength(0);
  484. expect(index.getSnapshot().sessions).toHaveLength(0);
  485. });
  486. it("index:stored→live 降级防御——live 空标题/新时间不得覆盖 store 种子", () => {
  487. const index = new SessionsIndexProjection("ws-1", "list-epoch-1");
  488. // store 种子:带标题与原始时间(模拟侧栏冷启动)。
  489. index.seed({
  490. sessionId: "s1",
  491. workspaceId: "ws-1",
  492. title: "项目分析与优化",
  493. phase: "completedSuccess",
  494. sessionEnded: true,
  495. hasBackgroundWork: false,
  496. lastActivityAt: 100,
  497. lastAssistantPreview: "旧预览",
  498. createdAt: 10,
  499. });
  500. // 冷恢复的 live 投影:hydration 前 meta.title 为空、record 时间被 resume 重置为"现在"。
  501. const events = buildEvents("s1", (push) => {
  502. push(SessionEventType.SessionCreated, {
  503. mode: "default",
  504. contextWindow: 200_000,
  505. });
  506. });
  507. const snapshot = projectionFor("s1", events).getSnapshot();
  508. index.upsertFromConversation(snapshot, {
  509. createdAt: 9_999,
  510. lastActivityAt: 9_999,
  511. });
  512. const merged = index.getSnapshot().sessions.find((s) => s.sessionId === "s1");
  513. expect(merged?.title).toBe("项目分析与优化");
  514. expect(merged?.createdAt).toBe(10);
  515. expect(merged?.lastAssistantPreview).toBe("旧预览");
  516. // Bugfix 断言:hydration 前的 live 投影 phase 是初始 draft,不得把终态基线降级。
  517. expect(merged?.phase).toBe("completedSuccess");
  518. expect(merged?.sessionEnded).toBe(true);
  519. });
  520. it("index:冷恢复 draft 窗口快照与基线等价时不产 delta(打开历史任务不刷列表)", () => {
  521. const index = new SessionsIndexProjection("ws-1", "list-epoch-1");
  522. index.seed({
  523. sessionId: "s1",
  524. workspaceId: "ws-1",
  525. title: "项目分析与优化",
  526. phase: "completedSuccess",
  527. sessionEnded: true,
  528. hasBackgroundWork: false,
  529. lastActivityAt: 100,
  530. lastAssistantPreview: "旧预览",
  531. createdAt: 10,
  532. });
  533. // 冷恢复 live 投影(hydration 未完成):phase=draft、无标题/预览;
  534. // record 时间已由 resume 路径回填 store 真实时间(lastActivityAt 一致)。
  535. const events = buildEvents("s1", (push) => {
  536. push(SessionEventType.SessionCreated, {
  537. mode: "default",
  538. contextWindow: 200_000,
  539. });
  540. });
  541. const snapshot = projectionFor("s1", events).getSnapshot();
  542. const deltas = index.upsertFromConversation(snapshot, {
  543. createdAt: 10,
  544. lastActivityAt: 100,
  545. });
  546. // 所有字段被降级防御保住 → summariesEqual → 零 delta,UI 列表不动。
  547. expect(deltas).toHaveLength(0);
  548. });
  549. it("index:多会话快照 schema 合法 + 无序聚合", () => {
  550. const index = new SessionsIndexProjection("ws-1", "list-epoch-1");
  551. for (const sid of ["a", "b", "c"]) {
  552. const events = buildEvents(sid, (push) => {
  553. push(SessionEventType.SessionCreated, {
  554. mode: "default",
  555. contextWindow: 200_000,
  556. });
  557. });
  558. index.upsertFromConversation(projectionFor(sid, events).getSnapshot(), {
  559. createdAt: 1,
  560. lastActivityAt: 2,
  561. });
  562. }
  563. const snap = index.getSnapshot();
  564. expect(snap.sessions).toHaveLength(3);
  565. expect(new Set(snap.sessions.map((s) => s.sessionId))).toEqual(new Set(["a", "b", "c"]));
  566. // 帧 schema 合法性
  567. expect(() => sessionsIndexSnapshotSchema.parse(snap)).not.toThrow();
  568. });
  569. it("fork:parentSessionId 透传", () => {
  570. const events = buildEvents("child", (push) => {
  571. push(SessionEventType.SessionCreated, {
  572. mode: "default",
  573. contextWindow: 200_000,
  574. });
  575. });
  576. const snapshot = projectionFor("child", events).getSnapshot();
  577. const summary = deriveSessionSummary(snapshot, {
  578. workspaceId: "ws-1",
  579. createdAt: 1,
  580. lastActivityAt: 2,
  581. parentSessionId: "parent",
  582. });
  583. expect(summary.parentSessionId).toBe("parent");
  584. });
  585. });
  586. describe("SessionsIndexPublisher 单测(帧记账)", () => {
  587. let clock = 1000;
  588. const now = () => (clock += 1);
  589. function snap(sessionId: string): ReturnType<ProductProjection["getSnapshot"]> {
  590. const events = buildEvents(sessionId, (push) => {
  591. push(SessionEventType.SessionCreated, {
  592. mode: "default",
  593. contextWindow: 200_000,
  594. });
  595. });
  596. return projectionFor(sessionId, events).getSnapshot();
  597. }
  598. it("subscribe → snapshot 帧(fromSeq=0),帧 schema 合法", () => {
  599. const pub = new SessionsIndexPublisher("ws-1", "epoch-1", now);
  600. pub.ingestConversation(snap("a"), { createdAt: 1, lastActivityAt: 2 });
  601. const res = pub.subscribe("conn-1");
  602. expect(res.mode).toBe("snapshot");
  603. expect(res.frame?.payload.kind).toBe("snapshot");
  604. expect(res.frame?.fromSeq).toBe(0);
  605. expect(() => sessionsIndexTopicFrameSchema.parse(res.frame)).not.toThrow();
  606. });
  607. it("订阅后 ingest → flush 出增量帧((fromSeq, toSeq])", () => {
  608. const pub = new SessionsIndexPublisher("ws-1", "epoch-1", now);
  609. const res = pub.subscribe("conn-1");
  610. const baseSeq = res.frame?.toSeq ?? 0;
  611. // 新会话进入 → 有变化
  612. expect(pub.ingestConversation(snap("a"), { createdAt: 1, lastActivityAt: 2 })).toBe(true);
  613. const frame = pub.flush(res.subscriptionId);
  614. expect(frame?.payload.kind).toBe("deltas");
  615. expect(frame?.fromSeq).toBe(baseSeq);
  616. expect(frame?.toSeq).toBe(pub.seq);
  617. if (frame?.payload.kind === "deltas") {
  618. expect(frame.payload.deltas[0]).toMatchObject({ op: "session.upserted" });
  619. }
  620. // 已排空 → 再 flush 为 null
  621. expect(pub.flush(res.subscriptionId)).toBeNull();
  622. });
  623. it("幂等 ingest 不产帧;resume base=当前 seq → frame null", () => {
  624. const pub = new SessionsIndexPublisher("ws-1", "epoch-1", now);
  625. pub.ingestConversation(snap("a"), { createdAt: 1, lastActivityAt: 2 });
  626. // 同快照再进 → 无变化
  627. expect(pub.ingestConversation(snap("a"), { createdAt: 1, lastActivityAt: 2 })).toBe(false);
  628. const res = pub.subscribe("conn-1", { logEpoch: "epoch-1", seq: pub.seq });
  629. expect(res.mode).toBe("resume");
  630. expect(res.frame).toBeNull();
  631. });
  632. it("removeSession → remove delta 帧", () => {
  633. const pub = new SessionsIndexPublisher("ws-1", "epoch-1", now);
  634. pub.ingestConversation(snap("a"), { createdAt: 1, lastActivityAt: 2 });
  635. const res = pub.subscribe("conn-1");
  636. expect(pub.removeSession("a")).toBe(true);
  637. const frame = pub.flush(res.subscriptionId);
  638. if (frame?.payload.kind === "deltas") {
  639. expect(frame.payload.deltas[0]).toMatchObject({
  640. op: "session.removed",
  641. sessionId: "a",
  642. });
  643. } else {
  644. throw new Error("expected deltas frame");
  645. }
  646. });
  647. it("异代际 base → 退化 snapshot;重订阅替换旧代际(同 connection 新 subscriptionId)", () => {
  648. const pub = new SessionsIndexPublisher("ws-1", "epoch-1", now);
  649. pub.ingestConversation(snap("a"), { createdAt: 1, lastActivityAt: 2 });
  650. const stale = pub.subscribe("conn-1", { logEpoch: "other-epoch", seq: 1 });
  651. expect(stale.mode).toBe("snapshot");
  652. expect(stale.frame?.payload.kind).toBe("snapshot");
  653. const replaced = pub.subscribe("conn-1");
  654. expect(replaced.subscriptionId).not.toBe(stale.subscriptionId);
  655. expect(pub.subscriptionIds()).toEqual([replaced.subscriptionId]);
  656. });
  657. });