1
0

api-proxy-cold.spec.ts 19 KB

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