api-proxy-cold.spec.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. /**
  2. * Cold-session and degenerate-composition paths of the host ApiProxy:
  3. * metadata-only listing, Agent-free history reads, subagent ownership
  4. * isolation, and prompt failure mapping.
  5. */
  6. import { mkdtempSync, writeFileSync, utimesSync } from 'node:fs'
  7. import { tmpdir } from 'node:os'
  8. import { join } from 'node:path'
  9. import { describe, expect, it, vi } from 'vitest'
  10. import { Context } from 'cordis'
  11. import SessionStore from '@deepseek-ai/dsh-session'
  12. import AgentRegistry, { InboxItemId } from '@deepseek-ai/dsh-agent'
  13. import type { Agent } from '@deepseek-ai/dsh-agent'
  14. import UserInteractionService from '@deepseek-ai/dsh-user-interaction'
  15. import type { SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session'
  16. import type { RpcRequest } from '@deepseek-ai/dsh-host-apiproxy/api/rpc'
  17. import { RpcId } from '@deepseek-ai/dsh-host-apiproxy/api/rpc'
  18. import { createApiProxy } from '@deepseek-ai/dsh-host-apiproxy'
  19. const sid = (id: string): SessionId => id as SessionId
  20. let nextRpc = 1
  21. function request<P>(payload: P): RpcRequest<P> {
  22. return { rpcId: RpcId(`cold-${String(nextRpc++)}`), payload }
  23. }
  24. function header(id: string, createdAt: number, extra: Partial<SessionHeader> = {}): SessionHeader {
  25. return { version: 0, id: sid(id), createdAt, cwd: '/proj', ...extra }
  26. }
  27. describe('sessions.list cold merge', () => {
  28. it('summarizes unattached sessions: log mtime, locate-less and vanished-log createdAt fallbacks, lineage', async () => {
  29. const ctx = new Context()
  30. await ctx.plugin(SessionStore)
  31. await ctx.plugin(UserInteractionService)
  32. const root = mkdtempSync(join(tmpdir(), 'dsh-cold-'))
  33. const logPath = join(root, 'a.log')
  34. writeFileSync(logPath, 'log-bytes')
  35. utimesSync(logPath, 5000, 5000) // mtime 5_000_000 ms — newer than every createdAt below
  36. const metas = [
  37. header('session-a', 1000),
  38. header('session-b', 2000, { parentSession: sid('session-parent'), origin: 'subagent' }),
  39. header('session-c', 1500),
  40. ]
  41. // Structural fake of the persistence face list() consumes: list + locate.
  42. // locate: a real per-session file (mtime wins), a backend without one
  43. // (SQLite shape → createdAt), and a path whose file vanished (stat ENOENT
  44. // → createdAt).
  45. ctx.provide('sessionPersistence', {
  46. list: () => Promise.resolve(metas),
  47. locate: (meta: SessionHeader) => {
  48. if (meta.id === sid('session-a')) return { kind: 'jsonl', path: logPath }
  49. if (meta.id === sid('session-c')) return { kind: 'jsonl', path: join(root, 'vanished.log') }
  50. return undefined
  51. },
  52. })
  53. const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp', workspaceRoot: '/tmp' })
  54. const response = await api.sessions.list(request({}))
  55. expect(response.result.ok).toBe(true)
  56. if (!response.result.ok) throw new Error('unreachable')
  57. const items = response.result.value.items
  58. expect(items.map(item => item.sessionId)).toEqual(['session-a', 'session-b', 'session-c'])
  59. const [a, b, c] = items
  60. expect(a?.updatedAt).toBeCloseTo(5_000_000, -3)
  61. expect(a?.running).toBe(false)
  62. // Cold summaries are never blank: lazy persistence keeps never-appended
  63. // sessions out of list(), so a listed session necessarily has events.
  64. expect(items.every(item => !item.blank)).toBe(true)
  65. expect(a?.cwd).toBe('/proj')
  66. expect(a?.parentSessionId).toBeUndefined()
  67. expect(b?.updatedAt).toBe(2000)
  68. expect(b?.parentSessionId).toBe('session-parent')
  69. expect(b?.origin).toBe('subagent')
  70. expect(c?.updatedAt).toBe(1500)
  71. })
  72. })
  73. describe('attached updatedAt excludes end-seed', () => {
  74. it('reports the last real work, not the pickup, so a resumed-untouched session does not float', async () => {
  75. const ctx = new Context()
  76. await ctx.plugin(SessionStore)
  77. await ctx.plugin(UserInteractionService)
  78. await ctx.plugin(AgentRegistry)
  79. const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp', workspaceRoot: '/tmp' })
  80. // Old work, resumed just now: the log tail would report the pickup.
  81. const worked = 1_000_000
  82. const resumed = ctx.sessions.create(sid('resumed-untouched'), {
  83. seed: [
  84. { type: 'turn/start', seq: 0, time: worked, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  85. { type: 'turn/end', seq: 1, time: worked, data: { turn: 1, reason: { kind: 'completed' } } },
  86. ],
  87. meta: { cwd: '/proj', createdAt: 500 },
  88. })
  89. ctx.agents.register({ id: resumed.id, session: resumed, status: 'idle', ctx } as Agent)
  90. const boundary = resumed.events.at(-1)
  91. expect(boundary?.type).toBe('session/end-seed')
  92. expect(boundary?.time).toBeGreaterThan(worked)
  93. const listed = await api.sessions.list(request({}))
  94. if (!listed.result.ok) throw new Error('list failed')
  95. const summary = listed.result.value.items.find(item => item.sessionId === 'resumed-untouched')
  96. expect(summary?.updatedAt).toBe(worked)
  97. // Real work appended after end-seed does move it.
  98. resumed.append('turn/start', { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } })
  99. const after = await api.sessions.list(request({}))
  100. if (!after.result.ok) throw new Error('list failed')
  101. const moved = after.result.value.items.find(item => item.sessionId === 'resumed-untouched')
  102. expect(moved?.updatedAt).toBeGreaterThan(worked)
  103. })
  104. })
  105. describe('subagent ownership fence', () => {
  106. it('reads a cold child without an Agent and rejects generic resume or adoption', async () => {
  107. const ctx = new Context()
  108. await ctx.plugin(SessionStore)
  109. await ctx.plugin(AgentRegistry)
  110. await ctx.plugin(UserInteractionService)
  111. const sessionId = sid('session-child')
  112. const meta = header('session-child', 1000, {
  113. parentSession: sid('session-parent'),
  114. seedLength: 0,
  115. })
  116. const events = [
  117. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  118. {
  119. type: 'user/message',
  120. seq: 1,
  121. time: 2,
  122. data: { content: [{ type: 'text', text: 'work' }], source: { kind: 'user' } },
  123. surfaceOp: 'append',
  124. },
  125. {
  126. type: 'subagent/descriptor',
  127. seq: 2,
  128. time: 3,
  129. data: { version: 2, mode: 'continuable', provider: 'spawn', label: 'child' },
  130. },
  131. { type: 'turn/end', seq: 3, time: 4, data: { turn: 1, reason: { kind: 'completed' } } },
  132. ] as SessionEvent[]
  133. const inspect = vi.fn(() => Promise.resolve({ meta, events }))
  134. ctx.provide('sessionPersistence', {
  135. list: () => Promise.resolve([meta]),
  136. inspect,
  137. locate: () => undefined,
  138. } as never)
  139. const resume = vi.spyOn(ctx.agents, 'resume')
  140. const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp', workspaceRoot: '/tmp' })
  141. const history = await api.sessions.history(request({ sessionId }))
  142. expect(history.result.ok).toBe(true)
  143. if (history.result.ok) {
  144. expect(history.result.value.events.map(entry => entry.event.type)).toEqual(events.map(event => event.type))
  145. }
  146. expect(ctx.agents.get(sessionId)).toBeUndefined()
  147. const prompt = await api.sessions.prompt(request({
  148. sessionId,
  149. mode: 'queue',
  150. content: [{ type: 'text', text: 'follow up' }],
  151. }))
  152. expect(prompt.result.ok).toBe(false)
  153. if (!prompt.result.ok) {
  154. expect(prompt.result.error).toMatchObject({
  155. code: 'agent-busy',
  156. details: { reason: 'use subagent delivery for this child session' },
  157. })
  158. }
  159. const create = await api.sessions.create(request({ sessionId, cwd: '/proj' }))
  160. expect(create.result.ok).toBe(false)
  161. if (!create.result.ok) expect(create.result.error.code).toBe('agent-busy')
  162. expect(resume).not.toHaveBeenCalled()
  163. expect(ctx.agents.get(sessionId)).toBeUndefined()
  164. expect(inspect).toHaveBeenCalledTimes(3)
  165. })
  166. it('rejects origin-marked and runtime-owned live children from generic controls', async () => {
  167. const ctx = new Context()
  168. await ctx.plugin(SessionStore)
  169. await ctx.plugin(AgentRegistry)
  170. await ctx.plugin(UserInteractionService)
  171. const parentSession = ctx.sessions.create(sid('session-parent'), { meta: { cwd: '/proj' } })
  172. const parent = { id: parentSession.id, session: parentSession, status: 'idle', ctx } as Agent
  173. ctx.agents.register(parent)
  174. const originSession = ctx.sessions.create(sid('session-origin-child'), {
  175. meta: { cwd: '/proj', parentSession: parent.id, origin: 'subagent' },
  176. })
  177. const cancel = vi.fn()
  178. const updateInbox = vi.fn(() => 'applied' as const)
  179. const originChild = {
  180. id: originSession.id,
  181. session: originSession,
  182. status: 'idle',
  183. ctx,
  184. cancel,
  185. updateInbox,
  186. } as unknown as Agent
  187. ctx.agents.register(originChild)
  188. const startingSession = ctx.sessions.create(sid('session-starting-child'), {
  189. meta: { cwd: '/proj', parentSession: parent.id },
  190. })
  191. const startingChild = { id: startingSession.id, session: startingSession, status: 'idle', ctx } as Agent
  192. ctx.agents.enter(startingChild, parent)
  193. const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp', workspaceRoot: '/tmp' })
  194. const stopped = await api.sessions.cancel(request({ sessionId: originChild.id }))
  195. expect(stopped.result.ok).toBe(false)
  196. if (!stopped.result.ok) expect(stopped.result.error.code).toBe('agent-busy')
  197. expect(cancel).not.toHaveBeenCalled()
  198. const queued = await api.sessions.updateQueue(request({
  199. sessionId: originChild.id,
  200. itemId: InboxItemId('queued-item'),
  201. action: { kind: 'remove' },
  202. }))
  203. expect(queued.result.ok).toBe(false)
  204. if (!queued.result.ok) expect(queued.result.error.code).toBe('agent-busy')
  205. expect(updateInbox).not.toHaveBeenCalled()
  206. const models = await api.sessions.models(request({ sessionId: startingChild.id }))
  207. expect(models.result.ok).toBe(false)
  208. if (!models.result.ok) expect(models.result.error.code).toBe('agent-busy')
  209. const create = await api.sessions.create(request({ sessionId: originChild.id, cwd: '/proj' }))
  210. expect(create.result.ok).toBe(false)
  211. if (!create.result.ok) expect(create.result.error.code).toBe('agent-busy')
  212. const history = await api.sessions.history(request({ sessionId: originChild.id }))
  213. expect(history.result.ok).toBe(true)
  214. expect(ctx.agents.get(originChild.id)).toBe(originChild)
  215. })
  216. it('does not classify an ordinary fork from an inherited ancestor descriptor', async () => {
  217. const ctx = new Context()
  218. await ctx.plugin(SessionStore)
  219. await ctx.plugin(AgentRegistry)
  220. await ctx.plugin(UserInteractionService)
  221. const session = ctx.sessions.create(sid('session-ordinary-fork'), {
  222. seed: [{
  223. type: 'subagent/descriptor',
  224. seq: 0,
  225. time: 1,
  226. data: { version: 2, mode: 'continuable', provider: 'spawn', label: 'ancestor' },
  227. }],
  228. meta: { cwd: '/proj', parentSession: sid('session-source'), seedLength: 1 },
  229. })
  230. const followup = vi.fn()
  231. const agent = { id: session.id, session, status: 'idle', ctx, followup } as unknown as Agent
  232. ctx.agents.register(agent)
  233. const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp', workspaceRoot: '/tmp' })
  234. const response = await api.sessions.prompt(request({
  235. sessionId: agent.id,
  236. mode: 'queue',
  237. content: [{ type: 'text', text: 'ordinary work' }],
  238. }))
  239. expect(response.result.ok).toBe(true)
  240. expect(followup).toHaveBeenCalledOnce()
  241. })
  242. })
  243. describe('degenerate composition (no persistence, no factory)', () => {
  244. it('list skips the cold merge and history reports missing persistence as internal', async () => {
  245. const ctx = new Context()
  246. await ctx.plugin(SessionStore)
  247. await ctx.plugin(AgentRegistry)
  248. await ctx.plugin(UserInteractionService)
  249. const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp', workspaceRoot: '/tmp' })
  250. const listed = await api.sessions.list(request({}))
  251. expect(listed.result.ok).toBe(true)
  252. if (listed.result.ok) expect(listed.result.value.items).toEqual([])
  253. // No persistence means cold history cannot inspect a transcript.
  254. const response = await api.sessions.history(request({ sessionId: sid('session-ghost') }))
  255. expect(response.result.ok).toBe(false)
  256. if (!response.result.ok) {
  257. expect(response.result.error.code).toBe('internal')
  258. expect(response.result.error.message).toMatch(/history unavailable for session "session-ghost"/)
  259. }
  260. })
  261. it('maps a persistence catalog miss to session-not-found without inspection', async () => {
  262. const ctx = new Context()
  263. await ctx.plugin(SessionStore)
  264. await ctx.plugin(AgentRegistry)
  265. await ctx.plugin(UserInteractionService)
  266. const inspect = vi.fn()
  267. ctx.provide('sessionPersistence', {
  268. list: () => Promise.resolve([]),
  269. inspect,
  270. } as never)
  271. const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp', workspaceRoot: '/tmp' })
  272. const response = await api.sessions.history(request({ sessionId: sid('session-missing') }))
  273. expect(response.result.ok).toBe(false)
  274. if (!response.result.ok) expect(response.result.error.code).toBe('session-not-found')
  275. expect(inspect).not.toHaveBeenCalled()
  276. })
  277. })
  278. describe('sessions.prompt synchronous rejection', () => {
  279. it('maps a synchronous send throw (disposed/invalid input) to agent-busy with the reason attached', async () => {
  280. const ctx = new Context()
  281. await ctx.plugin(SessionStore)
  282. await ctx.plugin(AgentRegistry)
  283. await ctx.plugin(UserInteractionService)
  284. const session = ctx.sessions.create(sid('session-throwing'))
  285. // A live structural stub whose delivery verbs throw synchronously, the
  286. // shape a disposed loop presents at this seam.
  287. ctx.agents.register({
  288. id: session.id,
  289. session,
  290. status: 'idle',
  291. ctx,
  292. followup: () => { throw new Error('agent "session-throwing" lifecycle disposed') },
  293. steer: () => { throw new Error('agent "session-throwing" lifecycle disposed') },
  294. } as unknown as Agent)
  295. const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp', workspaceRoot: '/tmp' })
  296. for (const mode of ['queue', 'steer'] as const) {
  297. const response = await api.sessions.prompt(request({
  298. sessionId: session.id, mode, content: [{ type: 'text' as const, text: 'x' }],
  299. }))
  300. expect(response.result.ok).toBe(false)
  301. if (!response.result.ok) {
  302. expect(response.result.error.code).toBe('agent-busy')
  303. expect(response.result.error.message).toBe('prompt rejected')
  304. expect(response.result.error.details).toEqual({
  305. reason: 'Error: agent "session-throwing" lifecycle disposed',
  306. })
  307. }
  308. }
  309. })
  310. it('classifies a raced cold-resume ID collision as agent-busy', async () => {
  311. const ctx = new Context()
  312. await ctx.plugin(SessionStore)
  313. await ctx.plugin(AgentRegistry)
  314. await ctx.plugin(UserInteractionService)
  315. const sessionId = sid('race-resume')
  316. const meta: SessionHeader = header('race-resume', 1000)
  317. ctx.provide('sessionPersistence', {
  318. list: () => Promise.resolve([meta]),
  319. inspect: () => Promise.resolve({ meta, events: [] as SessionEvent[] }),
  320. locate: () => undefined,
  321. } as never)
  322. // The raced winner: a live parent-owned subagent publishes the identity
  323. // while the generic cold resume is in flight, so the resume collides.
  324. const parentSession = ctx.sessions.create(sid('race-parent'), { meta: { cwd: '/proj' } })
  325. const parent = { id: parentSession.id, session: parentSession, status: 'idle', ctx } as Agent
  326. ctx.agents.register(parent)
  327. const childSession = ctx.sessions.create(sessionId, {
  328. meta: { cwd: '/proj', parentSession: parent.id, origin: 'subagent' },
  329. })
  330. const child = { id: sessionId, session: childSession, status: 'idle', ctx } as unknown as Agent
  331. vi.spyOn(ctx.agents, 'resume').mockImplementationOnce(async () => {
  332. // The parent's `enter()` wins the identity between the pre-resume
  333. // re-check and publication; the generic resume then collides.
  334. ctx.agents.register(child)
  335. throw new Error('session id already published')
  336. })
  337. const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp', workspaceRoot: '/tmp' })
  338. const models = await api.sessions.models(request({ sessionId }))
  339. expect(models.result.ok).toBe(false)
  340. if (!models.result.ok) {
  341. expect(models.result.error).toMatchObject({
  342. code: 'agent-busy',
  343. details: { reason: 'use subagent delivery for this child session' },
  344. })
  345. }
  346. })
  347. })