session-fork.host.spec.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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. if (anchor === 'message' || anchor === 'turn-end') {
  102. source.followup(message('B'))
  103. await source.whenIdle()
  104. } else {
  105. source.inbox.append('next-turn', message('B'))
  106. }
  107. const original = source.session.snapshotEvents()
  108. const atSeq = anchor === 'omitted' ? undefined
  109. : anchor === 'past-end' ? source.session.seq + 1
  110. : anchor === 'turn-end' ? boundary
  111. : original.find(event => event.type === 'assistant/message')!.seq
  112. const response = await createSessionTestRemote(ctx, {
  113. defaultModelSelection: () => ({ provider: 'mock', model: 'mock' }), cwd: '/tmp',
  114. }).fork({ sessionId: source.id, ...(atSeq === undefined ? {} : { atSeq }) })
  115. if (!response.ok) throw response.error
  116. const child = ctx.agents.get(response.value.sessionId)!
  117. const requestCount = adapter.requests.length
  118. child.followup(message('C'))
  119. await child.whenIdle()
  120. const userTexts = child.session.deriveMessages().flatMap(item => item.role === 'user'
  121. ? item.content.flatMap(part => part.type === 'text' ? [part.text] : []) : [])
  122. expect(userTexts).toEqual(['A', 'C'])
  123. expect(adapter.requests.slice(requestCount)).toHaveLength(1)
  124. expect(child.session.inheritedEventCount).toBe(boundary + 1)
  125. expect(source.session.snapshotEvents()).toEqual(original)
  126. } finally {
  127. await ctx.fiber.dispose()
  128. }
  129. },
  130. )
  131. it('cuts at the anchored completed turn and records lineage and cwd', async () => {
  132. const ctx = await composed()
  133. const source = liveAgent(ctx, 'session-source', 2)
  134. const response = await remote(ctx).fork(request({ sessionId: source.id, atSeq: 1 }))
  135. expect(response.ok ? null : response.error).toBeNull()
  136. if (!response.ok) return
  137. const child = ctx.sessions.get(response.value.sessionId)
  138. expect(child?.snapshotEvents().map(event => event.type)).toEqual([
  139. 'turn/start', 'user/message', 'turn/end', 'session/end-seed',
  140. ])
  141. expect(child?.header.parentSession).toBe(source.id)
  142. expect(child?.header.cwd).toBe('/proj')
  143. await ctx.fiber.dispose()
  144. })
  145. it('attaches a subagent fork to its nearest workspace-owning ancestor', async () => {
  146. const accounted: SessionId[] = []
  147. const attachSession = vi.fn<(sessionId: SessionId) => Promise<void>>()
  148. .mockResolvedValue(undefined)
  149. const workspace = {
  150. sessionIds: accounted,
  151. attachSession,
  152. } as unknown as Workspace
  153. const ctx = await composed([workspace])
  154. const owner = liveAgent(ctx, 'session-owner', 1)
  155. accounted.push(owner.id)
  156. const child = liveAgent(ctx, 'session-child', 1, 'none', {
  157. parentSession: owner.id,
  158. origin: 'subagent',
  159. })
  160. const grandchild = liveAgent(ctx, 'session-grandchild', 1, 'none', {
  161. parentSession: child.id,
  162. origin: 'subagent',
  163. })
  164. vi.spyOn(ctx.sessionQuery, 'traceSession').mockResolvedValue({
  165. target: { header: grandchild.header, live: true, persisted: false },
  166. ancestors: [
  167. { header: child.header, live: true, persisted: false },
  168. { header: owner.header, live: true, persisted: false },
  169. ],
  170. descendants: [],
  171. complete: true,
  172. root: { header: owner.header, live: true, persisted: false },
  173. })
  174. const response = await remote(ctx).fork(request({ sessionId: grandchild.id }))
  175. expect(response.ok).toBe(true)
  176. if (!response.ok) return
  177. expect(attachSession).toHaveBeenCalledWith(response.value.sessionId)
  178. expect(ctx.sessions.get(response.value.sessionId)?.header).toMatchObject({
  179. parentSession: grandchild.id,
  180. cwd: '/proj',
  181. })
  182. expect(ctx.sessions.get(response.value.sessionId)?.header.origin).toBeUndefined()
  183. await ctx.fiber.dispose()
  184. })
  185. it('forks a persisted subagent without resuming its Agent', async () => {
  186. const ctx = await composed()
  187. const sourceId = sid('session-cold-subagent')
  188. const parentId = sid('session-cold-parent')
  189. const header: SessionHeader = {
  190. version: SESSION_FORMAT_VERSION,
  191. id: sourceId,
  192. createdAt: 1,
  193. cwd: '/proj',
  194. parentSession: parentId,
  195. isSeeded: false,
  196. origin: 'subagent',
  197. }
  198. const events = [
  199. {
  200. type: 'turn/start',
  201. seq: SessionSeq(0),
  202. time: 1,
  203. data: {
  204. turn: 1,
  205. trigger: { kind: 'message', source: { kind: 'user' } },
  206. } as SessionEvent<'turn/start'>['data'],
  207. },
  208. {
  209. type: 'user/message',
  210. seq: SessionSeq(1),
  211. time: 2,
  212. data: createUserMessage({ content: [{ type: 'text', text: 'work' }], source: { kind: 'user' } }),
  213. surfaceOp: 'append',
  214. },
  215. { type: 'turn/end', seq: SessionSeq(2), time: 3, data: { turn: 1, reason: { kind: 'completed' } } },
  216. ] satisfies SessionEvent[]
  217. ctx.provide('sessionPersistence', testSessionPersistence(ctx, {
  218. list: () => Promise.resolve([header]),
  219. inspect: () => Promise.resolve({
  220. meta: header,
  221. inheritedEventCount: SessionLogOffset(0),
  222. events,
  223. }),
  224. }) as never)
  225. const resume = vi.spyOn(ctx.agents, 'resume')
  226. const response = await remote(ctx).fork(request({ sessionId: sourceId }))
  227. expect(response.ok).toBe(true)
  228. if (!response.ok) return
  229. expect(resume).not.toHaveBeenCalled()
  230. expect(ctx.agents.get(sourceId)).toBeUndefined()
  231. expect(ctx.sessions.get(response.value.sessionId)?.header).toMatchObject({
  232. parentSession: sourceId,
  233. cwd: '/proj',
  234. })
  235. expect(ctx.sessions.get(response.value.sessionId)?.header.origin).toBeUndefined()
  236. await ctx.fiber.dispose()
  237. })
  238. it('uses the last completed turn only for omitted and past-end anchors', async () => {
  239. const ctx = await composed()
  240. const source = liveAgent(ctx, 'session-tail', 2, 'open')
  241. const proxy = remote(ctx)
  242. const expectedTypes = [
  243. 'turn/start', 'user/message', 'turn/end',
  244. 'turn/start', 'user/message', 'turn/end',
  245. 'session/end-seed',
  246. ]
  247. const omitted = await proxy.fork(request({ sessionId: source.id }))
  248. expect(omitted.ok).toBe(true)
  249. if (omitted.ok) {
  250. expect(ctx.sessions.get(omitted.value.sessionId)?.snapshotEvents().map(event => event.type))
  251. .toEqual(expectedTypes)
  252. }
  253. const pastEnd = await proxy.fork(request({ sessionId: source.id, atSeq: 999 }))
  254. expect(pastEnd.ok).toBe(true)
  255. if (pastEnd.ok) {
  256. expect(ctx.sessions.get(pastEnd.value.sessionId)?.snapshotEvents().map(event => event.type))
  257. .toEqual(expectedTypes)
  258. }
  259. await ctx.fiber.dispose()
  260. })
  261. it('rejects invalid fork anchors before reading or creating a Session', async () => {
  262. const ctx = await composed()
  263. const proxy = remote(ctx)
  264. for (const atSeq of [-1, 0.5]) {
  265. await expect(proxy.fork(request({ sessionId: sid('missing'), atSeq })))
  266. .resolves.toMatchObject({ ok: false, error: { code: 'gateway/bad-request' } })
  267. }
  268. expect(ctx.sessions.list()).toEqual([])
  269. await ctx.fiber.dispose()
  270. })
  271. it('cuts through an aborted turn: stopped is closed, not open', async () => {
  272. const ctx = await composed()
  273. const source = liveAgent(ctx, 'session-aborted', 1, 'aborted')
  274. // What a stopped message's fork button anchors on: the frozen node sits
  275. // one event before its turn/end, floored client-side to that event's seq.
  276. const anchor = (source.snapshotEvents().at(-1)?.seq ?? 0) - 1
  277. const response = await remote(ctx).fork(request({ sessionId: source.id, atSeq: anchor }))
  278. expect(response.ok).toBe(true)
  279. if (!response.ok) return
  280. expect(ctx.sessions.get(response.value.sessionId)?.snapshotEvents().map(event => event.type)).toEqual([
  281. 'turn/start', 'user/message', 'turn/end',
  282. 'turn/start', 'user/message', 'turn/end',
  283. 'session/end-seed',
  284. ])
  285. await ctx.fiber.dispose()
  286. })
  287. it('rejects an in-log anchor whose turn is still open', async () => {
  288. const ctx = await composed()
  289. const source = liveAgent(ctx, 'session-open', 1, 'open')
  290. const anchor = source.snapshotEvents().at(-1)?.seq ?? 0
  291. const response = await remote(ctx).fork(request({ sessionId: source.id, atSeq: anchor }))
  292. expect(response).toMatchObject({
  293. ok: false,
  294. error: { code: 'session/fork-unavailable', details: { sessionId: source.id } },
  295. })
  296. if (!response.ok) expect(response.error.message).toMatch(/has not completed/)
  297. await ctx.fiber.dispose()
  298. })
  299. it('inherits model selection through the completed turn and excludes later changes', async () => {
  300. const ctx = await composed()
  301. const source = liveAgent(ctx, 'session-routed', 0)
  302. source.append('turn/start', { turn: 1 })
  303. source.append('request/header', {
  304. header: {
  305. config: {
  306. provider: 'inherited-provider',
  307. model: 'inherited-model',
  308. reasoningEffort: ReasoningEffortId('high'),
  309. },
  310. },
  311. reason: 'initial',
  312. })
  313. const boundary = source.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  314. const inherited = source.snapshotEvents()
  315. source.append('session/title', {
  316. title: 'Title after the selected turn', messageSeqs: [], source: { kind: 'user' },
  317. })
  318. source.append('turn/start', { turn: 2 })
  319. source.append('request/header', {
  320. header: { config: { provider: 'later-provider', model: 'later-model' } },
  321. reason: 'change',
  322. })
  323. source.append('turn/end', { turn: 2, reason: { kind: 'completed' } })
  324. const response = await remote(ctx).fork(request({ sessionId: source.id, atSeq: boundary.seq }))
  325. expect(response.ok).toBe(true)
  326. if (!response.ok) return
  327. const child = ctx.agents.get(response.value.sessionId)
  328. if (child === undefined) throw new Error('fork did not publish the child agent')
  329. expect(child.session.snapshotEvents().slice(0, child.session.inheritedEventCount)).toEqual(inherited)
  330. const assembly = await child.ctx.systemPrompt.assemble()
  331. expect(assembly.variables).toMatchObject({
  332. provider: 'inherited-provider',
  333. model: 'inherited-model',
  334. })
  335. const fallback: LlmCallConfig = { provider: 'default-provider', model: 'default-model' }
  336. await expect(agentEvents(child.ctx, child).waterfall(
  337. 'agent/request', { turn: 1, step: 0, signal: new AbortController().signal }, () => Promise.resolve(fallback),
  338. )).resolves.toMatchObject({
  339. provider: 'inherited-provider',
  340. model: 'inherited-model',
  341. reasoningEffort: 'high',
  342. })
  343. await ctx.fiber.dispose()
  344. })
  345. })