session-fork.host.spec.ts 11 KB

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