queue-store.spec.ts 11 KB

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