queue-store.spec.ts 10 KB

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