File size: 11,483 Bytes
09aec41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
/**
 * Queue snapshot semantics: authoritative replacement after every host-side
 * change, reconnect re-baselining, pre-instantiation buffering, editable-text
 * projection, and snapshot reference stability.
 */
import { describe, expect, vi } from 'vitest'
import { createUserMessage } from '@deepseek-ai/dsh-llm'
import type { ContentBlock, UserMessage } from '@deepseek-ai/dsh-llm/types'
import { SessionSeq, type SessionEvent } from '@deepseek-ai/dsh-session/types'
import type { MessageId, RpcId, SessionId } from '@deepseek-ai/dsh-api-remotes/client'
import type { SessionControlFrame } from '@deepseek-ai/dsh-api-session-controller/types'
import { createClientTest, webApp } from '@deepseek-ai/dsh-client-test-runtime/src/assembly/index.ts'
import { SessionManager } from '../src/client/sessions/manager.ts'
import { sessionBench } from './remote/bench.client.ts'
import { pushEvent, sessionWorld } from './remote/session.client.ts'

/** A Session talks through the Gateway client; its dependency cone is the Typert registry and the Connection. */
const API_ROSTER = webApp.closure(['@deepseek-ai/dsh-api-gateway'])
const it = createClientTest({ roster: API_ROSTER })
const SID = 'fk-q1' as SessionId
/** The first client boot pays the cold module transform of the api cone. */
const COLD_BOOT_TIMEOUT_MS = 60_000
const text = (value: string): ContentBlock[] => [{ type: 'text', text: value }]
const rid = (id: string): RpcId => id as RpcId
const iid = (id: string): MessageId => id as MessageId

interface QueueFixture {
  id: string
  body: string
  content?: ContentBlock[]
  placement?: 'queued' | 'steering'
  message?: UserMessage
}

/** Build one authoritative queue snapshot. */
function queueFrame(items: QueueFixture[]): Extract<SessionControlFrame, { type: 'queue' }> {
  return {
    type: 'queue',
    sessionId: SID,
    items: items.map(item => ({
      id: iid(item.id),
      placement: item.placement ?? 'queued',
      message: (item.message ?? createUserMessage({
        content: item.content ?? text(item.body),
        source: { kind: 'user', rpcId: rid(`rpc-${item.id}`) } as never,
      })) as never,
    })),
  }
}

describe('Session queue snapshot intake', () => {
  it('projects stable ids, flat previews, and complete text', async ({ mock, start }) => {
    const session = await sessionBench(mock, start, SID)
    session.handleControlFrame(queueFrame([
      { id: 'q-1', body: '第一条  排队\n消息' },
    ]))
    const queue = session.getSnapshot().queue
    expect(typeof queue[0]?.messageId).toBe('string')
    expect(queue).toMatchObject([
      {
        id: 'q-1', placement: 'queued',
        content: [{ type: 'text', text: '第一条  排队\n消息' }],
        preview: '第一条 排队 消息', text: '第一条  排队\n消息',
      },
    ])
  }, COLD_BOOT_TIMEOUT_MS)

  it('marks mixed-content messages non-editable and keeps attachment blocks out of the text preview', async ({ mock, start }) => {
    const session = await sessionBench(mock, start, SID)
    session.handleControlFrame(queueFrame([{
      id: 'q-image',
      body: '',
      content: [
        { type: 'text', text: 'hi' },
        { type: 'image', data: 'x' } as never,
        { type: 'file', attachment: { attachmentId: 'file-1', name: 'notes.txt', bytes: 5 } } as never,
      ],
    }]))
    const queue = session.getSnapshot().queue
    expect(typeof queue[0]?.messageId).toBe('string')
    expect(queue).toMatchObject([
      {
        id: 'q-image', placement: 'queued',
        content: [
          { type: 'text', text: 'hi' },
          { type: 'image', data: 'x' },
          { type: 'file', attachment: { attachmentId: 'file-1', name: 'notes.txt', bytes: 5 } },
        ],
        // Attachment blocks render from `content`, so the preview carries
        // only text; other foreign blocks keep their marker.
        preview: 'hi', text: null,
      },
    ])
  })

  it('caps previews at 200 code points and preserves the full editable text', async ({ mock, start }) => {
    const session = await sessionBench(mock, start, SID)
    const body = '长'.repeat(201)
    session.handleControlFrame(queueFrame([{ id: 'q-cap', body }]))
    const row = session.getSnapshot().queue[0]
    expect(Array.from(row?.preview ?? '')).toHaveLength(201)
    expect(row?.preview.endsWith('…')).toBe(true)
    expect(row?.text).toBe(body)
  })

  it('replaces content, order, and membership from each authoritative frame', async ({ mock, start }) => {
    const session = await sessionBench(mock, start, SID)
    session.handleControlFrame(queueFrame([
      { id: 'q-1', body: 'one' },
      { id: 'q-2', body: 'two' },
    ]))
    session.handleControlFrame(queueFrame([
      { id: 'q-2', body: 'two edited' },
    ]))
    const queue = session.getSnapshot().queue
    expect(typeof queue[0]?.messageId).toBe('string')
    expect(queue).toMatchObject([
      {
        id: 'q-2', placement: 'queued',
        content: [{ type: 'text', text: 'two edited' }],
        preview: 'two edited', text: 'two edited',
      },
    ])
    session.handleControlFrame(queueFrame([]))
    expect(session.getSnapshot().queue).toEqual([])
  })

  it('keeps the queue array reference stable across unrelated snapshot swaps', async ({ mock, start }) => {
    const session = await sessionBench(mock, start, SID)
    session.handleControlFrame(queueFrame([{ id: 'q-stable', body: '稳定' }]))
    const before = session.getSnapshot().queue
    session.handleAgentError('unrelated')
    expect(session.getSnapshot().queue).toBe(before)
  })

  it('retains steering placement and complete content in the same authoritative snapshot', async ({ mock, start }) => {
    const session = await sessionBench(mock, start, SID)
    session.handleControlFrame(queueFrame([
      { id: 'q-next', body: 'later' },
      { id: 's-now', body: 'interrupt now', placement: 'steering' },
    ]))

    expect(session.getSnapshot().queue.map(item => ({
      id: item.id, placement: item.placement, content: item.content,
    }))).toEqual([
      { id: 'q-next', placement: 'queued', content: text('later') },
      { id: 's-now', placement: 'steering', content: text('interrupt now') },
    ])
  })

  it('hands off exactly one current occurrence when live steering becomes durable', async ({ mock, start }) => {
    const session = await sessionBench(mock, start, SID)
    await session.open()
    const message = createUserMessage({
      content: text('same message'),
      source: { kind: 'user' },
    })
    session.handleControlFrame(queueFrame([
      { id: 's-first', body: '', placement: 'steering', message },
      { id: 's-second', body: '', placement: 'steering', message },
    ]))
    const durable = {
      seq: SessionSeq(0),
      time: 1_700_000_000_000,
      type: 'user/message',
      surfaceOp: 'append',
      data: message,
    } satisfies SessionEvent

    await pushEvent(mock, durable)
    await vi.waitFor(() => {
      expect(session.getSnapshot().queue.map(item => item.id)).toEqual(['s-second'])
    })

    session.handleControlFrame(queueFrame([
      { id: 's-later', body: '', placement: 'steering', message },
    ]))
    await pushEvent(mock, durable)
    await vi.waitFor(() => {
      expect(session.getSnapshot().queue.map(item => item.id)).toEqual(['s-later'])
    })
  })

  it('hands off live steering when the agent claims it as a user message', async ({ mock, start }) => {
    const session = await sessionBench(mock, start, SID)
    await session.open()
    const message = createUserMessage({
      content: text('claimed steering'),
      source: { kind: 'user' },
    })
    session.handleControlFrame(queueFrame([
      { id: 's-claimed', body: '', placement: 'steering', message },
    ]))

    await pushEvent(mock, {
      seq: 0,
      time: 1_700_000_000_000,
      type: 'user/message',
      surfaceOp: 'append',
      data: message,
    } as never)

    await vi.waitFor(() => {
      expect(session.getSnapshot().queue).toEqual([])
    })
  })
})

describe('queue operation transport', () => {
  it('addresses the session.updateQueue RPC without optimistic local mutation', async ({ mock, start }) => {
    const session = await sessionBench(mock, start, SID)
    session.handleControlFrame(queueFrame([{ id: 'q-op', body: 'pending' }]))
    const before = session.getSnapshot().queue

    await expect(session.updateQueue(iid('q-op'), { kind: 'edit', content: text('next') }))
      .resolves.toEqual({ ok: true, value: { accepted: true } })
    await expect(session.updateQueue(iid('q-op'), { kind: 'steer' }))
      .resolves.toEqual({ ok: true, value: { accepted: true } })
    expect(mock.log.requests('session/updateQueue')).toEqual([
      {
        sessionId: SID,
        itemId: 'q-op',
        action: { kind: 'edit', content: text('next') },
      },
      {
        sessionId: SID,
        itemId: 'q-op',
        action: { kind: 'steer' },
      },
    ])
    expect(session.getSnapshot().queue).toBe(before)
  })
})

describe('queue reconnect semantics', () => {
  it('a control baseline clears stale state before a fresh update lands', async ({ mock, start }) => {
    const session = await sessionBench(mock, start, SID)
    session.handleControlFrame(queueFrame([{ id: 'q-old', body: '旧连接' }]))
    session.replaceControl([])
    expect(session.getSnapshot().queue).toEqual([])
    session.handleControlFrame(queueFrame([{ id: 'q-new', body: '新基线' }]))
    expect(session.getSnapshot().queue.map(row => row.id)).toEqual(['q-new'])
  })

  it('resync does not clear a baseline that raced ahead of the host connection signal', async ({ mock, start }) => {
    const session = await sessionBench(mock, start, SID)
    await session.open()
    session.handleControlFrame(queueFrame([{ id: 'q-fresh', body: '新基线' }]))
    await session.resync()
    expect(session.getSnapshot().queue.map(row => row.id)).toEqual(['q-fresh'])
  })

  it('running-status changes never guess at queue retirement', async ({ mock, start }) => {
    const session = await sessionBench(mock, start, SID)
    session.handleControlFrame(queueFrame([{ id: 'q-live', body: '保留' }]))
    session.handleRunning(true)
    session.handleRunning(false)
    expect(session.getSnapshot().queue.map(row => row.id)).toEqual(['q-live'])
  })
})

describe('manager buffering of queue snapshots', () => {
  it('replays only the latest snapshot for an uninstantiated session', async ({ mock, start }) => {
    mock.load(sessionWorld)
    const { ctx: { remote } } = await start()
    const manager = new SessionManager(remote)
    manager.handleControlFrame(queueFrame([{ id: 'q-old', body: '旧' }]))
    manager.handleControlFrame(queueFrame([{ id: 'q-new', body: '新' }]))
    expect(manager.get(SID).getSnapshot().queue.map(row => row.id)).toEqual(['q-new'])
  })

  it('a control baseline replaces the prior queue', async ({ mock, start }) => {
    mock.load(sessionWorld)
    const { ctx: { remote } } = await start()
    const manager = new SessionManager(remote)
    manager.handleControlFrame(queueFrame([{ id: 'q-g1', body: '第一代' }]))
    const nextQueue = queueFrame([{ id: 'q-g2', body: '第二代' }]).items
    manager.handleControlFrame({
      type: 'baseline',
      value: {
        queues: { [SID]: nextQueue },
        jobs: {},
        projections: {},
      },
    })
    const snapshot = manager.get(SID).getSnapshot()
    expect(snapshot.queue.map(row => row.id)).toEqual(['q-g2'])
  })
})