event-reducer.test.ts 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031
  1. // ============================================================
  2. // Test imports
  3. // ============================================================
  4. import { beforeEach, describe, expect, it } from "vitest";
  5. import { EventReducer } from "../src/events/event-reducer.js";
  6. import { SessionEventType } from "../src/events/session.events.js";
  7. import type { SessionEvent } from "../src/events/session.events.js";
  8. import { createSessionEvent } from "../src/events/session.events.js";
  9. import { CompactTrigger } from "../src/compact/index.js";
  10. import { RewindScope, RewindStrategy } from "../src/rewind/index.js";
  11. import type {
  12. MessageId,
  13. PartId,
  14. SessionId,
  15. ToolCallId,
  16. TraceId,
  17. } from "../src/interfaces/shared.js";
  18. import type { SessionGoal, GoalStatus } from "../src/tools/target.js";
  19. // -----------------------------------------------
  20. // Event Reducer Tests
  21. // -----------------------------------------------
  22. describe("EventReducer", () => {
  23. const sessionId = "sess_123" as SessionId;
  24. let reducer: EventReducer;
  25. beforeEach(() => {
  26. reducer = new EventReducer();
  27. });
  28. describe("reduce", () => {
  29. it("should return initial state for empty events", () => {
  30. const projection = reducer.reduce([]);
  31. expect(projection.id).toBe("unknown");
  32. expect(projection.turnCount).toBe(0);
  33. expect(projection.status).toBe("idle");
  34. });
  35. it("should apply session_created event", () => {
  36. const events: SessionEvent[] = [
  37. createSessionEvent(SessionEventType.SessionCreated, sessionId, {
  38. mode: "build",
  39. contextWindow: 200000,
  40. }),
  41. ];
  42. const projection = reducer.reduce(events);
  43. expect(projection.id).toBe(sessionId);
  44. expect(projection.mode).toBe("build");
  45. expect(projection.contextWindow).toBe(200000);
  46. });
  47. it("should apply session_mode_changed event", () => {
  48. const events: SessionEvent[] = [
  49. createSessionEvent(SessionEventType.SessionCreated, sessionId, {
  50. mode: "build",
  51. contextWindow: 200000,
  52. }),
  53. createSessionEvent(SessionEventType.SessionModeChanged, sessionId, {
  54. mode: "plan",
  55. previousMode: "build",
  56. source: "tool",
  57. toolCallId: "tool_1" as ToolCallId,
  58. }),
  59. ];
  60. const projection = reducer.reduce(events);
  61. expect(projection.mode).toBe("plan");
  62. });
  63. it("should increment turn count on turn_started", () => {
  64. const events: SessionEvent[] = [
  65. createSessionEvent(SessionEventType.SessionCreated, sessionId, {
  66. mode: "build",
  67. contextWindow: 200000,
  68. }),
  69. createSessionEvent(
  70. SessionEventType.TurnStarted,
  71. sessionId,
  72. { turnNumber: 1, input: "Hello" },
  73. { turnId: "turn_1" as any },
  74. ),
  75. ];
  76. const projection = reducer.reduce(events);
  77. expect(projection.turnCount).toBe(1);
  78. expect(projection.status).toBe("running");
  79. });
  80. it("should set status to idle on turn_complete", () => {
  81. const events: SessionEvent[] = [
  82. createSessionEvent(SessionEventType.SessionCreated, sessionId, {
  83. mode: "build",
  84. contextWindow: 200000,
  85. }),
  86. createSessionEvent(
  87. SessionEventType.TurnStarted,
  88. sessionId,
  89. { turnNumber: 1, input: "Hello" },
  90. { turnId: "turn_1" as any },
  91. ),
  92. createSessionEvent(
  93. SessionEventType.TurnComplete,
  94. sessionId,
  95. {
  96. response: "Hi",
  97. tokenCount: 100,
  98. toolCallCount: 0,
  99. duration: 1000,
  100. resultType: "success",
  101. },
  102. { turnId: "turn_1" as any },
  103. ),
  104. ];
  105. const projection = reducer.reduce(events);
  106. expect(projection.status).toBe("idle");
  107. });
  108. it("should clear stale lastError when a new turn starts", () => {
  109. const events: SessionEvent[] = [
  110. createSessionEvent(SessionEventType.SessionCreated, sessionId, {
  111. mode: "build",
  112. contextWindow: 200000,
  113. }),
  114. createSessionEvent(
  115. SessionEventType.TurnStarted,
  116. sessionId,
  117. { turnNumber: 1, input: "Use GLM-5.2" },
  118. { turnId: "turn_1" as any },
  119. ),
  120. createSessionEvent(
  121. SessionEventType.TurnError,
  122. sessionId,
  123. {
  124. error: {
  125. type: "1220",
  126. message: "[1220][您无权访问glm-5.2。][trace-a]",
  127. },
  128. turnPhase: "model",
  129. },
  130. { turnId: "turn_1" as any },
  131. ),
  132. createSessionEvent(
  133. SessionEventType.TurnStarted,
  134. sessionId,
  135. { turnNumber: 2, input: "Continue with GLM-5.1" },
  136. { turnId: "turn_2" as any },
  137. ),
  138. ];
  139. const runningProjection = reducer.reduce(events);
  140. expect(runningProjection.status).toBe("running");
  141. expect(runningProjection.lastError).toBeUndefined();
  142. const completedProjection = reducer.reduce([
  143. ...events,
  144. createSessionEvent(
  145. SessionEventType.TurnComplete,
  146. sessionId,
  147. {
  148. response: "Done.",
  149. tokenCount: 100,
  150. toolCallCount: 0,
  151. duration: 1000,
  152. resultType: "success",
  153. },
  154. { turnId: "turn_2" as any },
  155. ),
  156. ]);
  157. expect(completedProjection.status).toBe("idle");
  158. expect(completedProjection.lastError).toBeUndefined();
  159. const nextFailedProjection = reducer.reduce([
  160. ...events,
  161. createSessionEvent(
  162. SessionEventType.TurnError,
  163. sessionId,
  164. {
  165. error: {
  166. type: "NEW_ERROR",
  167. message: "new turn failed",
  168. },
  169. turnPhase: "model",
  170. },
  171. { turnId: "turn_2" as any },
  172. ),
  173. ]);
  174. expect(nextFailedProjection.lastError).toEqual({
  175. type: "NEW_ERROR",
  176. message: "new turn failed",
  177. });
  178. });
  179. it("should preserve structured turn error code and detail in lastError", () => {
  180. const events: SessionEvent[] = [
  181. createSessionEvent(SessionEventType.SessionCreated, sessionId, {
  182. mode: "build",
  183. contextWindow: 200000,
  184. }),
  185. createSessionEvent(
  186. SessionEventType.TurnError,
  187. sessionId,
  188. {
  189. error: {
  190. type: "MODEL_ERROR",
  191. code: "provider_not_found",
  192. message: "Model provider is not configured: stale-provider",
  193. detail: "stale-provider/gpt-5.5",
  194. },
  195. turnPhase: "model",
  196. },
  197. { turnId: "turn_1" as any },
  198. ),
  199. ];
  200. const projection = reducer.reduce(events);
  201. expect(projection.lastError).toEqual({
  202. type: "MODEL_ERROR",
  203. code: "provider_not_found",
  204. message: "Model provider is not configured: stale-provider",
  205. detail: "stale-provider/gpt-5.5",
  206. });
  207. });
  208. it("should preserve structured turn error attribution in lastError", () => {
  209. const events: SessionEvent[] = [
  210. createSessionEvent(
  211. SessionEventType.TurnError,
  212. sessionId,
  213. {
  214. error: {
  215. type: "MODEL_ERROR",
  216. code: "model_request_failed",
  217. message: "[1301][Sensitive content rejected]",
  218. attribution: {
  219. source: "provider",
  220. reason: "unknown",
  221. providerId: "account:bigmodel-individual-coding-plan",
  222. providerErrorCode: "1301",
  223. },
  224. },
  225. turnPhase: "model",
  226. },
  227. { turnId: "turn_attribution" as any },
  228. ),
  229. ];
  230. const projection = reducer.reduce(events);
  231. expect(projection.lastError).toMatchObject({
  232. attribution: {
  233. source: "provider",
  234. reason: "unknown",
  235. providerId: "account:bigmodel-individual-coding-plan",
  236. providerErrorCode: "1301",
  237. },
  238. });
  239. });
  240. it("should track active context from the latest model request usage", () => {
  241. const events: SessionEvent[] = [
  242. createSessionEvent(SessionEventType.SessionCreated, sessionId, {
  243. mode: "build",
  244. contextWindow: 200000,
  245. }),
  246. createSessionEvent(SessionEventType.ModelComplete, sessionId, {
  247. content: "Need a tool.",
  248. stopReason: "tool-calls",
  249. usage: {
  250. inputTokens: 39951,
  251. outputTokens: 73,
  252. totalTokens: 40024,
  253. },
  254. }),
  255. createSessionEvent(SessionEventType.ModelComplete, sessionId, {
  256. content: "Done.",
  257. stopReason: "stop",
  258. usage: {
  259. inputTokens: 89299,
  260. outputTokens: 282,
  261. totalTokens: 89581,
  262. },
  263. }),
  264. createSessionEvent(
  265. SessionEventType.TurnComplete,
  266. sessionId,
  267. {
  268. response: "Done.",
  269. tokenCount: 316041,
  270. toolCallCount: 4,
  271. duration: 1000,
  272. resultType: "success",
  273. usage: {
  274. cacheReadTokens: 186832,
  275. cacheWriteTokens: 0,
  276. inputTokens: 316041,
  277. modelRequestCount: 5,
  278. outputTokens: 10687,
  279. reasoningTokens: 128,
  280. source: "provider",
  281. totalTokens: 326728,
  282. },
  283. },
  284. { turnId: "turn_1" as any },
  285. ),
  286. ];
  287. const projection = reducer.reduce(events);
  288. expect(projection.contextUsed).toBe(89581);
  289. });
  290. it("should not let sidecar model usage overwrite main session context", () => {
  291. const events: SessionEvent[] = [
  292. createSessionEvent(SessionEventType.SessionCreated, sessionId, {
  293. mode: "build",
  294. contextWindow: 1_000_000,
  295. }),
  296. createSessionEvent(SessionEventType.ModelComplete, sessionId, {
  297. content: "你好!我是 zcode-agent。",
  298. querySource: "main_turn",
  299. stopReason: "stop",
  300. usage: {
  301. inputTokens: 17_737,
  302. outputTokens: 41,
  303. totalTokens: 17_778,
  304. },
  305. }),
  306. createSessionEvent(SessionEventType.ModelComplete, sessionId, {
  307. content: "中文问候",
  308. querySource: "session_title",
  309. stopReason: "stop",
  310. usage: {
  311. inputTokens: 89,
  312. outputTokens: 84,
  313. totalTokens: 173,
  314. },
  315. }),
  316. createSessionEvent(SessionEventType.ModelComplete, sessionId, {
  317. content: "compact summary",
  318. querySource: "compact",
  319. stopReason: "stop",
  320. usage: {
  321. inputTokens: 512,
  322. outputTokens: 128,
  323. totalTokens: 640,
  324. },
  325. }),
  326. createSessionEvent(SessionEventType.ModelComplete, sessionId, {
  327. content: "subagent answer",
  328. querySource: "subagent",
  329. stopReason: "stop",
  330. usage: {
  331. inputTokens: 4_200,
  332. outputTokens: 300,
  333. totalTokens: 4_500,
  334. },
  335. }),
  336. createSessionEvent(SessionEventType.ModelComplete, sessionId, {
  337. content: "",
  338. stopReason: "tool_internal",
  339. usage: {
  340. inputTokens: 9_001,
  341. outputTokens: 12,
  342. totalTokens: 9_013,
  343. },
  344. }),
  345. ];
  346. const projection = reducer.reduce(events);
  347. expect(projection.contextUsed).toBe(17_778);
  348. });
  349. it("should project the current session goal from target_changed events", () => {
  350. const target = buildTarget(sessionId, "Ship target events", "active");
  351. const completedTarget = { ...target, status: "complete" as const };
  352. const events: SessionEvent[] = [
  353. createSessionEvent(SessionEventType.SessionCreated, sessionId, {
  354. mode: "build",
  355. contextWindow: 200000,
  356. }),
  357. createSessionEvent(SessionEventType.TargetChanged, sessionId, {
  358. action: "set",
  359. source: "command",
  360. target,
  361. }),
  362. createSessionEvent(SessionEventType.TargetChanged, sessionId, {
  363. action: "status_updated",
  364. previousTarget: target,
  365. source: "tool",
  366. target: completedTarget,
  367. }),
  368. createSessionEvent(SessionEventType.TargetChanged, sessionId, {
  369. action: "cleared",
  370. previousTarget: completedTarget,
  371. source: "command",
  372. target: null,
  373. }),
  374. ];
  375. const projection = reducer.reduce(events);
  376. expect(projection.target).toBeNull();
  377. expect(projection.updatedAt).toEqual(events.at(-1)?.timestamp);
  378. });
  379. it("should persist target completion verification timeline without duplicating completed summaries", () => {
  380. const target = buildTarget(sessionId, "实现 goal verify 横条", "active");
  381. const verification = {
  382. nextAction: "继续补 UI 回归。",
  383. passed: false,
  384. reason: "还缺交互验证。",
  385. };
  386. const events: SessionEvent[] = [
  387. createSessionEvent(SessionEventType.SessionCreated, sessionId, {
  388. mode: "build",
  389. contextWindow: 200000,
  390. }),
  391. createSessionEvent(SessionEventType.TargetChanged, sessionId, {
  392. action: "set",
  393. source: "command",
  394. target,
  395. }),
  396. createSessionEvent(SessionEventType.TargetCompletionVerification, sessionId, {
  397. status: "started",
  398. targetId: target.targetID,
  399. verificationId: "verify_1",
  400. }),
  401. createSessionEvent(SessionEventType.ModelComplete, sessionId, {
  402. content: JSON.stringify(verification),
  403. querySource: "target_completion_verification",
  404. stopReason: "stop",
  405. }),
  406. createSessionEvent(SessionEventType.TargetCompletionVerification, sessionId, {
  407. status: "completed",
  408. targetId: target.targetID,
  409. verification,
  410. verificationId: "verify_1",
  411. }),
  412. ];
  413. const projection = reducer.reduce(events);
  414. expect(projection.targetCompletionVerifications).toEqual([verification]);
  415. expect(projection.targetCompletionVerificationTimeline).toHaveLength(1);
  416. expect(projection.targetCompletionVerificationTimeline[0]).toMatchObject({
  417. targetId: target.targetID,
  418. status: "completed",
  419. verificationId: "verify_1",
  420. verification,
  421. goalIteration: 1,
  422. startedAt: events[2].timestamp,
  423. updatedAt: events[4].timestamp,
  424. });
  425. });
  426. it("should add failed closed target completion verification to the summary ledger", () => {
  427. const target = buildTarget(sessionId, "处理失败关闭校验", "active");
  428. const verification = {
  429. passed: false,
  430. reason: "Completion verifier request failed: network timeout",
  431. };
  432. const events: SessionEvent[] = [
  433. createSessionEvent(SessionEventType.SessionCreated, sessionId, {
  434. mode: "build",
  435. contextWindow: 200000,
  436. }),
  437. createSessionEvent(SessionEventType.TargetCompletionVerification, sessionId, {
  438. status: "started",
  439. targetId: target.targetID,
  440. verificationId: "verify_failed",
  441. }),
  442. createSessionEvent(SessionEventType.TargetCompletionVerification, sessionId, {
  443. status: "failed_closed",
  444. targetId: target.targetID,
  445. verification,
  446. verificationId: "verify_failed",
  447. }),
  448. ];
  449. const projection = reducer.reduce(events);
  450. expect(projection.targetCompletionVerifications).toEqual([verification]);
  451. expect(projection.targetCompletionVerificationTimeline[0]).toMatchObject({
  452. status: "failed_closed",
  453. verification,
  454. verificationId: "verify_failed",
  455. goalIteration: 1,
  456. });
  457. });
  458. it("should clear target completion verification timeline when a new target is set", () => {
  459. const target = buildTarget(sessionId, "旧目标", "active");
  460. const nextTarget = {
  461. ...buildTarget(sessionId, "新目标", "active"),
  462. targetID: "target_2",
  463. };
  464. const events: SessionEvent[] = [
  465. createSessionEvent(SessionEventType.SessionCreated, sessionId, {
  466. mode: "build",
  467. contextWindow: 200000,
  468. }),
  469. createSessionEvent(SessionEventType.TargetCompletionVerification, sessionId, {
  470. status: "started",
  471. targetId: target.targetID,
  472. verificationId: "verify_1",
  473. }),
  474. createSessionEvent(SessionEventType.TargetChanged, sessionId, {
  475. action: "set",
  476. previousTarget: target,
  477. source: "command",
  478. target: nextTarget,
  479. }),
  480. ];
  481. const projection = reducer.reduce(events);
  482. expect(projection.targetCompletionVerificationTimeline).toEqual([]);
  483. expect(projection.targetCompletionVerifications).toEqual([]);
  484. });
  485. it("should track pending permissions", () => {
  486. const events: SessionEvent[] = [
  487. createSessionEvent(SessionEventType.SessionCreated, sessionId, {
  488. mode: "build",
  489. contextWindow: 200000,
  490. }),
  491. createSessionEvent(SessionEventType.PermissionRequested, sessionId, {
  492. toolCallId: "tool_1" as any,
  493. toolName: "Bash",
  494. riskLevel: "high",
  495. reason: "Running shell command",
  496. input: {},
  497. suggestedPermissionUpdates: [
  498. {
  499. behavior: "allow",
  500. rules: [{ ruleContent: "pnpm run lint:*", toolName: "Bash" }],
  501. type: "addRules",
  502. },
  503. ],
  504. }),
  505. ];
  506. const projection = reducer.reduce(events);
  507. expect(projection.pendingPermissions).toHaveLength(1);
  508. expect(projection.pendingPermissions[0].toolName).toBe("Bash");
  509. expect(projection.pendingPermissions[0].suggestedPermissionUpdates).toEqual([
  510. {
  511. behavior: "allow",
  512. rules: [{ ruleContent: "pnpm run lint:*", toolName: "Bash" }],
  513. type: "addRules",
  514. },
  515. ]);
  516. });
  517. it("should carry the ask preview and option policy onto the pending permission", () => {
  518. // Both fields are re-picked field by field here, so a missed field silently drops
  519. // the confirmation preview for any session rebuilt from its event log.
  520. const display = {
  521. kind: "create_workflow" as const,
  522. ok: true,
  523. errorCount: 0,
  524. diagnostics: [],
  525. };
  526. const events: SessionEvent[] = [
  527. createSessionEvent(SessionEventType.SessionCreated, sessionId, {
  528. mode: "build",
  529. contextWindow: 200000,
  530. }),
  531. createSessionEvent(SessionEventType.PermissionRequested, sessionId, {
  532. toolCallId: "tool_1" as any,
  533. toolName: "CreateWorkflow",
  534. riskLevel: "low",
  535. reason: "createWorkflow.runConfirmation",
  536. input: { script: "return 1;" },
  537. display,
  538. optionsPolicy: "no-always-allow",
  539. }),
  540. ];
  541. const projection = reducer.reduce(events);
  542. expect(projection.pendingPermissions[0].display).toEqual(display);
  543. expect(projection.pendingPermissions[0].optionsPolicy).toBe("no-always-allow");
  544. });
  545. it("should remove pending permission on resolution", () => {
  546. const events: SessionEvent[] = [
  547. createSessionEvent(SessionEventType.SessionCreated, sessionId, {
  548. mode: "build",
  549. contextWindow: 200000,
  550. }),
  551. createSessionEvent(SessionEventType.PermissionRequested, sessionId, {
  552. toolCallId: "tool_1" as any,
  553. toolName: "Bash",
  554. riskLevel: "high",
  555. reason: "Running shell command",
  556. input: {},
  557. }),
  558. createSessionEvent(SessionEventType.PermissionResolved, sessionId, {
  559. toolCallId: "tool_1" as any,
  560. decision: "allow",
  561. }),
  562. ];
  563. const projection = reducer.reduce(events);
  564. expect(projection.pendingPermissions).toHaveLength(0);
  565. });
  566. it("should track pending steer inputs until drained or discarded", () => {
  567. const events: SessionEvent[] = [
  568. createSessionEvent(SessionEventType.SessionCreated, sessionId, {
  569. mode: "build",
  570. contextWindow: 200000,
  571. }),
  572. createSessionEvent(
  573. SessionEventType.TurnSteerQueued,
  574. sessionId,
  575. {
  576. pendingInputId: "pending_1",
  577. input: "queued message",
  578. inputPreview: "queued message",
  579. inputSize: 14,
  580. queueLength: 1,
  581. targetTurnId: "turn_1" as any,
  582. },
  583. { traceId: "trace_1" as TraceId, turnId: "turn_1" as any },
  584. ),
  585. createSessionEvent(
  586. SessionEventType.TurnSteerQueued,
  587. sessionId,
  588. {
  589. pendingInputId: "pending_2",
  590. input: "discard me",
  591. inputPreview: "discard me",
  592. inputSize: 10,
  593. queueLength: 2,
  594. targetTurnId: "turn_1" as any,
  595. },
  596. { traceId: "trace_1" as TraceId, turnId: "turn_1" as any },
  597. ),
  598. createSessionEvent(
  599. SessionEventType.TurnSteerDrained,
  600. sessionId,
  601. {
  602. injectedMessageIds: ["msg_1" as MessageId],
  603. pendingInputIds: ["pending_1"],
  604. targetTurnId: "turn_1" as any,
  605. },
  606. { traceId: "trace_1" as TraceId, turnId: "turn_1" as any },
  607. ),
  608. ];
  609. const afterDrain = reducer.reduce(events);
  610. expect(afterDrain.pendingSteerInputs).toHaveLength(1);
  611. expect(afterDrain.pendingSteerInputs[0]).toMatchObject({
  612. input: "discard me",
  613. pendingInputId: "pending_2",
  614. });
  615. const afterDiscard = reducer.reduce([
  616. ...events,
  617. createSessionEvent(
  618. SessionEventType.TurnSteerDiscarded,
  619. sessionId,
  620. {
  621. pendingInputIds: ["pending_2"],
  622. reason: "turn_cancelled",
  623. targetTurnId: "turn_1" as any,
  624. },
  625. { traceId: "trace_1" as TraceId, turnId: "turn_1" as any },
  626. ),
  627. ]);
  628. expect(afterDiscard.pendingSteerInputs).toHaveLength(0);
  629. });
  630. it("keeps queue edit in place and applies authoritative reorder positions", () => {
  631. const intent = (sourceCommandId: string, queueItemId: string, admissionSeq: number) => ({
  632. sourceCommandId,
  633. queueItemId,
  634. clientId: "mobile-client",
  635. kind: "sendText" as const,
  636. admissionSeq,
  637. admittedAt: admissionSeq,
  638. requestedDelivery: "queue" as const,
  639. admittedDelivery: "queue" as const,
  640. queuePosition: admissionSeq - 1,
  641. });
  642. const queued = (pendingInputId: string, input: string, admissionSeq: number) =>
  643. createSessionEvent(
  644. SessionEventType.TurnSteerQueued,
  645. sessionId,
  646. {
  647. pendingInputId,
  648. input,
  649. inputPreview: input,
  650. inputSize: input.length,
  651. queueLength: 2,
  652. targetTurnId: "turn_1" as any,
  653. intent: intent(`command-${pendingInputId}`, pendingInputId, admissionSeq),
  654. },
  655. { traceId: "trace_1" as TraceId, turnId: "turn_1" as any },
  656. );
  657. const first = queued("q1", "第一条", 1);
  658. const events: SessionEvent[] = [
  659. createSessionEvent(SessionEventType.SessionCreated, sessionId, {
  660. mode: "build",
  661. contextWindow: 200000,
  662. }),
  663. first,
  664. queued("q2", "第二条", 2),
  665. queued("q1", "第一条改", 1),
  666. createSessionEvent(
  667. SessionEventType.TurnSteerReordered,
  668. sessionId,
  669. {
  670. orderedPendingInputIds: ["q2", "q1"],
  671. targetTurnId: "turn_1" as any,
  672. },
  673. { traceId: "trace_1" as TraceId, turnId: "turn_1" as any },
  674. ),
  675. ];
  676. const projection = reducer.reduce(events);
  677. expect(projection.pendingSteerInputs.map((item) => item.pendingInputId)).toEqual([
  678. "q2",
  679. "q1",
  680. ]);
  681. expect(projection.pendingSteerInputs[1]).toMatchObject({
  682. input: "第一条改",
  683. queuedAt: first.timestamp,
  684. intent: {
  685. sourceCommandId: "command-q1",
  686. queueItemId: "q1",
  687. clientId: "mobile-client",
  688. queuePosition: 1,
  689. },
  690. });
  691. });
  692. it("should track active tool calls", () => {
  693. const events: SessionEvent[] = [
  694. createSessionEvent(SessionEventType.SessionCreated, sessionId, {
  695. mode: "build",
  696. contextWindow: 200000,
  697. }),
  698. createSessionEvent(SessionEventType.ToolCallScheduled, sessionId, {
  699. toolCallId: "tool_1" as any,
  700. toolName: "Glob",
  701. input: {},
  702. schedule: { parallelGroups: [], executionOrder: [] },
  703. }),
  704. ];
  705. const projection = reducer.reduce(events);
  706. expect(projection.activeToolCalls).toHaveLength(1);
  707. expect(projection.activeToolCalls[0].status).toBe("pending");
  708. });
  709. it("should update tool status on result", () => {
  710. const events: SessionEvent[] = [
  711. createSessionEvent(SessionEventType.SessionCreated, sessionId, {
  712. mode: "build",
  713. contextWindow: 200000,
  714. }),
  715. createSessionEvent(SessionEventType.ToolCallScheduled, sessionId, {
  716. toolCallId: "tool_1" as any,
  717. toolName: "Glob",
  718. input: {},
  719. schedule: { parallelGroups: [], executionOrder: [] },
  720. }),
  721. createSessionEvent(SessionEventType.ToolCallResult, sessionId, {
  722. toolCallId: "tool_1" as any,
  723. result: { success: true, content: "file1.ts\nfile2.ts" },
  724. duration: 50,
  725. }),
  726. ];
  727. const projection = reducer.reduce(events);
  728. const tool = projection.activeToolCalls.find((tc) => tc.toolCallId === "tool_1");
  729. expect(tool?.status).toBe("completed");
  730. });
  731. it("should track streaming tool ledger and recovery anchor", () => {
  732. const assistantMessageId = "msg_assistant" as MessageId;
  733. const toolCallId = "tool_1" as ToolCallId;
  734. const resultPartId = "part_1" as PartId;
  735. const committedAt = new Date("2026-05-11T00:00:00.000Z");
  736. const events: SessionEvent[] = [
  737. createSessionEvent(SessionEventType.SessionCreated, sessionId, {
  738. mode: "build",
  739. contextWindow: 200000,
  740. }),
  741. createSessionEvent(SessionEventType.StreamingToolLedgerUpdated, sessionId, {
  742. attemptId: "attempt_1",
  743. assistantMessageId,
  744. toolCallId,
  745. toolName: "Read",
  746. status: "tool_call_closed",
  747. executionTiming: "end_of_stream",
  748. input: { filePath: "README.md" },
  749. readOnly: true,
  750. sideEffectScope: "none",
  751. }),
  752. createSessionEvent(SessionEventType.StreamRecoveryAnchorCreated, sessionId, {
  753. anchorId: "anchor_1",
  754. attemptId: "attempt_1",
  755. kind: "tool_result",
  756. assistantMessageId,
  757. toolCallId,
  758. toolName: "Read",
  759. resultPartId,
  760. committedToolCallIds: [toolCallId],
  761. committedAt,
  762. }),
  763. createSessionEvent(SessionEventType.StreamingToolLedgerUpdated, sessionId, {
  764. attemptId: "attempt_1",
  765. assistantMessageId,
  766. toolCallId,
  767. toolName: "Read",
  768. status: "tool_result_committed",
  769. executionTiming: "end_of_stream",
  770. resultPartId,
  771. recoveryAnchorId: "anchor_1",
  772. committedAt,
  773. }),
  774. ];
  775. const projection = reducer.reduce(events);
  776. expect(projection.streamingToolLedger).toHaveLength(1);
  777. expect(projection.streamingToolLedger[0]).toMatchObject({
  778. attemptId: "attempt_1",
  779. status: "tool_result_committed",
  780. toolCallId,
  781. resultPartId,
  782. recoveryAnchorId: "anchor_1",
  783. });
  784. expect(projection.lastStreamRecoveryAnchor).toMatchObject({
  785. anchorId: "anchor_1",
  786. kind: "tool_result",
  787. committedToolCallIds: [toolCallId],
  788. });
  789. });
  790. it("should track background task lifecycle", () => {
  791. const events: SessionEvent[] = [
  792. createSessionEvent(SessionEventType.SessionCreated, sessionId, {
  793. mode: "build",
  794. contextWindow: 200000,
  795. }),
  796. createSessionEvent(SessionEventType.BackgroundTaskStarted, sessionId, {
  797. cancellable: true,
  798. taskId: "exec_1",
  799. toolCallId: "tool_1",
  800. toolName: "Bash",
  801. taskKind: "bash",
  802. command: "npm run dev",
  803. outputTail: "booting",
  804. stdoutBytes: 7,
  805. stdoutTail: "booting",
  806. terminalId: "exec_1",
  807. status: "running",
  808. }),
  809. createSessionEvent(SessionEventType.BackgroundTaskCompleted, sessionId, {
  810. taskId: "exec_1",
  811. status: "completed",
  812. outputPath: "/tmp/exec_1.log",
  813. outputBytes: 12,
  814. }),
  815. ];
  816. const projection = reducer.reduce(events);
  817. expect(projection.backgroundTasks).toHaveLength(1);
  818. expect(projection.backgroundTasks[0]).toMatchObject({
  819. cancellable: true,
  820. command: "npm run dev",
  821. taskKind: "bash",
  822. outputBytes: 12,
  823. outputPath: "/tmp/exec_1.log",
  824. outputTail: "booting",
  825. status: "completed",
  826. stdoutBytes: 7,
  827. stdoutTail: "booting",
  828. taskId: "exec_1",
  829. terminalId: "exec_1",
  830. });
  831. });
  832. it("should preserve background subagent child session identity", () => {
  833. const events: SessionEvent[] = [
  834. createSessionEvent(SessionEventType.SessionCreated, sessionId, {
  835. mode: "build",
  836. contextWindow: 200000,
  837. }),
  838. createSessionEvent(SessionEventType.BackgroundTaskStarted, sessionId, {
  839. taskId: "agent_1",
  840. taskKind: "subagent",
  841. childSessionId: "sess_child_1",
  842. status: "running",
  843. }),
  844. createSessionEvent(SessionEventType.BackgroundTaskCompleted, sessionId, {
  845. taskId: "agent_1",
  846. status: "completed",
  847. }),
  848. ];
  849. const projection = reducer.reduce(events);
  850. expect(projection.backgroundTasks[0]).toMatchObject({
  851. childSessionId: "sess_child_1",
  852. status: "completed",
  853. taskId: "agent_1",
  854. taskKind: "subagent",
  855. });
  856. });
  857. it("should track compact boundary projection", () => {
  858. const events: SessionEvent[] = [
  859. createSessionEvent(SessionEventType.SessionCreated, sessionId, {
  860. mode: "build",
  861. contextWindow: 200000,
  862. }),
  863. createSessionEvent(SessionEventType.CompactBoundary, sessionId, {
  864. boundaryId: "compact_1",
  865. trigger: CompactTrigger.Auto,
  866. summarySource: "model",
  867. preCompactTokenCount: 180000,
  868. truePostCompactTokenCount: 24000,
  869. autoCompactThreshold: 167000,
  870. willRetriggerNextTurn: false,
  871. summarizedMessageCount: 24,
  872. keptMessageCount: 3,
  873. lastSummarizedMessageId: "msg_old_tail" as MessageId,
  874. summaryMessageIds: ["msg_summary" as MessageId],
  875. traceId: "trace_1" as TraceId,
  876. }),
  877. ];
  878. const projection = reducer.reduce(events);
  879. expect(projection.contextUsed).toBe(24000);
  880. expect(projection.lastCompact).toMatchObject({
  881. boundaryId: "compact_1",
  882. trigger: "auto",
  883. preCompactTokenCount: 180000,
  884. truePostCompactTokenCount: 24000,
  885. summarizedMessageCount: 24,
  886. keptMessageCount: 3,
  887. willRetriggerNextTurn: false,
  888. });
  889. });
  890. it("should track checkpoint and rewind projection", () => {
  891. const events: SessionEvent[] = [
  892. createSessionEvent(SessionEventType.SessionCreated, sessionId, {
  893. mode: "build",
  894. contextWindow: 200000,
  895. }),
  896. createSessionEvent(SessionEventType.CheckpointCreated, sessionId, {
  897. checkpointId: "checkpoint_1",
  898. messageId: "msg_1" as MessageId,
  899. scope: RewindScope.Workspace,
  900. snapshotRef: "artifact://snapshot_1",
  901. compactBoundaryId: "compact_1",
  902. coveredByCompact: true,
  903. fileCount: 2,
  904. }),
  905. createSessionEvent(SessionEventType.RewindTriggered, sessionId, {
  906. rewindId: "rewind_1",
  907. scope: RewindScope.Workspace,
  908. strategy: RewindStrategy.FileOnly,
  909. targetMessageId: "msg_1" as MessageId,
  910. targetCheckpointId: "checkpoint_1",
  911. compactBoundaryId: "compact_1",
  912. restoredSnapshotRef: "artifact://snapshot_1",
  913. reason: "target_covered_by_compact_file_only_available",
  914. }),
  915. ];
  916. const projection = reducer.reduce(events);
  917. expect(projection.lastCheckpoint).toMatchObject({
  918. checkpointId: "checkpoint_1",
  919. compactBoundaryId: "compact_1",
  920. coveredByCompact: true,
  921. fileCount: 2,
  922. messageId: "msg_1",
  923. scope: "workspace",
  924. snapshotRef: "artifact://snapshot_1",
  925. });
  926. expect(projection.lastRewind).toMatchObject({
  927. compactBoundaryId: "compact_1",
  928. reason: "target_covered_by_compact_file_only_available",
  929. rewindId: "rewind_1",
  930. scope: "workspace",
  931. strategy: "file_only",
  932. targetCheckpointId: "checkpoint_1",
  933. targetMessageId: "msg_1",
  934. });
  935. });
  936. });
  937. describe("apply", () => {
  938. it("should apply a single event to projection", () => {
  939. let projection = reducer.reduce([]);
  940. const sessionCreatedEvent = createSessionEvent(SessionEventType.SessionCreated, sessionId, {
  941. mode: "build",
  942. contextWindow: 200000,
  943. });
  944. projection = reducer.apply(projection, sessionCreatedEvent);
  945. expect(projection.id).toBe(sessionId);
  946. });
  947. });
  948. });
  949. function buildTarget(sessionId: SessionId, objective: string, status: GoalStatus): SessionGoal {
  950. return {
  951. objective,
  952. sessionID: sessionId,
  953. status,
  954. summaryTitle: null,
  955. targetID: "target_1",
  956. time: {
  957. created: 1,
  958. updated: 1,
  959. },
  960. timeUsedSeconds: 0,
  961. tokenBudget: null,
  962. tokensUsed: 0,
  963. };
  964. }