File size: 15,435 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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
/** Session Controller fork boundaries, lineage, and inherited model routing. */

import { describe, expect, it, vi } from 'vitest'
import { Context } from '@deepseek-ai/cordis'
import AgentRegistry, { agentEvents } from '@deepseek-ai/dsh-agent'
import type { Agent, AgentHandle, CreateAgentOptions } from '@deepseek-ai/dsh-agent'
import { mountAgentLoopTestDependencies, mountAgentLoopTestHarness } from '@deepseek-ai/dsh-agent-loop-testkit'
import { MockAdapter, textResponse } from '../../../core/agent-loop/tests/mock-adapter.ts'
import { createUserMessage, ReasoningEffortId } from '@deepseek-ai/dsh-llm'
import type { LlmCallConfig } from '@deepseek-ai/dsh-llm'
import SessionStore, { SESSION_FORMAT_VERSION, SessionLogOffset, SessionSeq } from '@deepseek-ai/dsh-session'
import type { Session, SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session'
import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
import type { Workspace } from '@deepseek-ai/dsh-workspace'
import {
  createSessionTestRemote, installSessionReadTestServices, testSessionPersistence,
} from './test-remote.ts'

const sid = (id: string): SessionId => id as SessionId

function request<P>(payload: P): P {
  return payload
}

async function composed(workspaces: readonly Workspace[] = []): Promise<Context> {
  const ctx = new Context()
  await ctx.plugin(SessionStore)
  await ctx.plugin(SystemPrompt, { personaPrefix: '' })
  await ctx.plugin(AgentRegistry)
  installSessionReadTestServices(ctx)
  ctx.provide('workspaceRegistry', { list: () => workspaces } as never)
  ctx.agents.setFactory({
    createAgent: async (ownerCtx: Context, options: CreateAgentOptions): Promise<AgentHandle> => {
      const session = ctx.sessions.create(options.sessionId, {
        ...options.seed === undefined ? {} : { seed: [...options.seed] },
        ...options.meta === undefined ? {} : { meta: options.meta },
        ...options.inheritedEventCount === undefined
          ? {}
          : { inheritedEventCount: options.inheritedEventCount },
      })
      const agent = {} as Agent
      const agentCtx = ownerCtx
      Object.assign(agent, { id: session.id, session, status: 'idle', ctx: agentCtx })
      await options.setup?.(agentCtx, agent)
      await ctx.agents.register(agent)
      return { agent, dispose: () => Promise.resolve() }
    },
    resume: () => Promise.reject(new Error('fork test sources are live')),
  })
  return ctx
}

/** Tail turn appended after the completed ones: left open, or closed as aborted (a stopped turn). */
type Tail = 'none' | 'open' | 'aborted'

async function liveAgent(
  ctx: Context,
  id: string,
  turns: number,
  tail: Tail = 'none',
  lineage: { parentSession?: SessionId; origin?: 'subagent' } = {},
): Promise<Session> {
  const session = ctx.sessions.create(sid(id), { meta: { cwd: '/proj', ...lineage } })
  for (let turn = 1; turn <= turns; turn++) {
    session.append('turn/start', { turn })
    session.append('user/message', createUserMessage({
      content: [{ type: 'text', text: `prompt ${String(turn)}` }],
      source: { kind: 'user' },
    }), { surfaceOp: 'append' })
    session.append('turn/end', { turn, reason: { kind: 'completed' } })
  }
  if (tail !== 'none') {
    session.append('turn/start', { turn: turns + 1 })
    session.append('user/message', createUserMessage({
      content: [{ type: 'text', text: 'open prompt' }],
      source: { kind: 'user' },
    }), { surfaceOp: 'append' })
    if (tail === 'aborted') session.append('turn/end', {
      turn: turns + 1,
      reason: { kind: 'aborted', reason: { kind: 'user' } },
    })
  }
  await ctx.agents.register({ id: session.id, session, status: 'idle', ctx } as Agent)
  return session
}

const remote = (ctx: Context) => createSessionTestRemote(ctx, {
  defaultModelSelection: () => ({ provider: 'default-provider', model: 'default-model' }),
  cwd: '/tmp',
})

describe('sessions.fork', () => {
  it.each(['message', 'turn-end', 'omitted', 'past-end'] as const)(
    'excludes the next user input when forking at %s', async (anchor) => {
      const ctx = new Context()
      try {
        await mountAgentLoopTestDependencies(ctx)
        const harness = await mountAgentLoopTestHarness(ctx)
        const adapter = new MockAdapter(Array.from({ length: 4 }, () => textResponse('reply')))
        ctx.llm.registerAdapter(['mock'], adapter)
        ctx.provide('workspaceRegistry', { list: () => [] } as never)
        const source = await harness.create(sid('source'), { provider: 'mock', model: 'mock' })
        const message = (text: string) => createUserMessage({
          content: [{ type: 'text', text }], source: { kind: 'user' },
        })
        source.followup(message('A'))
        await source.whenIdle()
        const boundary = source.session.snapshotEvents().at(-1)!.seq
        if (anchor === 'message' || anchor === 'turn-end') {
          source.followup(message('B'))
          await source.whenIdle()
        } else {
          source.inbox.append('next-turn', message('B'))
        }
        const original = source.session.snapshotEvents()
        const atSeq = anchor === 'omitted' ? undefined
          : anchor === 'past-end' ? source.session.seq + 1
            : anchor === 'turn-end' ? boundary
              : original.find(event => event.type === 'assistant/message')!.seq
        const response = await createSessionTestRemote(ctx, {
          defaultModelSelection: () => ({ provider: 'mock', model: 'mock' }), cwd: '/tmp',
        }).fork({ sessionId: source.id, ...(atSeq === undefined ? {} : { atSeq }) })
        if (!response.ok) throw response.error
        const child = ctx.agents.get(response.value.sessionId)!
        const requestCount = adapter.requests.length
        child.followup(message('C'))
        await child.whenIdle()
        const userTexts = child.session.deriveMessages().flatMap(item => item.role === 'user'
          ? item.content.flatMap(part => part.type === 'text' ? [part.text] : []) : [])
        expect(userTexts).toEqual(['A', 'C'])
        expect(adapter.requests.slice(requestCount)).toHaveLength(1)
        expect(child.session.inheritedEventCount).toBe(boundary + 1)
        expect(source.session.snapshotEvents()).toEqual(original)
      } finally {
        await ctx.fiber.dispose()
      }
    },
  )

  it('cuts at the anchored completed turn and records lineage and cwd', async () => {
    const ctx = await composed()
    const source = await liveAgent(ctx, 'session-source', 2)
    const response = await remote(ctx).fork(request({ sessionId: source.id, atSeq: 1 }))
    expect(response.ok ? null : response.error).toBeNull()
    if (!response.ok) return
    const child = ctx.sessions.get(response.value.sessionId)
    expect(child?.snapshotEvents().map(event => event.type)).toEqual([
      'turn/start', 'user/message', 'turn/end', 'session/end-seed',
    ])
    expect(child?.header.parentSession).toBe(source.id)
    expect(child?.header.cwd).toBe('/proj')
    await ctx.fiber.dispose()
  })

  it('attaches a subagent fork to its nearest workspace-owning ancestor', async () => {
    const accounted: SessionId[] = []
    const attachSession = vi.fn<(sessionId: SessionId) => Promise<void>>()
      .mockResolvedValue(undefined)
    const workspace = {
      sessionIds: accounted,
      attachSession,
    } as unknown as Workspace
    const ctx = await composed([workspace])
    const owner = await liveAgent(ctx, 'session-owner', 1)
    accounted.push(owner.id)
    const child = await liveAgent(ctx, 'session-child', 1, 'none', {
      parentSession: owner.id,
      origin: 'subagent',
    })
    const grandchild = await liveAgent(ctx, 'session-grandchild', 1, 'none', {
      parentSession: child.id,
      origin: 'subagent',
    })
    vi.spyOn(ctx.sessionQuery, 'traceSession').mockResolvedValue({
      target: { header: grandchild.header, live: true, persisted: false },
      ancestors: [
        { header: child.header, live: true, persisted: false },
        { header: owner.header, live: true, persisted: false },
      ],
      descendants: [],
      complete: true,
      root: { header: owner.header, live: true, persisted: false },
    })

    const response = await remote(ctx).fork(request({ sessionId: grandchild.id }))

    expect(response.ok).toBe(true)
    if (!response.ok) return
    expect(attachSession).toHaveBeenCalledWith(response.value.sessionId)
    expect(ctx.sessions.get(response.value.sessionId)?.header).toMatchObject({
      parentSession: grandchild.id,
      cwd: '/proj',
    })
    expect(ctx.sessions.get(response.value.sessionId)?.header.origin).toBeUndefined()
    await ctx.fiber.dispose()
  })

  it('forks a persisted subagent without resuming its Agent', async () => {
    const ctx = await composed()
    const sourceId = sid('session-cold-subagent')
    const parentId = sid('session-cold-parent')
    const header: SessionHeader = {
      version: SESSION_FORMAT_VERSION,
      id: sourceId,
      createdAt: 1,
      cwd: '/proj',
      parentSession: parentId,
      isSeeded: false,
      origin: 'subagent',
    }
    const events = [
      {
        type: 'turn/start',
        seq: SessionSeq(0),
        time: 1,
        data: {
          turn: 1,
          trigger: { kind: 'message', source: { kind: 'user' } },
        } as SessionEvent<'turn/start'>['data'],
      },
      {
        type: 'user/message',
        seq: SessionSeq(1),
        time: 2,
        data: createUserMessage({ content: [{ type: 'text', text: 'work' }], source: { kind: 'user' } }),
        surfaceOp: 'append',
      },
      { type: 'turn/end', seq: SessionSeq(2), time: 3, data: { turn: 1, reason: { kind: 'completed' } } },
    ] satisfies SessionEvent[]
    ctx.provide('sessionPersistence', testSessionPersistence(ctx, {
      list: () => Promise.resolve([header]),
      inspect: () => Promise.resolve({
        meta: header,
        inheritedEventCount: SessionLogOffset(0),
        events,
      }),
    }) as never)
    const resume = vi.spyOn(ctx.agents, 'resume')

    const response = await remote(ctx).fork(request({ sessionId: sourceId }))

    expect(response.ok).toBe(true)
    if (!response.ok) return
    expect(resume).not.toHaveBeenCalled()
    expect(ctx.agents.get(sourceId)).toBeUndefined()
    expect(ctx.sessions.get(response.value.sessionId)?.header).toMatchObject({
      parentSession: sourceId,
      cwd: '/proj',
    })
    expect(ctx.sessions.get(response.value.sessionId)?.header.origin).toBeUndefined()
    await ctx.fiber.dispose()
  })

  it('uses the last completed turn only for omitted and past-end anchors', async () => {
    const ctx = await composed()
    const source = await liveAgent(ctx, 'session-tail', 2, 'open')
    const proxy = remote(ctx)
    const expectedTypes = [
      'turn/start', 'user/message', 'turn/end',
      'turn/start', 'user/message', 'turn/end',
      'session/end-seed',
    ]
    const omitted = await proxy.fork(request({ sessionId: source.id }))
    expect(omitted.ok).toBe(true)
    if (omitted.ok) {
      expect(ctx.sessions.get(omitted.value.sessionId)?.snapshotEvents().map(event => event.type))
        .toEqual(expectedTypes)
    }
    const pastEnd = await proxy.fork(request({ sessionId: source.id, atSeq: 999 }))
    expect(pastEnd.ok).toBe(true)
    if (pastEnd.ok) {
      expect(ctx.sessions.get(pastEnd.value.sessionId)?.snapshotEvents().map(event => event.type))
        .toEqual(expectedTypes)
    }
    await ctx.fiber.dispose()
  })

  it('rejects invalid fork anchors before reading or creating a Session', async () => {
    const ctx = await composed()
    const proxy = remote(ctx)

    for (const atSeq of [-1, 0.5]) {
      await expect(proxy.fork(request({ sessionId: sid('missing'), atSeq })))
        .resolves.toMatchObject({ ok: false, error: { code: 'gateway/bad-request' } })
    }
    expect(ctx.sessions.list()).toEqual([])
    await ctx.fiber.dispose()
  })

  it('cuts through an aborted turn: stopped is closed, not open', async () => {
    const ctx = await composed()
    const source = await liveAgent(ctx, 'session-aborted', 1, 'aborted')
    // What a stopped message's fork button anchors on: the frozen node sits
    // one event before its turn/end, floored client-side to that event's seq.
    const anchor = (source.snapshotEvents().at(-1)?.seq ?? 0) - 1
    const response = await remote(ctx).fork(request({ sessionId: source.id, atSeq: anchor }))
    expect(response.ok).toBe(true)
    if (!response.ok) return
    expect(ctx.sessions.get(response.value.sessionId)?.snapshotEvents().map(event => event.type)).toEqual([
      'turn/start', 'user/message', 'turn/end',
      'turn/start', 'user/message', 'turn/end',
      'session/end-seed',
    ])
    await ctx.fiber.dispose()
  })

  it('rejects an in-log anchor whose turn is still open', async () => {
    const ctx = await composed()
    const source = await liveAgent(ctx, 'session-open', 1, 'open')
    const anchor = source.snapshotEvents().at(-1)?.seq ?? 0
    const response = await remote(ctx).fork(request({ sessionId: source.id, atSeq: anchor }))
    expect(response).toMatchObject({
      ok: false,
      error: { code: 'session/fork-unavailable', details: { sessionId: source.id } },
    })
    if (!response.ok) expect(response.error.message).toMatch(/has not completed/)
    await ctx.fiber.dispose()
  })

  it('inherits model selection through the completed turn and excludes later changes', async () => {
    const ctx = await composed()
    const source = await liveAgent(ctx, 'session-routed', 0)
    source.append('turn/start', { turn: 1 })
    source.append('request/header', {
      header: {
        config: {
          provider: 'inherited-provider',
          model: 'inherited-model',
          reasoningEffort: ReasoningEffortId('high'),
        },
      },
      reason: 'initial',
    })
    const boundary = source.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
    const inherited = source.snapshotEvents()
    source.append('session/title', {
      title: 'Title after the selected turn', messageSeqs: [], source: { kind: 'user' },
    })
    source.append('turn/start', { turn: 2 })
    source.append('request/header', {
      header: { config: { provider: 'later-provider', model: 'later-model' } },
      reason: 'change',
    })
    source.append('turn/end', { turn: 2, reason: { kind: 'completed' } })
    const response = await remote(ctx).fork(request({ sessionId: source.id, atSeq: boundary.seq }))
    expect(response.ok).toBe(true)
    if (!response.ok) return
    const child = ctx.agents.get(response.value.sessionId)
    if (child === undefined) throw new Error('fork did not publish the child agent')
    expect(child.session.snapshotEvents().slice(0, child.session.inheritedEventCount)).toEqual(inherited)
    const assembly = await child.ctx.systemPrompt.assemble()
    expect(assembly.variables).toMatchObject({
      provider: 'inherited-provider',
      model: 'inherited-model',
    })
    const fallback: LlmCallConfig = { provider: 'default-provider', model: 'default-model' }
    await expect(agentEvents(child.ctx, child).waterfall(
      'agent/request', { turn: 1, step: 0, signal: new AbortController().signal }, () => Promise.resolve(fallback),
    )).resolves.toMatchObject({
      provider: 'inherited-provider',
      model: 'inherited-model',
      reasoningEffort: 'high',
    })
    await ctx.fiber.dispose()
  })
})