session-fork.host.spec.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. /** Session Controller fork boundaries, lineage, and inherited model routing. */
  2. import { describe, expect, it, vi } from 'vitest'
  3. import { Context } from '@deepseek-ai/cordis'
  4. import AgentRegistry, { agentEvents } from '@deepseek-ai/dsh-agent'
  5. import type { Agent, AgentHandle, CreateAgentOptions } from '@deepseek-ai/dsh-agent'
  6. import { mountAgentLoopTestDependencies, mountAgentLoopTestHarness } from '@deepseek-ai/dsh-agent-loop-testkit'
  7. import { MockAdapter, textResponse } from '../../../core/agent-loop/tests/mock-adapter.ts'
  8. import { createUserMessage, ReasoningEffortId } from '@deepseek-ai/dsh-llm'
  9. import type { LlmCallConfig } from '@deepseek-ai/dsh-llm'
  10. import SessionStore, { SESSION_FORMAT_VERSION, SessionLogOffset, SessionSeq } from '@deepseek-ai/dsh-session'
  11. import type { Session, SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session'
  12. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  13. import type { Workspace } from '@deepseek-ai/dsh-workspace'
  14. import {
  15. createSessionTestRemote, installSessionReadTestServices, testSessionPersistence,
  16. } from './test-remote.ts'
  17. const sid = (id: string): SessionId => id as SessionId
  18. function request<P>(payload: P): P {
  19. return payload
  20. }
  21. async function composed(workspaces: readonly Workspace[] = []): Promise<Context> {
  22. const ctx = new Context()
  23. await ctx.plugin(SessionStore)
  24. await ctx.plugin(SystemPrompt, { personaPrefix: '' })
  25. await ctx.plugin(AgentRegistry)
  26. installSessionReadTestServices(ctx)
  27. ctx.provide('workspaceRegistry', { list: () => workspaces } as never)
  28. ctx.agents.setFactory({
  29. createAgent: async (ownerCtx: Context, options: CreateAgentOptions): Promise<AgentHandle> => {
  30. const session = ctx.sessions.create(options.sessionId, {
  31. ...options.seed === undefined ? {} : { seed: [...options.seed] },
  32. ...options.meta === undefined ? {} : { meta: options.meta },
  33. ...options.inheritedEventCount === undefined
  34. ? {}
  35. : { inheritedEventCount: options.inheritedEventCount },
  36. })
  37. const agent = {} as Agent
  38. const agentCtx = ownerCtx
  39. Object.assign(agent, { id: session.id, session, status: 'idle', ctx: agentCtx })
  40. await options.setup?.(agentCtx, agent)
  41. ctx.agents.register(agent)
  42. return { agent, dispose: () => Promise.resolve() }
  43. },
  44. resume: () => Promise.reject(new Error('fork test sources are live')),
  45. })
  46. return ctx
  47. }
  48. /** Tail turn appended after the completed ones: left open, or closed as aborted (a stopped turn). */
  49. type Tail = 'none' | 'open' | 'aborted'
  50. function liveAgent(
  51. ctx: Context,
  52. id: string,
  53. turns: number,
  54. tail: Tail = 'none',
  55. lineage: { parentSession?: SessionId; origin?: 'subagent' } = {},
  56. ): Session {
  57. const session = ctx.sessions.create(sid(id), { meta: { cwd: '/proj', ...lineage } })
  58. for (let turn = 1; turn <= turns; turn++) {
  59. session.append('turn/start', { turn })
  60. session.append('user/message', createUserMessage({
  61. content: [{ type: 'text', text: `prompt ${String(turn)}` }],
  62. source: { kind: 'user' },
  63. }), { surfaceOp: 'append' })
  64. session.append('turn/end', { turn, reason: { kind: 'completed' } })
  65. }
  66. if (tail !== 'none') {
  67. session.append('turn/start', { turn: turns + 1 })
  68. session.append('user/message', createUserMessage({
  69. content: [{ type: 'text', text: 'open prompt' }],
  70. source: { kind: 'user' },
  71. }), { surfaceOp: 'append' })
  72. if (tail === 'aborted') session.append('turn/end', {
  73. turn: turns + 1,
  74. reason: { kind: 'aborted', reason: { kind: 'user' } },
  75. })
  76. }
  77. ctx.agents.register({ id: session.id, session, status: 'idle', ctx } as Agent)
  78. return session
  79. }
  80. const remote = (ctx: Context) => createSessionTestRemote(ctx, {
  81. defaultModelSelection: () => ({ provider: 'default-provider', model: 'default-model' }),
  82. cwd: '/tmp',
  83. })
  84. describe('sessions.fork', () => {
  85. it.each(['message', 'turn-end', 'omitted', 'past-end'] as const)(
  86. 'excludes the next user input when forking at %s', async (anchor) => {
  87. const ctx = new Context()
  88. try {
  89. await mountAgentLoopTestDependencies(ctx)
  90. const harness = await mountAgentLoopTestHarness(ctx)
  91. const adapter = new MockAdapter(Array.from({ length: 4 }, () => textResponse('reply')))
  92. ctx.llm.registerAdapter(['mock'], adapter)
  93. ctx.provide('workspaceRegistry', { list: () => [] } as never)
  94. const source = await harness.create(sid('source'), { provider: 'mock', model: 'mock' })
  95. const message = (text: string) => createUserMessage({
  96. content: [{ type: 'text', text }], source: { kind: 'user' },
  97. })
  98. source.followup(message('A'))
  99. await source.whenIdle()
  100. const boundary = source.session.snapshotEvents().at(-1)!.seq
  101. const title = source.session.append('session/title', {
  102. title: 'Title after A', messageSeqs: [], source: { kind: 'user' },
  103. })
  104. if (anchor === 'message' || anchor === 'turn-end') {
  105. source.followup(message('B'))
  106. await source.whenIdle()
  107. } else {
  108. source.inbox.append('next-turn', message('B'))
  109. }
  110. const original = source.session.snapshotEvents()
  111. const atSeq = anchor === 'omitted' ? undefined
  112. : anchor === 'past-end' ? source.session.seq + 1
  113. : anchor === 'turn-end' ? boundary
  114. : original.find(event => event.type === 'assistant/message')!.seq
  115. const response = await createSessionTestRemote(ctx, {
  116. defaultModelSelection: () => ({ provider: 'mock', model: 'mock' }), cwd: '/tmp',
  117. }).fork({ sessionId: source.id, ...(atSeq === undefined ? {} : { atSeq }) })
  118. if (!response.ok) throw response.error
  119. const child = ctx.agents.get(response.value.sessionId)!
  120. const requestCount = adapter.requests.length
  121. child.followup(message('C'))
  122. await child.whenIdle()
  123. const userTexts = child.session.deriveMessages().flatMap(item => item.role === 'user'
  124. ? item.content.flatMap(part => part.type === 'text' ? [part.text] : []) : [])
  125. expect(userTexts).toEqual(['A', 'C'])
  126. expect(adapter.requests.slice(requestCount)).toHaveLength(1)
  127. expect(child.session.inheritedEventCount).toBe(title.seq + 1)
  128. expect(child.session.snapshotEvents().slice(0, child.session.inheritedEventCount))
  129. .toEqual(original.slice(0, title.seq + 1))
  130. expect(source.session.snapshotEvents()).toEqual(original)
  131. } finally {
  132. await ctx.fiber.dispose()
  133. }
  134. },
  135. )
  136. it('cuts at the anchored completed turn and records lineage and cwd', async () => {
  137. const ctx = await composed()
  138. const source = liveAgent(ctx, 'session-source', 2)
  139. const response = await remote(ctx).fork(request({ sessionId: source.id, atSeq: 1 }))
  140. expect(response.ok ? null : response.error).toBeNull()
  141. if (!response.ok) return
  142. const child = ctx.sessions.get(response.value.sessionId)
  143. expect(child?.snapshotEvents().map(event => event.type)).toEqual([
  144. 'turn/start', 'user/message', 'turn/end', 'session/end-seed',
  145. ])
  146. expect(child?.header.parentSession).toBe(source.id)
  147. expect(child?.header.cwd).toBe('/proj')
  148. await ctx.fiber.dispose()
  149. })
  150. it('attaches a subagent fork to its nearest workspace-owning ancestor', async () => {
  151. const accounted: SessionId[] = []
  152. const attachSession = vi.fn<(sessionId: SessionId) => Promise<void>>()
  153. .mockResolvedValue(undefined)
  154. const workspace = {
  155. sessionIds: accounted,
  156. attachSession,
  157. } as unknown as Workspace
  158. const ctx = await composed([workspace])
  159. const owner = liveAgent(ctx, 'session-owner', 1)
  160. accounted.push(owner.id)
  161. const child = liveAgent(ctx, 'session-child', 1, 'none', {
  162. parentSession: owner.id,
  163. origin: 'subagent',
  164. })
  165. const grandchild = liveAgent(ctx, 'session-grandchild', 1, 'none', {
  166. parentSession: child.id,
  167. origin: 'subagent',
  168. })
  169. vi.spyOn(ctx.sessionQuery, 'traceSession').mockResolvedValue({
  170. target: { header: grandchild.header, live: true, persisted: false },
  171. ancestors: [
  172. { header: child.header, live: true, persisted: false },
  173. { header: owner.header, live: true, persisted: false },
  174. ],
  175. descendants: [],
  176. complete: true,
  177. root: { header: owner.header, live: true, persisted: false },
  178. })
  179. const response = await remote(ctx).fork(request({ sessionId: grandchild.id }))
  180. expect(response.ok).toBe(true)
  181. if (!response.ok) return
  182. expect(attachSession).toHaveBeenCalledWith(response.value.sessionId)
  183. expect(ctx.sessions.get(response.value.sessionId)?.header).toMatchObject({
  184. parentSession: grandchild.id,
  185. cwd: '/proj',
  186. })
  187. expect(ctx.sessions.get(response.value.sessionId)?.header.origin).toBeUndefined()
  188. await ctx.fiber.dispose()
  189. })
  190. it('forks a persisted subagent without resuming its Agent', async () => {
  191. const ctx = await composed()
  192. const sourceId = sid('session-cold-subagent')
  193. const parentId = sid('session-cold-parent')
  194. const header: SessionHeader = {
  195. version: SESSION_FORMAT_VERSION,
  196. id: sourceId,
  197. createdAt: 1,
  198. cwd: '/proj',
  199. parentSession: parentId,
  200. isSeeded: false,
  201. origin: 'subagent',
  202. }
  203. const events = [
  204. {
  205. type: 'turn/start',
  206. seq: SessionSeq(0),
  207. time: 1,
  208. data: {
  209. turn: 1,
  210. trigger: { kind: 'message', source: { kind: 'user' } },
  211. } as SessionEvent<'turn/start'>['data'],
  212. },
  213. {
  214. type: 'user/message',
  215. seq: SessionSeq(1),
  216. time: 2,
  217. data: createUserMessage({ content: [{ type: 'text', text: 'work' }], source: { kind: 'user' } }),
  218. surfaceOp: 'append',
  219. },
  220. { type: 'turn/end', seq: SessionSeq(2), time: 3, data: { turn: 1, reason: { kind: 'completed' } } },
  221. ] satisfies SessionEvent[]
  222. ctx.provide('sessionPersistence', testSessionPersistence(ctx, {
  223. list: () => Promise.resolve([header]),
  224. inspect: () => Promise.resolve({
  225. meta: header,
  226. inheritedEventCount: SessionLogOffset(0),
  227. events,
  228. }),
  229. }) as never)
  230. const resume = vi.spyOn(ctx.agents, 'resume')
  231. const response = await remote(ctx).fork(request({ sessionId: sourceId }))
  232. expect(response.ok).toBe(true)
  233. if (!response.ok) return
  234. expect(resume).not.toHaveBeenCalled()
  235. expect(ctx.agents.get(sourceId)).toBeUndefined()
  236. expect(ctx.sessions.get(response.value.sessionId)?.header).toMatchObject({
  237. parentSession: sourceId,
  238. cwd: '/proj',
  239. })
  240. expect(ctx.sessions.get(response.value.sessionId)?.header.origin).toBeUndefined()
  241. await ctx.fiber.dispose()
  242. })
  243. it('uses the last completed turn only for omitted and past-end anchors', async () => {
  244. const ctx = await composed()
  245. const source = liveAgent(ctx, 'session-tail', 2, 'open')
  246. const proxy = remote(ctx)
  247. const expectedTypes = [
  248. 'turn/start', 'user/message', 'turn/end',
  249. 'turn/start', 'user/message', 'turn/end',
  250. 'session/end-seed',
  251. ]
  252. const omitted = await proxy.fork(request({ sessionId: source.id }))
  253. expect(omitted.ok).toBe(true)
  254. if (omitted.ok) {
  255. expect(ctx.sessions.get(omitted.value.sessionId)?.snapshotEvents().map(event => event.type))
  256. .toEqual(expectedTypes)
  257. }
  258. const pastEnd = await proxy.fork(request({ sessionId: source.id, atSeq: 999 }))
  259. expect(pastEnd.ok).toBe(true)
  260. if (pastEnd.ok) {
  261. expect(ctx.sessions.get(pastEnd.value.sessionId)?.snapshotEvents().map(event => event.type))
  262. .toEqual(expectedTypes)
  263. }
  264. await ctx.fiber.dispose()
  265. })
  266. it('rejects invalid fork anchors before reading or creating a Session', async () => {
  267. const ctx = await composed()
  268. const proxy = remote(ctx)
  269. for (const atSeq of [-1, 0.5]) {
  270. await expect(proxy.fork(request({ sessionId: sid('missing'), atSeq })))
  271. .resolves.toMatchObject({ ok: false, error: { code: 'gateway/bad-request' } })
  272. }
  273. expect(ctx.sessions.list()).toEqual([])
  274. await ctx.fiber.dispose()
  275. })
  276. it('cuts through an aborted turn: stopped is closed, not open', async () => {
  277. const ctx = await composed()
  278. const source = liveAgent(ctx, 'session-aborted', 1, 'aborted')
  279. // What a stopped message's fork button anchors on: the frozen node sits
  280. // one event before its turn/end, floored client-side to that event's seq.
  281. const anchor = (source.snapshotEvents().at(-1)?.seq ?? 0) - 1
  282. const response = await remote(ctx).fork(request({ sessionId: source.id, atSeq: anchor }))
  283. expect(response.ok).toBe(true)
  284. if (!response.ok) return
  285. expect(ctx.sessions.get(response.value.sessionId)?.snapshotEvents().map(event => event.type)).toEqual([
  286. 'turn/start', 'user/message', 'turn/end',
  287. 'turn/start', 'user/message', 'turn/end',
  288. 'session/end-seed',
  289. ])
  290. await ctx.fiber.dispose()
  291. })
  292. it('rejects an in-log anchor whose turn is still open', async () => {
  293. const ctx = await composed()
  294. const source = liveAgent(ctx, 'session-open', 1, 'open')
  295. const anchor = source.snapshotEvents().at(-1)?.seq ?? 0
  296. const response = await remote(ctx).fork(request({ sessionId: source.id, atSeq: anchor }))
  297. expect(response).toMatchObject({
  298. ok: false,
  299. error: { code: 'session/fork-unavailable', details: { sessionId: source.id } },
  300. })
  301. if (!response.ok) expect(response.error.message).toMatch(/has not completed/)
  302. await ctx.fiber.dispose()
  303. })
  304. it.each(['next-turn', 'next-step', null] as const)('inherits model settings before %s inbox changes', async (target) => {
  305. const ctx = await composed()
  306. const source = liveAgent(ctx, 'session-routed', 1)
  307. source.append('request/header', {
  308. header: {
  309. config: {
  310. provider: 'inherited-provider',
  311. model: 'inherited-model',
  312. reasoningEffort: ReasoningEffortId('high'),
  313. },
  314. },
  315. reason: 'initial',
  316. })
  317. const inherited = source.snapshotEvents()
  318. if (target !== null) {
  319. source.append('agent/inbox/spliced', {
  320. target, start: 0,
  321. inserted: [createUserMessage({
  322. content: [{ type: 'text', text: 'next input' }], source: { kind: 'user' },
  323. })],
  324. })
  325. source.append('session/title', {
  326. title: 'Title after inbox insertion', messageSeqs: [], source: { kind: 'user' },
  327. })
  328. source.append('request/header', {
  329. header: { config: { provider: 'later-provider', model: 'later-model' } },
  330. reason: 'change',
  331. })
  332. }
  333. const response = await remote(ctx).fork(request({ sessionId: source.id }))
  334. expect(response.ok).toBe(true)
  335. if (!response.ok) return
  336. const child = ctx.agents.get(response.value.sessionId)
  337. if (child === undefined) throw new Error('fork did not publish the child agent')
  338. expect(child.session.snapshotEvents().slice(0, child.session.inheritedEventCount)).toEqual(inherited)
  339. const assembly = await child.ctx.systemPrompt.assemble()
  340. expect(assembly.variables).toMatchObject({
  341. provider: 'inherited-provider',
  342. model: 'inherited-model',
  343. })
  344. const fallback: LlmCallConfig = { provider: 'default-provider', model: 'default-model' }
  345. await expect(agentEvents(child.ctx, child).waterfall(
  346. 'agent/request', { turn: 1, step: 0, signal: new AbortController().signal }, () => Promise.resolve(fallback),
  347. )).resolves.toMatchObject({
  348. provider: 'inherited-provider',
  349. model: 'inherited-model',
  350. reasoningEffort: 'high',
  351. })
  352. await ctx.fiber.dispose()
  353. })
  354. })