queue-store.spec.ts 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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, steering,
  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' }, steering: false,
  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'))
  79. session.handleMuxEnvelope(rid('e2'), queuedFrame('插话', 'p-2', true))
  80. // Loop-authored steering (different source) must not consume the user entry.
  81. const foreignSteering = {
  82. seq: 0, time: 1,
  83. type: 'steering/message', surfaceOp: 'append',
  84. data: { turn: 0, content: text('loop'), source: { kind: 'plugin', plugin: 'loop' } },
  85. } as never
  86. session.handleMuxEnvelope(rid('e3'), { type: 'session/event', sessionId: SID, event: foreignSteering })
  87. expect(session.getSnapshot().queue).toHaveLength(2)
  88. const matchedSteering = {
  89. seq: 1, time: 2,
  90. type: 'steering/message', surfaceOp: 'append',
  91. data: { turn: 0, content: text('插话'), source: { kind: 'user', rpcId: rid('p-2') } },
  92. } as never
  93. session.handleMuxEnvelope(rid('e4'), { type: 'session/event', sessionId: SID, event: matchedSteering })
  94. expect(session.getSnapshot().queue.map(r => r.key)).toEqual(['p-1'])
  95. })
  96. it('a leave-running flip sweeps the whole mirror (cancel/terminal-drop cover)', () => {
  97. const session = makeSession()
  98. session.handleRunning(true)
  99. session.handleMuxEnvelope(rid('e1'), queuedFrame('一', 'p-1'))
  100. session.handleMuxEnvelope(rid('e2'), queuedFrame('二', 'p-2', true))
  101. session.handleRunning(false)
  102. expect(session.getSnapshot().queue).toEqual([])
  103. })
  104. it('a stale not-running relay on an idle session still sweeps replayed rows', () => {
  105. const session = makeSession()
  106. session.handleMuxEnvelope(rid('e1'), queuedFrame('孤儿', 'p-1'))
  107. session.handleRunning(false) // running already false: equality path must not skip the sweep
  108. expect(session.getSnapshot().queue).toEqual([])
  109. })
  110. })
  111. describe('queue reconnect semantics', () => {
  112. it('session/subscribed re-baselines the mirror: stale rows drop, the following snapshot lands fresh', () => {
  113. const session = makeSession()
  114. session.handleMuxEnvelope(rid('e1'), queuedFrame('旧连接', 'p-old'))
  115. // New mux generation: subscribed arrives first on the same stream...
  116. session.handleMuxEnvelope(rid('e2'), { type: 'session/subscribed', sessionId: SID, lastSeq: 10 })
  117. expect(session.getSnapshot().queue).toEqual([])
  118. // ...then the queue snapshot replays the live inbox.
  119. session.handleMuxEnvelope(rid('e3'), queuedFrame('新基线', 'p-new'))
  120. expect(session.getSnapshot().queue.map(r => r.key)).toEqual(['p-new'])
  121. })
  122. it('resync must NOT clear the mirror (regression: onConnected races the mux baseline)', async () => {
  123. const session = makeSession()
  124. // Reconnect ordering that broke: mux opened first and already delivered
  125. // the fresh generation's baseline; host stream (and with it onConnected →
  126. // resync) lands after. The host never resends — clearing here left the
  127. // dock empty until the next enqueue.
  128. session.handleMuxEnvelope(rid('e1'), { type: 'session/subscribed', sessionId: SID, lastSeq: 5 })
  129. session.handleMuxEnvelope(rid('e2'), queuedFrame('新基线', 'p-fresh'))
  130. await session.resync()
  131. expect(session.getSnapshot().queue.map(r => r.key)).toEqual(['p-fresh'])
  132. })
  133. })
  134. describe('manager buffering of queued frames', () => {
  135. it('buffers session/queued for uninstantiated sessions and replays before the running sync', () => {
  136. const api = new FakeApiClient()
  137. const manager = new SessionManager(api)
  138. manager.handleMuxEnvelope({ rpcId: rid('b1'), payload: queuedFrame('预热', 'p-b1') })
  139. // Instantiation replays the buffer; no summary exists, so no running sweep runs.
  140. const session = manager.get(SID)
  141. expect(session.getSnapshot().queue.map(r => r.key)).toEqual(['p-b1'])
  142. // The buffer is consumed: a second get must not double-replay.
  143. expect(manager.get(SID).getSnapshot().queue).toHaveLength(1)
  144. })
  145. it('a not-running list summary sweeps replayed rows at instantiation', async () => {
  146. const api = new FakeApiClient()
  147. api.onList = () => Promise.resolve(ok([{ sessionId: SID, updatedAt: 1, running: false }]))
  148. const manager = new SessionManager(api)
  149. await manager.refreshList()
  150. manager.handleMuxEnvelope({ rpcId: rid('b2'), payload: queuedFrame('该扫掉', 'p-b2') })
  151. expect(manager.get(SID).getSnapshot().queue).toEqual([])
  152. })
  153. it('subscribed re-baselines the uninstantiated buffer: stale queued frames drop, non-queue frames survive (regression: reconnect duplication)', () => {
  154. const api = new FakeApiClient()
  155. const manager = new SessionManager(api)
  156. // Generation 1 baseline lands while the session is uninstantiated, along
  157. // with a pending approval (never re-derivable from history).
  158. manager.handleMuxEnvelope({ rpcId: rid('g1a'), payload: queuedFrame('第一代', 'p-g1') })
  159. manager.handleMuxEnvelope({
  160. rpcId: rid('g1b'),
  161. payload: { type: 'approval/requested', sessionId: SID, approvalId: 'ap-1' as never, toolName: 'bash' },
  162. })
  163. // Reconnect: generation 2 replays subscribed + the SAME live queue entry.
  164. manager.handleMuxEnvelope({ rpcId: rid('g2a'), payload: { type: 'session/subscribed', sessionId: SID, lastSeq: 3 } })
  165. manager.handleMuxEnvelope({ rpcId: rid('g2b'), payload: queuedFrame('第一代', 'p-g1') })
  166. const snapshot = manager.get(SID).getSnapshot()
  167. // One queue row (no duplicate batch); the approval survived the re-baseline.
  168. expect(snapshot.queue.map(r => r.key)).toEqual(['p-g1'])
  169. expect(snapshot.pending.map(p => p.kind)).toEqual(['approval'])
  170. })
  171. })
  172. /** ok wrapper with a typed items payload (the shared helper pins value to never[]). */
  173. function ok(items: { sessionId: SessionId; updatedAt: number; running: boolean }[]) {
  174. return { rpcId: rid(`ok-${items.length}`), result: { ok: true as const, value: { items: items as never[] } } }
  175. }