api-proxy-cold.spec.ts 16 KB

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