session-fork.host.spec.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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 { createUserMessage, ReasoningEffortId } from '@deepseek-ai/dsh-llm'
  7. import type { LlmCallConfig } from '@deepseek-ai/dsh-llm'
  8. import SessionStore from '@deepseek-ai/dsh-session'
  9. import type { Session, SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session'
  10. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  11. import type { Workspace } from '@deepseek-ai/dsh-workspace'
  12. import { createSessionTestRemote } from './test-remote.ts'
  13. const sid = (id: string): SessionId => id as SessionId
  14. function request<P>(payload: P): P {
  15. return payload
  16. }
  17. async function composed(workspaces: readonly Workspace[] = []): Promise<Context> {
  18. const ctx = new Context()
  19. await ctx.plugin(SessionStore)
  20. await ctx.plugin(SystemPrompt, { persona: '' })
  21. await ctx.plugin(AgentRegistry)
  22. ctx.provide('workspaceRegistry', { list: () => workspaces } as never)
  23. ctx.agents.setFactory({
  24. createAgent: async (ownerCtx: Context, options: CreateAgentOptions): Promise<AgentHandle> => {
  25. const session = ctx.sessions.create(options.sessionId, {
  26. ...options.seed === undefined ? {} : { seed: [...options.seed] },
  27. ...options.meta === undefined ? {} : { meta: options.meta },
  28. })
  29. const agent = {} as Agent
  30. const agentCtx = ownerCtx.extend({ agent })
  31. Object.assign(agent, { id: session.id, session, status: 'idle', ctx: agentCtx })
  32. await options.setup?.(agentCtx)
  33. ctx.agents.register(agent)
  34. return { agent, dispose: () => Promise.resolve() }
  35. },
  36. resume: () => Promise.reject(new Error('fork test sources are live')),
  37. })
  38. return ctx
  39. }
  40. /** Tail turn appended after the completed ones: left open, or closed as aborted (a stopped turn). */
  41. type Tail = 'none' | 'open' | 'aborted'
  42. function liveAgent(
  43. ctx: Context,
  44. id: string,
  45. turns: number,
  46. tail: Tail = 'none',
  47. lineage: { parentSession?: SessionId; origin?: 'subagent' } = {},
  48. ): Session {
  49. const session = ctx.sessions.create(sid(id), { meta: { cwd: '/proj', ...lineage } })
  50. for (let turn = 1; turn <= turns; turn++) {
  51. session.append('turn/start', { turn })
  52. session.append('user/message', createUserMessage({
  53. content: [{ type: 'text', text: `prompt ${String(turn)}` }],
  54. source: { kind: 'user' },
  55. }), { surfaceOp: 'append' })
  56. session.append('turn/end', { turn, reason: { kind: 'completed' } })
  57. }
  58. if (tail !== 'none') {
  59. session.append('turn/start', { turn: turns + 1 })
  60. session.append('user/message', createUserMessage({
  61. content: [{ type: 'text', text: 'open prompt' }],
  62. source: { kind: 'user' },
  63. }), { surfaceOp: 'append' })
  64. if (tail === 'aborted') session.append('turn/end', {
  65. turn: turns + 1,
  66. reason: { kind: 'aborted', reason: { kind: 'user' } },
  67. })
  68. }
  69. ctx.agents.register({ id: session.id, session, status: 'idle', ctx } as Agent)
  70. return session
  71. }
  72. const remote = (ctx: Context) => createSessionTestRemote(ctx, {
  73. defaultModelSelection: () => ({ provider: 'default-provider', model: 'default-model' }),
  74. cwd: '/tmp',
  75. })
  76. describe('sessions.fork', () => {
  77. it('cuts at the anchored completed turn and records lineage and cwd', async () => {
  78. const ctx = await composed()
  79. const source = liveAgent(ctx, 'session-source', 2)
  80. const response = await remote(ctx).fork(request({ sessionId: source.id, atSeq: 1 }))
  81. expect(response.ok).toBe(true)
  82. if (!response.ok) return
  83. const child = ctx.sessions.get(response.value.sessionId)
  84. expect(child?.events.map(event => event.type)).toEqual([
  85. 'turn/start', 'user/message', 'turn/end', 'session/end-seed',
  86. ])
  87. expect(child?.header.parentSession).toBe(source.id)
  88. expect(child?.header.cwd).toBe('/proj')
  89. await ctx.fiber.dispose()
  90. })
  91. it('attaches a subagent fork to its nearest workspace-owning ancestor', async () => {
  92. const accounted: SessionId[] = []
  93. const attachSession = vi.fn<(sessionId: SessionId) => Promise<void>>()
  94. .mockResolvedValue(undefined)
  95. const workspace = {
  96. sessionIds: accounted,
  97. attachSession,
  98. } as unknown as Workspace
  99. const ctx = await composed([workspace])
  100. const owner = liveAgent(ctx, 'session-owner', 1)
  101. accounted.push(owner.id)
  102. const child = liveAgent(ctx, 'session-child', 1, 'none', {
  103. parentSession: owner.id,
  104. origin: 'subagent',
  105. })
  106. const grandchild = liveAgent(ctx, 'session-grandchild', 1, 'none', {
  107. parentSession: child.id,
  108. origin: 'subagent',
  109. })
  110. ctx.provide('sessionQuery', {
  111. traceSession: vi.fn(() => Promise.resolve({
  112. target: { header: grandchild.header, live: true, persisted: false },
  113. ancestors: [
  114. { header: child.header, live: true, persisted: false },
  115. { header: owner.header, live: true, persisted: false },
  116. ],
  117. descendants: [],
  118. complete: true,
  119. root: { header: owner.header, live: true, persisted: false },
  120. })),
  121. } as never)
  122. const response = await remote(ctx).fork(request({ sessionId: grandchild.id }))
  123. expect(response.ok).toBe(true)
  124. if (!response.ok) return
  125. expect(attachSession).toHaveBeenCalledWith(response.value.sessionId)
  126. expect(ctx.sessions.get(response.value.sessionId)?.header).toMatchObject({
  127. parentSession: grandchild.id,
  128. cwd: '/proj',
  129. })
  130. expect(ctx.sessions.get(response.value.sessionId)?.header.origin).toBeUndefined()
  131. await ctx.fiber.dispose()
  132. })
  133. it('forks a persisted subagent without resuming its Agent', async () => {
  134. const ctx = await composed()
  135. const sourceId = sid('session-cold-subagent')
  136. const parentId = sid('session-cold-parent')
  137. const header: SessionHeader = {
  138. version: 0,
  139. id: sourceId,
  140. createdAt: 1,
  141. cwd: '/proj',
  142. parentSession: parentId,
  143. origin: 'subagent',
  144. }
  145. const events = [
  146. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  147. {
  148. type: 'user/message',
  149. seq: 1,
  150. time: 2,
  151. data: createUserMessage({ content: [{ type: 'text', text: 'work' }], source: { kind: 'user' } }),
  152. surfaceOp: 'append',
  153. },
  154. { type: 'turn/end', seq: 2, time: 3, data: { turn: 1, reason: { kind: 'completed' } } },
  155. ] as SessionEvent[]
  156. ctx.provide('sessionPersistence', {
  157. list: () => Promise.resolve([header]),
  158. inspect: () => Promise.resolve({ meta: header, events }),
  159. } as never)
  160. ctx.provide('sessionQuery', {
  161. traceSession: () => Promise.resolve({
  162. target: { header, live: false, persisted: true },
  163. ancestors: [],
  164. descendants: [],
  165. complete: true,
  166. root: { header, live: false, persisted: true },
  167. }),
  168. } as never)
  169. const resume = vi.spyOn(ctx.agents, 'resume')
  170. const response = await remote(ctx).fork(request({ sessionId: sourceId }))
  171. expect(response.ok).toBe(true)
  172. if (!response.ok) return
  173. expect(resume).not.toHaveBeenCalled()
  174. expect(ctx.agents.get(sourceId)).toBeUndefined()
  175. expect(ctx.sessions.get(response.value.sessionId)?.header).toMatchObject({
  176. parentSession: sourceId,
  177. cwd: '/proj',
  178. })
  179. expect(ctx.sessions.get(response.value.sessionId)?.header.origin).toBeUndefined()
  180. await ctx.fiber.dispose()
  181. })
  182. it('uses the last completed turn only for omitted and past-end anchors', async () => {
  183. const ctx = await composed()
  184. const source = liveAgent(ctx, 'session-tail', 2, 'open')
  185. const proxy = remote(ctx)
  186. const expectedTypes = [
  187. 'turn/start', 'user/message', 'turn/end',
  188. 'turn/start', 'user/message', 'turn/end',
  189. 'session/end-seed',
  190. ]
  191. const omitted = await proxy.fork(request({ sessionId: source.id }))
  192. expect(omitted.ok).toBe(true)
  193. if (omitted.ok) {
  194. expect(ctx.sessions.get(omitted.value.sessionId)?.events.map(event => event.type))
  195. .toEqual(expectedTypes)
  196. }
  197. const pastEnd = await proxy.fork(request({ sessionId: source.id, atSeq: 999 }))
  198. expect(pastEnd.ok).toBe(true)
  199. if (pastEnd.ok) {
  200. expect(ctx.sessions.get(pastEnd.value.sessionId)?.events.map(event => event.type))
  201. .toEqual(expectedTypes)
  202. }
  203. await ctx.fiber.dispose()
  204. })
  205. it('rejects invalid fork anchors before reading or creating a Session', async () => {
  206. const ctx = await composed()
  207. const proxy = remote(ctx)
  208. for (const atSeq of [-1, 0.5]) {
  209. await expect(proxy.fork(request({ sessionId: sid('missing'), atSeq })))
  210. .resolves.toMatchObject({ ok: false, error: { code: 'bad-request' } })
  211. }
  212. expect(ctx.sessions.list()).toEqual([])
  213. await ctx.fiber.dispose()
  214. })
  215. it('cuts through an aborted turn: stopped is closed, not open', async () => {
  216. const ctx = await composed()
  217. const source = liveAgent(ctx, 'session-aborted', 1, 'aborted')
  218. // What a stopped message's fork button anchors on: the frozen node sits
  219. // one event before its turn/end, floored client-side to that event's seq.
  220. const anchor = (source.events.at(-1)?.seq ?? 0) - 1
  221. const response = await remote(ctx).fork(request({ sessionId: source.id, atSeq: anchor }))
  222. expect(response.ok).toBe(true)
  223. if (!response.ok) return
  224. expect(ctx.sessions.get(response.value.sessionId)?.events.map(event => event.type)).toEqual([
  225. 'turn/start', 'user/message', 'turn/end',
  226. 'turn/start', 'user/message', 'turn/end',
  227. 'session/end-seed',
  228. ])
  229. await ctx.fiber.dispose()
  230. })
  231. it('rejects an in-log anchor whose turn is still open', async () => {
  232. const ctx = await composed()
  233. const source = liveAgent(ctx, 'session-open', 1, 'open')
  234. const anchor = source.events.at(-1)?.seq ?? 0
  235. const response = await remote(ctx).fork(request({ sessionId: source.id, atSeq: anchor }))
  236. expect(response).toMatchObject({
  237. ok: false,
  238. error: { code: 'fork-unavailable', details: { sessionId: source.id } },
  239. })
  240. if (!response.ok) expect(response.error.message).toMatch(/has not completed/)
  241. await ctx.fiber.dispose()
  242. })
  243. it('installs the latest logged model selection before the child can run', async () => {
  244. const ctx = await composed()
  245. const source = liveAgent(ctx, 'session-routed', 1)
  246. source.append('request/header', {
  247. header: {
  248. config: {
  249. provider: 'inherited-provider',
  250. model: 'inherited-model',
  251. reasoningEffort: ReasoningEffortId('high'),
  252. },
  253. },
  254. reason: 'initial',
  255. })
  256. const response = await remote(ctx).fork(request({ sessionId: source.id }))
  257. expect(response.ok).toBe(true)
  258. if (!response.ok) return
  259. const child = ctx.agents.get(response.value.sessionId)
  260. if (child === undefined) throw new Error('fork did not publish the child agent')
  261. const assembly = await child.ctx.systemPrompt.assemble()
  262. expect(assembly.variables).toMatchObject({
  263. provider: 'inherited-provider',
  264. model: 'inherited-model',
  265. })
  266. const fallback: LlmCallConfig = { provider: 'default-provider', model: 'default-model' }
  267. await expect(agentEvents(child.ctx, child).waterfall(
  268. 'agent/request', { turn: 1, step: 0, signal: new AbortController().signal }, () => Promise.resolve(fallback),
  269. )).resolves.toMatchObject({
  270. provider: 'inherited-provider',
  271. model: 'inherited-model',
  272. reasoningEffort: 'high',
  273. })
  274. await ctx.fiber.dispose()
  275. })
  276. })