session-pending-submissions.client.spec.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. /** Local submission echoes: synchronous insertion, observed/failed retirement, and settlement callbacks. */
  2. import { afterEach, describe, expect, it, vi } from 'vitest'
  3. import { createUserMessage } from '@deepseek-ai/dsh-llm'
  4. import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment'
  5. import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session/types'
  6. import { RemoteError } from '@deepseek-ai/dsh-typert-protocol'
  7. import { Session } from '../src/client/sessions/session.ts'
  8. import type { PendingSubmissionRetirement } from '../src/client/contract/session.ts'
  9. import type { SessionQueuedItem, SessionRequestId } from '../src/types.ts'
  10. import { FakeApiClient, err, fakeRemote, ok } from './fake-api.client.ts'
  11. import { historyValue } from './event-script.client.ts'
  12. const SID = 'fk-s1' as SessionId
  13. afterEach(() => {
  14. vi.unstubAllGlobals()
  15. })
  16. function makeSession(api = new FakeApiClient()): { api: FakeApiClient; session: Session } {
  17. return { api, session: new Session(SID, fakeRemote(api)) }
  18. }
  19. function imageRef(id: string): ImageAttachmentRef {
  20. return {
  21. attachmentId: id,
  22. mediaType: 'image/png',
  23. bytes: 1,
  24. width: 2,
  25. height: 2,
  26. } as unknown as ImageAttachmentRef
  27. }
  28. /** A durable browser-prompt user/message whose source echoes `rpcId`. */
  29. function promptEvent(seq: number, rpcId: SessionRequestId, refs: readonly ImageAttachmentRef[] = []): SessionEvent {
  30. return {
  31. seq,
  32. time: 1_700_000_000_000 + seq,
  33. type: 'user/message',
  34. surfaceOp: 'append',
  35. data: createUserMessage({
  36. content: [
  37. ...refs.map(attachment => ({ type: 'image' as const, attachment })),
  38. { type: 'text' as const, text: '发送' },
  39. ],
  40. source: { kind: 'user', rpcId },
  41. }),
  42. } as unknown as SessionEvent
  43. }
  44. function queuedItem(rpcId: SessionRequestId, refs: readonly ImageAttachmentRef[] = []): SessionQueuedItem {
  45. return {
  46. id: 'm-queued' as SessionQueuedItem['id'],
  47. placement: 'queued',
  48. rpcId,
  49. message: {
  50. id: 'm-queued' as SessionQueuedItem['id'],
  51. content: refs.map(attachment => ({ type: 'image', attachment })) as unknown as SessionQueuedItem['message']['content'],
  52. },
  53. }
  54. }
  55. /** Let the frame-delayed retirement (setTimeout fallback in this node environment) run. */
  56. function settleFrames(): Promise<void> {
  57. return new Promise(resolve => setTimeout(resolve, 0))
  58. }
  59. describe('beginSubmission', () => {
  60. it('inserts the echo synchronously and flips the engaging edge before any prompt call', () => {
  61. const { session } = makeSession()
  62. expect(session.getSnapshot()).toMatchObject({ pendingSubmissions: [], promptAttempted: false })
  63. const handle = session.beginSubmission({
  64. text: '你好',
  65. images: [{ previewUrl: 'blob:p1', name: 'a.png', width: 4, height: 3 }],
  66. })
  67. expect(session.getSnapshot().promptAttempted).toBe(true)
  68. expect(session.getSnapshot().pendingSubmissions).toMatchObject([{
  69. requestId: handle.requestId,
  70. text: '你好',
  71. images: [{ previewUrl: 'blob:p1', name: 'a.png', width: 4, height: 3 }],
  72. }])
  73. })
  74. it('abandon retires the echo as failed exactly once', () => {
  75. const { session } = makeSession()
  76. const retirements: PendingSubmissionRetirement[] = []
  77. const handle = session.beginSubmission({
  78. text: '放弃',
  79. images: [],
  80. onRetire: retirement => retirements.push(retirement),
  81. })
  82. handle.abandon()
  83. handle.abandon()
  84. expect(session.getSnapshot().pendingSubmissions).toEqual([])
  85. expect(retirements).toEqual([{ reason: 'failed' }])
  86. })
  87. })
  88. describe('prompt-coupled retirement', () => {
  89. it('a rejected identified prompt retires its echo immediately alongside promptError', async () => {
  90. const { api, session } = makeSession()
  91. api.onPrompt = () => Promise.resolve(err(new RemoteError('session/agent-busy', '忙', { reason: 'busy' })))
  92. const retirements: PendingSubmissionRetirement[] = []
  93. const handle = session.beginSubmission({
  94. text: '失败的',
  95. images: [],
  96. onRetire: retirement => retirements.push(retirement),
  97. })
  98. const result = await session.prompt([{ type: 'text', text: '失败的' }], 'queue', undefined, handle.requestId)
  99. expect(result.ok).toBe(false)
  100. expect(session.getSnapshot().pendingSubmissions).toEqual([])
  101. expect(session.getSnapshot().promptError).toMatchObject({ op: 'send' })
  102. expect(retirements).toEqual([{ reason: 'failed' }])
  103. })
  104. it('sends the echo identity as the prompt requestId', async () => {
  105. const { api, session } = makeSession()
  106. const handle = session.beginSubmission({ text: '带 id', images: [] })
  107. await session.prompt([{ type: 'text', text: '带 id' }], 'queue', undefined, handle.requestId)
  108. expect(api.callsOf('session.prompt')).toMatchObject([{ requestId: handle.requestId }])
  109. })
  110. it('an unidentified prompt failure leaves registered echoes alone', async () => {
  111. const { api, session } = makeSession()
  112. api.onPrompt = () => Promise.resolve(err(new RemoteError('session/agent-busy', '忙', { reason: 'busy' })))
  113. session.beginSubmission({ text: '还在', images: [] })
  114. await session.prompt([{ type: 'text', text: '另一个' }], 'queue')
  115. expect(session.getSnapshot().pendingSubmissions).toHaveLength(1)
  116. })
  117. })
  118. describe('observed retirement', () => {
  119. it('a live durable event carrying the rpcId retires the echo one frame later with the admitted refs', async () => {
  120. const { api, session } = makeSession()
  121. api.onHistory = () => Promise.resolve(ok(historyValue([])))
  122. await session.open()
  123. const retirements: PendingSubmissionRetirement[] = []
  124. const handle = session.beginSubmission({
  125. text: '发送',
  126. images: [{ previewUrl: 'blob:p1' }],
  127. onRetire: retirement => retirements.push(retirement),
  128. })
  129. const refs = [imageRef('att-1')]
  130. await api.pushFollow(SID, { type: 'event', event: promptEvent(0, handle.requestId, refs) as never })
  131. // Synchronously after the append the echo is still in the snapshot; the
  132. // render-time dedupe owns the overlap frame.
  133. expect(session.getSnapshot().pendingSubmissions).toHaveLength(1)
  134. await settleFrames()
  135. expect(session.getSnapshot().pendingSubmissions).toEqual([])
  136. expect(retirements).toEqual([{ reason: 'observed', attachments: refs }])
  137. })
  138. it('a queue occurrence carrying the rpcId retires the echo (running-turn submissions)', async () => {
  139. const { session } = makeSession()
  140. const retirements: PendingSubmissionRetirement[] = []
  141. const handle = session.beginSubmission({
  142. text: '排队',
  143. images: [{ previewUrl: 'blob:p1' }],
  144. onRetire: retirement => retirements.push(retirement),
  145. })
  146. const refs = [imageRef('att-q')]
  147. session.handleControlFrame({ type: 'queue', sessionId: SID, items: [queuedItem(handle.requestId, refs)] })
  148. await settleFrames()
  149. expect(session.getSnapshot().pendingSubmissions).toEqual([])
  150. expect(retirements).toEqual([{ reason: 'observed', attachments: refs }])
  151. // The queue projection keeps the correlation id for render-time dedupe.
  152. expect(session.getSnapshot().queue).toMatchObject([{ rpcId: handle.requestId }])
  153. })
  154. it('a full-window install (reconnect resync) retires echoes observed in the window', async () => {
  155. const { api, session } = makeSession()
  156. const handle = session.beginSubmission({ text: '重连', images: [] })
  157. api.onHistory = () => Promise.resolve(ok(historyValue([promptEvent(12, handle.requestId)])))
  158. await session.open()
  159. await settleFrames()
  160. expect(session.getSnapshot().pendingSubmissions).toEqual([])
  161. })
  162. it('the first observation wins: a later prompt failure cannot re-retire an observed echo', async () => {
  163. const { api, session } = makeSession()
  164. api.onHistory = () => Promise.resolve(ok(historyValue([])))
  165. await session.open()
  166. const retirements: PendingSubmissionRetirement[] = []
  167. const handle = session.beginSubmission({
  168. text: '先观察',
  169. images: [],
  170. onRetire: retirement => retirements.push(retirement),
  171. })
  172. await api.pushFollow(SID, { type: 'event', event: promptEvent(0, handle.requestId) as never })
  173. handle.abandon()
  174. await settleFrames()
  175. expect(retirements).toEqual([{ reason: 'observed', attachments: [] }])
  176. })
  177. it('retires once when the queue and durable event report the same request id', async () => {
  178. const { api, session } = makeSession()
  179. api.onHistory = () => Promise.resolve(ok(historyValue([])))
  180. await session.open()
  181. const retirements: PendingSubmissionRetirement[] = []
  182. const handle = session.beginSubmission({
  183. text: '同一请求',
  184. images: [],
  185. onRetire: retirement => retirements.push(retirement),
  186. })
  187. session.handleControlFrame({
  188. type: 'queue', sessionId: SID, items: [queuedItem(handle.requestId, [])],
  189. })
  190. await api.pushFollow(SID, {
  191. type: 'event', event: promptEvent(0, handle.requestId) as never,
  192. })
  193. await settleFrames()
  194. expect(retirements).toEqual([{ reason: 'observed', attachments: [] }])
  195. expect(session.getSnapshot().pendingSubmissions).toEqual([])
  196. })
  197. it('uses requestAnimationFrame for the retirement delay when the runtime provides one', async () => {
  198. const frames: FrameRequestCallback[] = []
  199. vi.stubGlobal('requestAnimationFrame', (fn: FrameRequestCallback) => {
  200. frames.push(fn)
  201. return frames.length
  202. })
  203. const { api, session } = makeSession()
  204. api.onHistory = () => Promise.resolve(ok(historyValue([])))
  205. await session.open()
  206. const handle = session.beginSubmission({ text: '帧', images: [] })
  207. await api.pushFollow(SID, { type: 'event', event: promptEvent(0, handle.requestId) as never })
  208. expect(session.getSnapshot().pendingSubmissions).toHaveLength(1)
  209. expect(frames).toHaveLength(1)
  210. frames[0]?.(0)
  211. expect(session.getSnapshot().pendingSubmissions).toEqual([])
  212. })
  213. })
  214. describe('disposal', () => {
  215. it('retires unsettled echoes as failed and preserves an already-observed settlement', async () => {
  216. const { api, session } = makeSession()
  217. api.onHistory = () => Promise.resolve(ok(historyValue([])))
  218. await session.open()
  219. const retirements: { text: string; retirement: PendingSubmissionRetirement }[] = []
  220. const observed = session.beginSubmission({
  221. text: '已观察',
  222. images: [],
  223. onRetire: retirement => retirements.push({ text: '已观察', retirement }),
  224. })
  225. session.beginSubmission({
  226. text: '未settle',
  227. images: [],
  228. onRetire: retirement => retirements.push({ text: '未settle', retirement }),
  229. })
  230. await api.pushFollow(SID, { type: 'event', event: promptEvent(0, observed.requestId) as never })
  231. await session.dispose()
  232. await settleFrames()
  233. expect(retirements).toEqual([
  234. { text: '未settle', retirement: { reason: 'failed' } },
  235. { text: '已观察', retirement: { reason: 'observed', attachments: [] } },
  236. ])
  237. expect(session.getSnapshot().pendingSubmissions).toEqual([])
  238. })
  239. })