session-fork.host.spec.ts 12 KB

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