queue-store.spec.ts 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. /**
  2. * Queue mirror semantics (web input-triggers queue cut 1): session/queued
  3. * intake, host-rule retirement (message turn/start claims oldest non-steering;
  4. * steering/message drains by source), leave-running sweep, reconnect reset,
  5. * pre-instantiation buffering, and snapshot reference stability.
  6. */
  7. import { describe, expect, it } from 'vitest'
  8. import type { ContentBlock } from '@deepseek-ai/dsh-llm/types'
  9. import type { MuxFrame, RpcId, SessionId } from '@deepseek-ai/dsh-client-connection/client'
  10. import { Session } from '../src/client/sessions/session.ts'
  11. import { SessionManager } from '../src/client/sessions/manager.ts'
  12. import { FakeApiClient } from './fake-api.ts'
  13. import { ev } from './event-script.ts'
  14. const SID = 'fk-q1' as SessionId
  15. const text = (t: string): ContentBlock[] => [{ type: 'text', text: t }]
  16. const rid = (id: string): RpcId => id as RpcId
  17. /** session/queued frame with the wire-sourced rpcId key (the host prompt path). */
  18. function queuedFrame(body: string, rpcId: string): MuxFrame {
  19. return {
  20. type: 'session/queued', sessionId: SID, content: text(body),
  21. source: { kind: 'user', rpcId: rid(rpcId) } as never,
  22. }
  23. }
  24. function makeSession(): Session {
  25. return new Session(SID, new FakeApiClient())
  26. }
  27. describe('queue intake', () => {
  28. it('lands a queued frame as a row keyed by the source rpcId with a flat preview', () => {
  29. const session = makeSession()
  30. session.handleMuxEnvelope(rid('env-1'), queuedFrame('第一条 排队\n消息', 'p-1'))
  31. const queue = session.getSnapshot().queue
  32. expect(queue).toEqual([{ key: 'p-1', preview: '第一条 排队 消息' }])
  33. })
  34. it('falls back to the envelope rpcId when the source carries none, and tags non-text blocks', () => {
  35. const session = makeSession()
  36. session.handleMuxEnvelope(rid('env-2'), {
  37. type: 'session/queued', sessionId: SID,
  38. content: [{ type: 'text', text: 'hi' }, { type: 'image', data: 'x' } as never],
  39. source: { kind: 'plugin', plugin: 'loop' },
  40. })
  41. expect(session.getSnapshot().queue).toEqual([{ key: 'f:env-2', preview: 'hi [image]' }])
  42. })
  43. it('caps the preview at 200 code points with an ellipsis', () => {
  44. const session = makeSession()
  45. session.handleMuxEnvelope(rid('env-3'), queuedFrame('长'.repeat(201), 'p-cap'))
  46. const preview = session.getSnapshot().queue[0]?.preview ?? ''
  47. expect(Array.from(preview)).toHaveLength(201) // 200 + …
  48. expect(preview.endsWith('…')).toBe(true)
  49. })
  50. it('keeps the queue array reference stable across unrelated snapshot swaps', () => {
  51. const session = makeSession()
  52. session.handleMuxEnvelope(rid('env-4'), queuedFrame('稳定', 'p-s'))
  53. const before = session.getSnapshot().queue
  54. session.handleAgentError('unrelated') // dirties the snapshot without touching the queue
  55. expect(session.getSnapshot().queue).toBe(before)
  56. })
  57. })
  58. describe('queue retirement (host queuedMirror rules)', () => {
  59. it('a message-triggered turn/start claims the oldest non-steering row', () => {
  60. const session = makeSession()
  61. session.handleMuxEnvelope(rid('e1'), queuedFrame('先', 'p-1'))
  62. session.handleMuxEnvelope(rid('e2'), queuedFrame('后', 'p-2'))
  63. session.handleMuxEnvelope(rid('e3'), { type: 'session/event', sessionId: SID, event: ev.turnStart(0, 0) })
  64. expect(session.getSnapshot().queue.map(r => r.key)).toEqual(['p-2'])
  65. })
  66. it('an injection-triggered turn/start claims nothing', () => {
  67. const session = makeSession()
  68. session.handleMuxEnvelope(rid('e1'), queuedFrame('留', 'p-1'))
  69. const injection = {
  70. ...ev.turnStart(0, 0),
  71. data: { turn: 0, trigger: { kind: 'injection', source: { kind: 'plugin', plugin: 'x' } } },
  72. } as never
  73. session.handleMuxEnvelope(rid('e2'), { type: 'session/event', sessionId: SID, event: injection })
  74. expect(session.getSnapshot().queue).toHaveLength(1)
  75. })
  76. it('steering/message drains the source-matched steering row only', () => {
  77. const session = makeSession()
  78. session.handleMuxEnvelope(rid('e1'), queuedFrame('普通', 'p-1')) // idle → non-steering
  79. // Injection-triggered turn/start opens the turn without claiming a row, so
  80. // the next queued frame is derived steering (arrived mid-turn).
  81. const injection = {
  82. ...ev.turnStart(0, 0),
  83. data: { turn: 0, trigger: { kind: 'injection', source: { kind: 'plugin', plugin: 'x' } } },
  84. } as never
  85. session.handleMuxEnvelope(rid('e2'), { type: 'session/event', sessionId: SID, event: injection })
  86. session.handleMuxEnvelope(rid('e3'), queuedFrame('插话', 'p-2')) // turn open → steering
  87. // Loop-authored steering (different source) must not consume the user entry.
  88. const foreignSteering = {
  89. seq: 0, time: 1,
  90. type: 'steering/message', surfaceOp: 'append',
  91. data: { turn: 0, content: text('loop'), source: { kind: 'plugin', plugin: 'loop' } },
  92. } as never
  93. session.handleMuxEnvelope(rid('e4'), { type: 'session/event', sessionId: SID, event: foreignSteering })
  94. expect(session.getSnapshot().queue).toHaveLength(2)
  95. const matchedSteering = {
  96. seq: 1, time: 2,
  97. type: 'steering/message', surfaceOp: 'append',
  98. data: { turn: 0, content: text('插话'), source: { kind: 'user', rpcId: rid('p-2') } },
  99. } as never
  100. session.handleMuxEnvelope(rid('e5'), { type: 'session/event', sessionId: SID, event: matchedSteering })
  101. expect(session.getSnapshot().queue.map(r => r.key)).toEqual(['p-1'])
  102. })
  103. it('a leave-running flip sweeps the whole mirror (cancel/terminal-drop cover)', () => {
  104. const session = makeSession()
  105. session.handleRunning(true)
  106. session.handleMuxEnvelope(rid('e1'), queuedFrame('一', 'p-1'))
  107. session.handleMuxEnvelope(rid('e2'), queuedFrame('二', 'p-2'))
  108. session.handleRunning(false)
  109. expect(session.getSnapshot().queue).toEqual([])
  110. })
  111. it('a stale not-running relay on an idle session still sweeps replayed rows', () => {
  112. const session = makeSession()
  113. session.handleMuxEnvelope(rid('e1'), queuedFrame('孤儿', 'p-1'))
  114. session.handleRunning(false) // running already false: equality path must not skip the sweep
  115. expect(session.getSnapshot().queue).toEqual([])
  116. })
  117. })
  118. describe('queue reconnect semantics', () => {
  119. it('session/subscribed re-baselines the mirror: stale rows drop, the following snapshot lands fresh', () => {
  120. const session = makeSession()
  121. session.handleMuxEnvelope(rid('e1'), queuedFrame('旧连接', 'p-old'))
  122. // New mux generation: subscribed arrives first on the same stream...
  123. session.handleMuxEnvelope(rid('e2'), { type: 'session/subscribed', sessionId: SID, lastSeq: 10 })
  124. expect(session.getSnapshot().queue).toEqual([])
  125. // ...then the queue snapshot replays the live inbox.
  126. session.handleMuxEnvelope(rid('e3'), queuedFrame('新基线', 'p-new'))
  127. expect(session.getSnapshot().queue.map(r => r.key)).toEqual(['p-new'])
  128. })
  129. it('resync must NOT clear the mirror (regression: onConnected races the mux baseline)', async () => {
  130. const session = makeSession()
  131. // Reconnect ordering that broke: mux opened first and already delivered
  132. // the fresh generation's baseline; host stream (and with it onConnected →
  133. // resync) lands after. The host never resends — clearing here left the
  134. // dock empty until the next enqueue.
  135. session.handleMuxEnvelope(rid('e1'), { type: 'session/subscribed', sessionId: SID, lastSeq: 5 })
  136. session.handleMuxEnvelope(rid('e2'), queuedFrame('新基线', 'p-fresh'))
  137. await session.resync()
  138. expect(session.getSnapshot().queue.map(r => r.key)).toEqual(['p-fresh'])
  139. })
  140. })
  141. describe('manager buffering of queued frames', () => {
  142. it('buffers session/queued for uninstantiated sessions and replays before the running sync', () => {
  143. const api = new FakeApiClient()
  144. const manager = new SessionManager(api)
  145. manager.handleMuxEnvelope({ rpcId: rid('b1'), payload: queuedFrame('预热', 'p-b1') })
  146. // Instantiation replays the buffer; no summary exists, so no running sweep runs.
  147. const session = manager.get(SID)
  148. expect(session.getSnapshot().queue.map(r => r.key)).toEqual(['p-b1'])
  149. // The buffer is consumed: a second get must not double-replay.
  150. expect(manager.get(SID).getSnapshot().queue).toHaveLength(1)
  151. })
  152. it('a not-running list summary sweeps replayed rows at instantiation', async () => {
  153. const api = new FakeApiClient()
  154. api.onList = () => Promise.resolve(ok([{ sessionId: SID, updatedAt: 1, running: false }]))
  155. const manager = new SessionManager(api)
  156. await manager.refreshList()
  157. manager.handleMuxEnvelope({ rpcId: rid('b2'), payload: queuedFrame('该扫掉', 'p-b2') })
  158. expect(manager.get(SID).getSnapshot().queue).toEqual([])
  159. })
  160. it('subscribed re-baselines the uninstantiated buffer: stale queued frames drop, non-queue frames survive (regression: reconnect duplication)', () => {
  161. const api = new FakeApiClient()
  162. const manager = new SessionManager(api)
  163. // Generation 1 baseline lands while the session is uninstantiated, along
  164. // with a pending approval (never re-derivable from history).
  165. manager.handleMuxEnvelope({ rpcId: rid('g1a'), payload: queuedFrame('第一代', 'p-g1') })
  166. manager.handleMuxEnvelope({
  167. rpcId: rid('g1b'),
  168. payload: { type: 'approval/requested', sessionId: SID, approvalId: 'ap-1' as never, toolName: 'bash' },
  169. })
  170. // Reconnect: generation 2 replays subscribed + the SAME live queue entry.
  171. manager.handleMuxEnvelope({ rpcId: rid('g2a'), payload: { type: 'session/subscribed', sessionId: SID, lastSeq: 3 } })
  172. manager.handleMuxEnvelope({ rpcId: rid('g2b'), payload: queuedFrame('第一代', 'p-g1') })
  173. const snapshot = manager.get(SID).getSnapshot()
  174. // One queue row (no duplicate batch); the approval survived the re-baseline.
  175. expect(snapshot.queue.map(r => r.key)).toEqual(['p-g1'])
  176. expect(snapshot.pending.map(p => p.kind)).toEqual(['approval'])
  177. })
  178. })
  179. /** ok wrapper with a typed items payload (the shared helper pins value to never[]). */
  180. function ok(items: { sessionId: SessionId; updatedAt: number; running: boolean }[]) {
  181. return { rpcId: rid(`ok-${items.length}`), result: { ok: true as const, value: { items: items as never[] } } }
  182. }