api-proxy-cold.spec.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  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 { TypeRTLookupFailure } from '@deepseek-ai/dsh-type-meta'
  14. import TypertRegistry from '@deepseek-ai/dsh-typert-registry'
  15. import { MessageId } from '@deepseek-ai/dsh-llm'
  16. import type { Agent } from '@deepseek-ai/dsh-agent'
  17. import UserInteractionService from '@deepseek-ai/dsh-user-interaction'
  18. import type { SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session'
  19. import {
  20. PersistenceCoordinator,
  21. SessionPersistenceRevision,
  22. type PersistenceBackend,
  23. type StoredPrefix,
  24. } from '@deepseek-ai/dsh-session-persistence'
  25. import type { RpcRequest } from '@deepseek-ai/dsh-host-apiproxy/api/rpc'
  26. import { RpcId } from '@deepseek-ai/dsh-host-apiproxy/api/rpc'
  27. import { createApiProxy } from '@deepseek-ai/dsh-host-apiproxy'
  28. const sid = (id: string): SessionId => id as SessionId
  29. let nextRpc = 1
  30. function request<P>(payload: P): RpcRequest<P> {
  31. return {
  32. rpcId: RpcId(`cold-${String(nextRpc++)}`),
  33. payload: { timeZone: 'UTC', clientTimeZone: 'UTC', ...payload },
  34. }
  35. }
  36. function header(id: string, createdAt: number, extra: Partial<SessionHeader> = {}): SessionHeader {
  37. return { version: 0, id: sid(id), createdAt, cwd: '/proj', ...extra }
  38. }
  39. describe('sessions.list cold merge', () => {
  40. it('summarizes unattached sessions: log mtime, locate-less and vanished-log createdAt fallbacks, lineage', async () => {
  41. const ctx = new Context()
  42. await ctx.plugin(SessionStore)
  43. await ctx.plugin(UserInteractionService)
  44. const root = mkdtempSync(join(tmpdir(), 'dsh-cold-'))
  45. const logPath = join(root, 'a.log')
  46. writeFileSync(logPath, 'log-bytes')
  47. utimesSync(logPath, 5000, 5000) // mtime 5_000_000 ms — newer than every createdAt below
  48. const metas = [
  49. header('session-a', 1000),
  50. header('session-b', 2000, { parentSession: sid('session-parent'), origin: 'subagent' }),
  51. header('session-c', 1500),
  52. ]
  53. // Structural fake of the persistence face list() consumes: list + locate.
  54. // locate: a real per-session file (mtime wins), a backend without one
  55. // (SQLite shape → createdAt), and a path whose file vanished (stat ENOENT
  56. // → createdAt).
  57. ctx.provide('sessionPersistence', {
  58. list: () => Promise.resolve(metas),
  59. locate: (meta: SessionHeader) => {
  60. if (meta.id === sid('session-a')) return { kind: 'jsonl', path: logPath }
  61. if (meta.id === sid('session-c')) return { kind: 'jsonl', path: join(root, 'vanished.log') }
  62. return undefined
  63. },
  64. })
  65. const api = createApiProxy(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp', workspaceRoot: '/tmp' })
  66. const response = await api.sessions.list(request({}))
  67. expect(response.result.ok).toBe(true)
  68. if (!response.result.ok) throw new Error('unreachable')
  69. const items = response.result.value.items
  70. expect(items.map(item => item.sessionId)).toEqual(['session-a', 'session-b', 'session-c'])
  71. const [a, b, c] = items
  72. expect(a?.updatedAt).toBeCloseTo(5_000_000, -3)
  73. expect(a?.running).toBe(false)
  74. // Cold summaries are never blank: lazy persistence keeps never-appended
  75. // sessions out of list(), so a listed session necessarily has events.
  76. expect(items.every(item => !item.blank)).toBe(true)
  77. expect(a?.cwd).toBe('/proj')
  78. expect(a?.parentSessionId).toBeUndefined()
  79. expect(b?.updatedAt).toBe(2000)
  80. expect(b?.parentSessionId).toBe('session-parent')
  81. expect(b?.origin).toBe('subagent')
  82. expect(c?.updatedAt).toBe(1500)
  83. })
  84. })
  85. describe('attached updatedAt excludes end-seed', () => {
  86. it('reports the last real work, not the pickup, so a resumed-untouched session does not float', async () => {
  87. const ctx = new Context()
  88. await ctx.plugin(SessionStore)
  89. await ctx.plugin(UserInteractionService)
  90. await ctx.plugin(AgentRegistry)
  91. const api = createApiProxy(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp', workspaceRoot: '/tmp' })
  92. // Old work, resumed just now: the log tail would report the pickup.
  93. const worked = 1_000_000
  94. const resumed = ctx.sessions.create(sid('resumed-untouched'), {
  95. seed: [
  96. { type: 'turn/start', seq: 0, time: worked, data: { turn: 1 } },
  97. { type: 'turn/end', seq: 1, time: worked, data: { turn: 1, reason: { kind: 'completed' } } },
  98. ],
  99. meta: { cwd: '/proj', createdAt: 500 },
  100. })
  101. ctx.agents.register({ id: resumed.id, session: resumed, status: 'idle', ctx } as Agent)
  102. const boundary = resumed.events.at(-1)
  103. expect(boundary?.type).toBe('session/end-seed')
  104. expect(boundary?.time).toBeGreaterThan(worked)
  105. const listed = await api.sessions.list(request({}))
  106. if (!listed.result.ok) throw new Error('list failed')
  107. const summary = listed.result.value.items.find(item => item.sessionId === 'resumed-untouched')
  108. expect(summary?.updatedAt).toBe(worked)
  109. // Real work appended after end-seed does move it.
  110. resumed.append('turn/start', { turn: 2 })
  111. const after = await api.sessions.list(request({}))
  112. if (!after.result.ok) throw new Error('list failed')
  113. const moved = after.result.value.items.find(item => item.sessionId === 'resumed-untouched')
  114. expect(moved?.updatedAt).toBeGreaterThan(worked)
  115. })
  116. })
  117. describe('cold history recovery view', () => {
  118. it('shows in-memory interruption repair without activating the session', async () => {
  119. const ctx = new Context()
  120. await ctx.plugin(SessionStore)
  121. await ctx.plugin(UserInteractionService)
  122. const sessionId = sid('session-interrupted')
  123. const meta = header(sessionId, 1000)
  124. const stored: StoredPrefix<never> = {
  125. meta,
  126. events: [{ type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }],
  127. revision: SessionPersistenceRevision('history-recovery-test:1'),
  128. }
  129. const backend: PersistenceBackend<never> = {
  130. name: 'history-recovery-test',
  131. loadStored: id => Promise.resolve(id === sessionId ? structuredClone(stored) : undefined),
  132. readStoredRevision: id => Promise.resolve(
  133. id === sessionId ? SessionPersistenceRevision('history-recovery-test:1') : undefined,
  134. ),
  135. appendBatch: () => Promise.resolve(),
  136. commitRepair: () => Promise.resolve(),
  137. list: () => Promise.resolve([structuredClone(meta)]),
  138. }
  139. const coordinator = new PersistenceCoordinator(ctx, backend)
  140. ctx.provide('sessionPersistence', {
  141. list: (signal?: AbortSignal) => backend.list(signal),
  142. inspect: (id: SessionId, signal?: AbortSignal) => coordinator.inspect(id, signal),
  143. locate: () => undefined,
  144. } as never)
  145. const api = createApiProxy(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp', workspaceRoot: '/tmp' })
  146. const history = await api.sessions.history(request({ sessionId, beforeSeq: 2, maxMessages: 10 }))
  147. if (!history.result.ok) throw new Error('history failed')
  148. expect(history.result.value.events.map(entry => entry.event)).toMatchInlineSnapshot(`
  149. [
  150. {
  151. "data": {
  152. "turn": 1,
  153. },
  154. "seq": 0,
  155. "time": 1,
  156. "type": "turn/start",
  157. },
  158. {
  159. "data": {
  160. "reason": {
  161. "kind": "interrupted",
  162. },
  163. "turn": 1,
  164. },
  165. "seq": 1,
  166. "time": 1,
  167. "type": "turn/end",
  168. },
  169. ]
  170. `)
  171. expect(ctx.sessions.get(sessionId)).toBeUndefined()
  172. await ctx.fiber.dispose()
  173. })
  174. })
  175. describe('Remote Agent and Session lookup policy', () => {
  176. it('deduplicates a cold resume across Agent and Session parameters', async () => {
  177. const ctx = new Context()
  178. await ctx.plugin(TypertRegistry)
  179. await ctx.plugin(SessionStore)
  180. await ctx.plugin(AgentRegistry)
  181. await ctx.plugin(UserInteractionService)
  182. const sessionId = sid('session-remote-cold')
  183. const meta = header(sessionId, 1000)
  184. const inspect = vi.fn(() => Promise.resolve({ meta, events: [] as SessionEvent[] }))
  185. ctx.provide('sessionPersistence', {
  186. list: () => Promise.resolve([meta]),
  187. inspect,
  188. locate: () => undefined,
  189. } as never)
  190. const resumedSession = { id: sessionId, header: meta, events: [] } as unknown as import('@deepseek-ai/dsh-session').Session
  191. const resumedAgent = { id: sessionId, session: resumedSession, status: 'idle', ctx } as Agent
  192. const release = Promise.withResolvers<undefined>()
  193. const resume = vi.spyOn(ctx.agents, 'resume').mockImplementation(async () => {
  194. await release.promise
  195. return { agent: resumedAgent, dispose: () => Promise.resolve() }
  196. })
  197. const defaultAgentLookup = ctx.typert.lookups.get('agent')
  198. const defaultSessionLookup = ctx.typert.lookups.get('session')
  199. createApiProxy(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp', workspaceRoot: '/tmp' })
  200. await vi.waitFor(() => {
  201. expect(ctx.typert.lookups.get('agent')).not.toBe(defaultAgentLookup)
  202. expect(ctx.typert.lookups.get('session')).not.toBe(defaultSessionLookup)
  203. })
  204. const agentLookup = ctx.typert.lookups.get('agent')
  205. const sessionLookup = ctx.typert.lookups.get('session')
  206. if (agentLookup === undefined || sessionLookup === undefined) throw new Error('core lookup providers were not mounted')
  207. const resolvedAgent = Promise.resolve(agentLookup.resolve(sessionId))
  208. const resolvedSession = Promise.resolve(sessionLookup.resolve(sessionId))
  209. await vi.waitFor(() => { expect(resume).toHaveBeenCalledOnce() })
  210. release.resolve(undefined)
  211. await expect(resolvedAgent).resolves.toBe(resumedAgent)
  212. await expect(resolvedSession).resolves.toBe(resumedSession)
  213. expect(inspect).toHaveBeenCalledOnce()
  214. })
  215. it('preserves the subagent ownership fence for cold and live Remote lookups', async () => {
  216. const ctx = new Context()
  217. await ctx.plugin(TypertRegistry)
  218. await ctx.plugin(SessionStore)
  219. await ctx.plugin(AgentRegistry)
  220. await ctx.plugin(UserInteractionService)
  221. const coldId = sid('session-remote-cold-child')
  222. const coldMeta = header(coldId, 1000, {
  223. parentSession: sid('session-parent'),
  224. origin: 'subagent',
  225. })
  226. const inspect = vi.fn(() => Promise.resolve({ meta: coldMeta, events: [] as SessionEvent[] }))
  227. ctx.provide('sessionPersistence', {
  228. list: () => Promise.resolve([coldMeta]),
  229. inspect,
  230. locate: () => undefined,
  231. } as never)
  232. const liveSession = ctx.sessions.create(sid('session-remote-live-child'), {
  233. meta: { cwd: '/proj', parentSession: sid('session-parent'), origin: 'subagent' },
  234. })
  235. const liveAgent = { id: liveSession.id, session: liveSession, status: 'idle', ctx } as Agent
  236. ctx.agents.register(liveAgent)
  237. const resume = vi.spyOn(ctx.agents, 'resume')
  238. const defaultAgentLookup = ctx.typert.lookups.get('agent')
  239. const defaultSessionLookup = ctx.typert.lookups.get('session')
  240. createApiProxy(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp', workspaceRoot: '/tmp' })
  241. await vi.waitFor(() => {
  242. expect(ctx.typert.lookups.get('agent')).not.toBe(defaultAgentLookup)
  243. expect(ctx.typert.lookups.get('session')).not.toBe(defaultSessionLookup)
  244. })
  245. const agentLookup = ctx.typert.lookups.get('agent')
  246. const sessionLookup = ctx.typert.lookups.get('session')
  247. if (agentLookup === undefined || sessionLookup === undefined) throw new Error('core lookup providers were not mounted')
  248. const ownershipFailure = {
  249. failure: {
  250. code: 'agent-busy',
  251. details: { reason: 'use subagent delivery for this child session' },
  252. },
  253. }
  254. const coldFailure = Promise.resolve(agentLookup.resolve(coldId))
  255. const liveFailure = Promise.resolve(sessionLookup.resolve(liveSession.id))
  256. await expect(coldFailure).rejects.toBeInstanceOf(TypeRTLookupFailure)
  257. await expect(coldFailure).rejects.toMatchObject(ownershipFailure)
  258. await expect(liveFailure).rejects.toBeInstanceOf(TypeRTLookupFailure)
  259. await expect(liveFailure).rejects.toMatchObject(ownershipFailure)
  260. expect(resume).not.toHaveBeenCalled()
  261. expect(inspect).toHaveBeenCalledOnce()
  262. })
  263. })
  264. describe('subagent ownership fence', () => {
  265. it('reads a cold child without an Agent and rejects generic resume or adoption', async () => {
  266. const ctx = new Context()
  267. await ctx.plugin(SessionStore)
  268. await ctx.plugin(AgentRegistry)
  269. await ctx.plugin(UserInteractionService)
  270. const sessionId = sid('session-child')
  271. const meta = header('session-child', 1000, {
  272. parentSession: sid('session-parent'),
  273. seedLength: 0,
  274. origin: 'subagent',
  275. })
  276. const events = [
  277. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  278. {
  279. type: 'user/message',
  280. seq: 1,
  281. time: 2,
  282. data: { content: [{ type: 'text', text: 'work' }], source: { kind: 'user' } },
  283. surfaceOp: 'append',
  284. },
  285. {
  286. type: 'subagent/descriptor',
  287. seq: 2,
  288. time: 3,
  289. data: { version: 2, mode: 'continuable', provider: 'spawn', label: 'child' },
  290. },
  291. { type: 'turn/end', seq: 3, time: 4, data: { turn: 1, reason: { kind: 'completed' } } },
  292. ] as SessionEvent[]
  293. const inspect = vi.fn(() => Promise.resolve({ meta, events }))
  294. ctx.provide('sessionPersistence', {
  295. list: () => Promise.resolve([meta]),
  296. inspect,
  297. locate: () => undefined,
  298. } as never)
  299. const resume = vi.spyOn(ctx.agents, 'resume')
  300. const api = createApiProxy(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp', workspaceRoot: '/tmp' })
  301. const history = await api.sessions.history(request({ sessionId }))
  302. expect(history.result.ok).toBe(true)
  303. if (history.result.ok) {
  304. expect(history.result.value.events.map(entry => entry.event.type)).toEqual(events.map(event => event.type))
  305. }
  306. expect(ctx.agents.get(sessionId)).toBeUndefined()
  307. const prompt = await api.sessions.prompt(request({
  308. sessionId,
  309. mode: 'queue',
  310. content: [{ type: 'text', text: 'follow up' }],
  311. }))
  312. expect(prompt.result.ok).toBe(false)
  313. if (!prompt.result.ok) {
  314. expect(prompt.result.error).toMatchObject({
  315. code: 'agent-busy',
  316. details: { reason: 'use subagent delivery for this child session' },
  317. })
  318. }
  319. const create = await api.sessions.create(request({ sessionId, cwd: '/proj' }))
  320. expect(create.result.ok).toBe(false)
  321. if (!create.result.ok) expect(create.result.error.code).toBe('agent-busy')
  322. expect(resume).not.toHaveBeenCalled()
  323. expect(ctx.agents.get(sessionId)).toBeUndefined()
  324. expect(inspect).toHaveBeenCalledTimes(3)
  325. })
  326. it('no longer treats a descriptor-only cold child without origin as subagent-owned', async () => {
  327. const ctx = new Context()
  328. await ctx.plugin(SessionStore)
  329. await ctx.plugin(AgentRegistry)
  330. await ctx.plugin(UserInteractionService)
  331. const sessionId = sid('session-legacy-child')
  332. const meta = header('session-legacy-child', 1000, {
  333. parentSession: sid('session-parent'),
  334. seedLength: 0,
  335. })
  336. const events = [
  337. {
  338. type: 'subagent/descriptor',
  339. seq: 0,
  340. time: 1,
  341. data: { version: 2, mode: 'continuable', provider: 'spawn', label: 'child' },
  342. },
  343. ] as SessionEvent[]
  344. ctx.provide('sessionPersistence', {
  345. list: () => Promise.resolve([meta]),
  346. inspect: () => Promise.resolve({ meta, events }),
  347. locate: () => undefined,
  348. } as never)
  349. // Pre-#1569 stores classify a child only through the descriptor event and
  350. // carry no header `origin`; the pre-release decision stops recognizing
  351. // them, so the ownership fence lets generic resume reach the registry
  352. // instead of answering `agent-busy`.
  353. const resume = vi.spyOn(ctx.agents, 'resume')
  354. .mockRejectedValue(new Error('registry unavailable in this bench'))
  355. const api = createApiProxy(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp', workspaceRoot: '/tmp' })
  356. const prompt = await api.sessions.prompt(request({
  357. sessionId,
  358. mode: 'queue',
  359. content: [{ type: 'text', text: 'follow up' }],
  360. }))
  361. expect(resume).toHaveBeenCalledTimes(1)
  362. expect(prompt.result.ok).toBe(false)
  363. if (!prompt.result.ok) expect(prompt.result.error.code).toBe('internal')
  364. })
  365. it('rejects origin-marked and runtime-owned live children from generic controls', async () => {
  366. const ctx = new Context()
  367. await ctx.plugin(SessionStore)
  368. await ctx.plugin(AgentRegistry)
  369. await ctx.plugin(UserInteractionService)
  370. const parentSession = ctx.sessions.create(sid('session-parent'), { meta: { cwd: '/proj' } })
  371. const parent = { id: parentSession.id, session: parentSession, status: 'idle', ctx } as Agent
  372. ctx.agents.register(parent)
  373. const originSession = ctx.sessions.create(sid('session-origin-child'), {
  374. meta: { cwd: '/proj', parentSession: parent.id, origin: 'subagent' },
  375. })
  376. const cancel = vi.fn()
  377. const updateInbox = vi.fn(() => 'applied' as const)
  378. const originChild = {
  379. id: originSession.id,
  380. session: originSession,
  381. status: 'idle',
  382. ctx,
  383. cancel,
  384. updateInbox,
  385. } as unknown as Agent
  386. ctx.agents.register(originChild)
  387. const startingSession = ctx.sessions.create(sid('session-starting-child'), {
  388. meta: { cwd: '/proj', parentSession: parent.id },
  389. })
  390. const startingChild = { id: startingSession.id, session: startingSession, status: 'idle', ctx } as Agent
  391. ctx.agents.enter(startingChild, parent)
  392. const api = createApiProxy(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp', workspaceRoot: '/tmp' })
  393. const stopped = await api.sessions.cancel(request({ sessionId: originChild.id }))
  394. expect(stopped.result.ok).toBe(false)
  395. if (!stopped.result.ok) expect(stopped.result.error.code).toBe('agent-busy')
  396. expect(cancel).not.toHaveBeenCalled()
  397. const queued = await api.sessions.updateQueue(request({
  398. sessionId: originChild.id,
  399. itemId: MessageId('queued-item'),
  400. action: { kind: 'remove' },
  401. }))
  402. expect(queued.result.ok).toBe(false)
  403. if (!queued.result.ok) expect(queued.result.error.code).toBe('agent-busy')
  404. expect(updateInbox).not.toHaveBeenCalled()
  405. const models = await api.sessions.models(request({ sessionId: startingChild.id }))
  406. expect(models.result.ok).toBe(false)
  407. if (!models.result.ok) expect(models.result.error.code).toBe('agent-busy')
  408. const create = await api.sessions.create(request({ sessionId: originChild.id, cwd: '/proj' }))
  409. expect(create.result.ok).toBe(false)
  410. if (!create.result.ok) expect(create.result.error.code).toBe('agent-busy')
  411. const history = await api.sessions.history(request({ sessionId: originChild.id }))
  412. expect(history.result.ok).toBe(true)
  413. expect(ctx.agents.get(originChild.id)).toBe(originChild)
  414. })
  415. it('does not classify an ordinary fork from an inherited ancestor descriptor', async () => {
  416. const ctx = new Context()
  417. await ctx.plugin(SessionStore)
  418. await ctx.plugin(AgentRegistry)
  419. await ctx.plugin(UserInteractionService)
  420. const session = ctx.sessions.create(sid('session-ordinary-fork'), {
  421. seed: [{
  422. type: 'subagent/descriptor',
  423. seq: 0,
  424. time: 1,
  425. data: { version: 2, mode: 'continuable', provider: 'spawn', label: 'ancestor' },
  426. }],
  427. meta: { cwd: '/proj', parentSession: sid('session-source'), seedLength: 1 },
  428. })
  429. const followup = vi.fn()
  430. const agent = { id: session.id, session, status: 'idle', ctx, followup } as unknown as Agent
  431. ctx.agents.register(agent)
  432. const api = createApiProxy(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp', workspaceRoot: '/tmp' })
  433. const response = await api.sessions.prompt(request({
  434. sessionId: agent.id,
  435. mode: 'queue',
  436. content: [{ type: 'text', text: 'ordinary work' }],
  437. }))
  438. expect(response.result.ok).toBe(true)
  439. expect(followup).toHaveBeenCalledOnce()
  440. })
  441. })
  442. describe('degenerate composition (no persistence, no factory)', () => {
  443. it('list skips the cold merge and history reports missing persistence as internal', async () => {
  444. const ctx = new Context()
  445. await ctx.plugin(SessionStore)
  446. await ctx.plugin(AgentRegistry)
  447. await ctx.plugin(UserInteractionService)
  448. const api = createApiProxy(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp', workspaceRoot: '/tmp' })
  449. const listed = await api.sessions.list(request({}))
  450. expect(listed.result.ok).toBe(true)
  451. if (listed.result.ok) expect(listed.result.value.items).toEqual([])
  452. // No persistence means cold history cannot inspect a transcript.
  453. const response = await api.sessions.history(request({ sessionId: sid('session-ghost') }))
  454. expect(response.result.ok).toBe(false)
  455. if (!response.result.ok) {
  456. expect(response.result.error.code).toBe('internal')
  457. expect(response.result.error.message).toMatch(/history unavailable for session "session-ghost"/)
  458. }
  459. })
  460. it('maps a persistence catalog miss to session-not-found without inspection', async () => {
  461. const ctx = new Context()
  462. await ctx.plugin(SessionStore)
  463. await ctx.plugin(AgentRegistry)
  464. await ctx.plugin(UserInteractionService)
  465. const inspect = vi.fn()
  466. ctx.provide('sessionPersistence', {
  467. list: () => Promise.resolve([]),
  468. inspect,
  469. } as never)
  470. const api = createApiProxy(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp', workspaceRoot: '/tmp' })
  471. const response = await api.sessions.history(request({ sessionId: sid('session-missing') }))
  472. expect(response.result.ok).toBe(false)
  473. if (!response.result.ok) expect(response.result.error.code).toBe('session-not-found')
  474. expect(inspect).not.toHaveBeenCalled()
  475. })
  476. })
  477. describe('cold Session zone identity', () => {
  478. it('rejects a different requested zone before resuming a persisted identity', async () => {
  479. const ctx = new Context()
  480. await ctx.plugin(SessionStore)
  481. await ctx.plugin(AgentRegistry)
  482. await ctx.plugin(UserInteractionService)
  483. const sessionId = sid('session-cold-zone-conflict')
  484. const meta = header('session-cold-zone-conflict', 1000, { timeZone: 'UTC' })
  485. ctx.provide('sessionPersistence', {
  486. list: () => Promise.resolve([meta]),
  487. inspect: () => Promise.resolve({ meta, events: [] as SessionEvent[] }),
  488. locate: () => undefined,
  489. } as never)
  490. const resume = vi.spyOn(ctx.agents, 'resume')
  491. const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp', workspaceRoot: '/tmp' })
  492. const response = await api.sessions.create(request({
  493. sessionId,
  494. cwd: '/proj',
  495. timeZone: 'Asia/Shanghai',
  496. }))
  497. expect(response.result).toMatchObject({
  498. ok: false,
  499. error: {
  500. code: 'session-conflict',
  501. details: {
  502. sessionId,
  503. existingCwd: '/proj',
  504. existingTimeZone: 'UTC',
  505. requestedTimeZone: 'Asia/Shanghai',
  506. },
  507. },
  508. })
  509. expect(resume).not.toHaveBeenCalled()
  510. })
  511. })
  512. describe('sessions.prompt synchronous rejection', () => {
  513. it('maps a synchronous send throw (disposed/invalid input) to agent-busy with the reason attached', async () => {
  514. const ctx = new Context()
  515. await ctx.plugin(SessionStore)
  516. await ctx.plugin(AgentRegistry)
  517. await ctx.plugin(UserInteractionService)
  518. const session = ctx.sessions.create(sid('session-throwing'))
  519. // A live structural stub whose delivery verbs throw synchronously, the
  520. // shape a disposed loop presents at this gateway boundary.
  521. ctx.agents.register({
  522. id: session.id,
  523. session,
  524. status: 'idle',
  525. ctx,
  526. followup: () => { throw new Error('agent "session-throwing" lifecycle disposed') },
  527. steer: () => { throw new Error('agent "session-throwing" lifecycle disposed') },
  528. } as unknown as Agent)
  529. const api = createApiProxy(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp', workspaceRoot: '/tmp' })
  530. for (const mode of ['queue', 'steer'] as const) {
  531. const response = await api.sessions.prompt(request({
  532. sessionId: session.id, mode, content: [{ type: 'text' as const, text: 'x' }],
  533. }))
  534. expect(response.result.ok).toBe(false)
  535. if (!response.result.ok) {
  536. expect(response.result.error.code).toBe('agent-busy')
  537. expect(response.result.error.message).toBe('prompt rejected')
  538. expect(response.result.error.details).toEqual({
  539. reason: 'Error: agent "session-throwing" lifecycle disposed',
  540. })
  541. }
  542. }
  543. })
  544. it('classifies a raced cold-resume ID collision as agent-busy', async () => {
  545. const ctx = new Context()
  546. await ctx.plugin(SessionStore)
  547. await ctx.plugin(AgentRegistry)
  548. await ctx.plugin(UserInteractionService)
  549. const sessionId = sid('race-resume')
  550. const meta: SessionHeader = header('race-resume', 1000)
  551. ctx.provide('sessionPersistence', {
  552. list: () => Promise.resolve([meta]),
  553. inspect: () => Promise.resolve({ meta, events: [] as SessionEvent[] }),
  554. locate: () => undefined,
  555. } as never)
  556. // The raced winner: a live parent-owned subagent publishes the identity
  557. // while the generic cold resume is in flight, so the resume collides.
  558. const parentSession = ctx.sessions.create(sid('race-parent'), { meta: { cwd: '/proj' } })
  559. const parent = { id: parentSession.id, session: parentSession, status: 'idle', ctx } as Agent
  560. ctx.agents.register(parent)
  561. const childSession = ctx.sessions.create(sessionId, {
  562. meta: { cwd: '/proj', parentSession: parent.id, origin: 'subagent' },
  563. })
  564. const child = { id: sessionId, session: childSession, status: 'idle', ctx } as unknown as Agent
  565. vi.spyOn(ctx.agents, 'resume').mockImplementationOnce(async () => {
  566. // The parent's `enter()` wins the identity between the pre-resume
  567. // re-check and publication; the generic resume then collides.
  568. ctx.agents.register(child)
  569. throw new Error('session id already published')
  570. })
  571. const api = createApiProxy(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp', workspaceRoot: '/tmp' })
  572. const models = await api.sessions.models(request({ sessionId }))
  573. expect(models.result.ok).toBe(false)
  574. if (!models.result.ok) {
  575. expect(models.result.error).toMatchObject({
  576. code: 'agent-busy',
  577. details: { reason: 'use subagent delivery for this child session' },
  578. })
  579. }
  580. })
  581. })