session-cold.host.spec.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  1. /**
  2. * Cold-session and degenerate-composition paths of the Session Controller:
  3. * metadata-only listing, Agent-free history reads, subagent ownership
  4. * isolation, and prompt failure mapping.
  5. */
  6. import { SESSION_FORMAT_VERSION, SessionLogOffset, SessionSeq } from '@deepseek-ai/dsh-session'
  7. import { describe, expect, it, vi } from 'vitest'
  8. import { Context } from '@deepseek-ai/cordis'
  9. import SessionStore from '@deepseek-ai/dsh-session'
  10. import AgentRegistry from '@deepseek-ai/dsh-agent'
  11. import { SessionHistoryController } from '@deepseek-ai/dsh-api-session-controller/src/history.ts'
  12. import { subagentIdentityProjectionDefinition } from '@deepseek-ai/dsh-subagent/src/projection.ts'
  13. import TypertRegistry from '@deepseek-ai/dsh-typert-registry'
  14. import { createUserMessage, MessageId } from '@deepseek-ai/dsh-llm'
  15. import { snapshotSubagentDescriptor } from '@deepseek-ai/dsh-subagent'
  16. import type { Agent } from '@deepseek-ai/dsh-agent'
  17. import type { SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session'
  18. import type { SessionPromptRequest, SessionRequestId } from '../src/types.ts'
  19. import {
  20. SessionPersistenceRevision,
  21. type SessionPersistenceSnapshot,
  22. } from '@deepseek-ai/dsh-session-persistence'
  23. import {
  24. createSessionTestRemote,
  25. testSessionPersistence,
  26. } from './test-remote.ts'
  27. const sid = (id: string): SessionId => id as SessionId
  28. function request<P>(payload: P): P {
  29. return payload
  30. }
  31. let nextRequestId = 1
  32. function promptRequest(
  33. payload: Omit<SessionPromptRequest, 'requestId'>,
  34. ): SessionPromptRequest {
  35. return {
  36. ...payload,
  37. requestId: `cold-${String(nextRequestId++)}` as SessionRequestId,
  38. }
  39. }
  40. function header(id: string, createdAt: number, extra: Partial<SessionHeader> = {}): SessionHeader {
  41. return { version: SESSION_FORMAT_VERSION, id: sid(id), createdAt, isSeeded: false, cwd: '/proj', ...extra }
  42. }
  43. function providePersistence(ctx: Context, persistence: Record<string, unknown>): () => void {
  44. return ctx.provide('sessionPersistence', testSessionPersistence(ctx, persistence) as never)
  45. }
  46. function statSnapshot(
  47. meta: SessionHeader,
  48. metrics: Partial<Pick<SessionPersistenceSnapshot, 'eventCount' | 'sizeBytes'>> = {},
  49. ): SessionPersistenceSnapshot {
  50. return { header: meta, revision: SessionPersistenceRevision(`test:${meta.id}:stat`), ...metrics }
  51. }
  52. /** A stored log with one human prompt at time 1200: proven non-blank. */
  53. function conversationEvents(): SessionEvent[] {
  54. return [
  55. { type: 'turn/start', seq: SessionSeq(0), time: 800, data: { turn: 1 } },
  56. {
  57. type: 'user/message', seq: SessionSeq(1), time: 1200,
  58. data: createUserMessage({ content: [{ type: 'text', text: 'worked' }], source: { kind: 'user' } }),
  59. surfaceOp: 'append',
  60. },
  61. ] as SessionEvent[]
  62. }
  63. describe('sessions.list cold merge', () => {
  64. it('uses a predecessor title hint with zero cold stat or body reads', async () => {
  65. const ctx = new Context()
  66. await ctx.plugin(SessionStore)
  67. const metas = [header('legacy-title', 100), header('uncached', 200)]
  68. const stat = vi.fn(async (id: SessionId) => statSnapshot(
  69. metas.find(meta => meta.id === id)!,
  70. { sizeBytes: 1 },
  71. ))
  72. const inspect = vi.fn(async (id: SessionId) => ({
  73. meta: metas.find(meta => meta.id === id)!,
  74. events: conversationEvents(),
  75. }))
  76. providePersistence(ctx, {
  77. list: () => Promise.resolve(metas),
  78. stat,
  79. inspect,
  80. })
  81. ctx.provide('sessionProjectionCache', {
  82. cachedSnapshot: () => undefined,
  83. cachedPredecessorTitle: (meta: SessionHeader) => meta.id === sid('legacy-title')
  84. ? { asOfSeq: 3, values: { title: 'Cached predecessor title' } }
  85. : undefined,
  86. } as never)
  87. const remote = createSessionTestRemote(ctx, {
  88. defaultModelSelection: () => ({ provider: 'p', model: 'm' }),
  89. cwd: '/tmp',
  90. })
  91. const observe = vi.spyOn(ctx.sessionQuery, 'observeSession')
  92. const response = await remote.list(request({}))
  93. if (!response.ok) throw new Error('list failed')
  94. expect(response.value.items).toEqual([
  95. expect.objectContaining({
  96. sessionId: sid('uncached'),
  97. blank: false,
  98. updatedAt: 200,
  99. }),
  100. expect.objectContaining({
  101. sessionId: sid('legacy-title'),
  102. blank: false,
  103. updatedAt: 100,
  104. projections: { asOfSeq: 3, values: { title: 'Cached predecessor title' } },
  105. }),
  106. ])
  107. expect(stat).not.toHaveBeenCalled()
  108. expect(inspect).not.toHaveBeenCalled()
  109. expect(observe).not.toHaveBeenCalled()
  110. })
  111. it('serves cold rows from current cached projections without body access', async () => {
  112. const ctx = new Context()
  113. await ctx.plugin(SessionStore)
  114. const metas: SessionHeader[] = [
  115. header('cached-blank', 100),
  116. header('cached-conversation', 200),
  117. header('uncached', 300, { parentSession: sid('session-parent'), origin: 'subagent' }),
  118. header('seeded-cold', 450, { isSeeded: true }),
  119. { version: SESSION_FORMAT_VERSION, id: sid('missing-cwd'), createdAt: 800, isSeeded: false },
  120. ]
  121. const inspect = vi.fn()
  122. providePersistence(ctx, {
  123. list: () => Promise.resolve(metas),
  124. inspect,
  125. })
  126. const cacheCalls: string[] = []
  127. ctx.provide('sessionProjectionCache', {
  128. cachedSnapshot: (meta: SessionHeader) => {
  129. cacheCalls.push(String(meta.id))
  130. if (meta.id === sid('cached-blank')) {
  131. return { asOfSeq: 0, values: { sessionListMetadata: { blank: true, lastPromptAt: null } } }
  132. }
  133. if (meta.id === sid('cached-conversation')) {
  134. return { asOfSeq: 1, values: { sessionListMetadata: { blank: false, lastPromptAt: 1000 } } }
  135. }
  136. return undefined
  137. },
  138. cachedPredecessorTitle: () => undefined,
  139. } as never)
  140. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  141. const response = await remote.list(request({}))
  142. expect(response.ok).toBe(true)
  143. if (!response.ok) throw new Error('unreachable')
  144. const byId = Object.fromEntries(response.value.items.map(item => [item.sessionId, item]))
  145. expect(byId['cached-blank']).toMatchObject({ blank: true, updatedAt: 100, running: false })
  146. expect(byId['cached-conversation']).toMatchObject({ blank: false, updatedAt: 1000 })
  147. // A cache miss leaves blankness unknown; the row stays visible without a body read.
  148. expect(byId['uncached']).toMatchObject({
  149. blank: false,
  150. updatedAt: 300,
  151. parentSessionId: 'session-parent',
  152. origin: 'subagent',
  153. })
  154. expect(byId['missing-cwd']).toBeUndefined()
  155. // A cold seeded header never consults the cache: its cut is not 0, so a
  156. // cut-0 lookup would alias a different projection identity.
  157. expect(byId['seeded-cold']).toMatchObject({ blank: false, updatedAt: 450 })
  158. expect(cacheCalls).not.toContain('seeded-cold')
  159. expect(inspect).not.toHaveBeenCalled()
  160. })
  161. it('prefers a live row attached during the query without folding its seed', async () => {
  162. const ctx = new Context()
  163. await ctx.plugin(SessionStore)
  164. await ctx.plugin(AgentRegistry)
  165. const meta = header('attached-during-list', 100)
  166. const started = Promise.withResolvers<undefined>()
  167. const release = Promise.withResolvers<undefined>()
  168. providePersistence(ctx, {
  169. list: async () => {
  170. started.resolve(undefined)
  171. await release.promise
  172. return [meta]
  173. },
  174. })
  175. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  176. const listing = remote.list(request({}))
  177. await started.promise
  178. const session = ctx.sessions.create(meta.id, {
  179. seed: [
  180. { type: 'turn/start', seq: SessionSeq(0), time: 200, data: { turn: 1 } },
  181. {
  182. type: 'user/message', seq: SessionSeq(1), time: 300,
  183. data: createUserMessage({ content: [{ type: 'text', text: 'live' }], source: { kind: 'user' } }),
  184. surfaceOp: 'append',
  185. },
  186. ],
  187. meta: {
  188. ...meta.cwd === undefined ? {} : { cwd: meta.cwd },
  189. createdAt: meta.createdAt,
  190. },
  191. })
  192. ctx.agents.register({ id: session.id, session, status: 'running', ctx } as Agent)
  193. release.resolve(undefined)
  194. const response = await listing
  195. if (!response.ok) throw new Error('list failed')
  196. expect(response.value.items).toEqual([
  197. expect.objectContaining({
  198. sessionId: meta.id,
  199. blank: false,
  200. running: true,
  201. updatedAt: 100,
  202. }),
  203. ])
  204. })
  205. })
  206. describe('attached updatedAt tracks human prompts', () => {
  207. it('ignores pickup and non-prompt work after the latest human message', async () => {
  208. const ctx = new Context()
  209. await ctx.plugin(SessionStore)
  210. await ctx.plugin(AgentRegistry)
  211. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  212. await new Promise(resolve => setTimeout(resolve, 0))
  213. // Old work, resumed just now: the log tail would report the pickup.
  214. const worked = 1_000_000
  215. const resumed = ctx.sessions.create(sid('resumed-untouched'), {
  216. seed: [
  217. { type: 'turn/start', seq: SessionSeq(0), time: worked, data: { turn: 1 } },
  218. {
  219. type: 'user/message', seq: SessionSeq(1), time: worked,
  220. data: createUserMessage({ content: [{ type: 'text', text: 'worked' }], source: { kind: 'user' } }),
  221. surfaceOp: 'append',
  222. },
  223. { type: 'turn/end', seq: SessionSeq(2), time: worked + 1, data: { turn: 1, reason: { kind: 'completed' } } },
  224. ],
  225. meta: { cwd: '/proj', createdAt: 500 },
  226. })
  227. ctx.agents.register({ id: resumed.id, session: resumed, status: 'idle', ctx } as Agent)
  228. const boundary = resumed.snapshotEvents().at(-1)
  229. expect(boundary?.type).toBe('session/end-seed')
  230. expect(boundary?.time).toBeGreaterThan(worked)
  231. const listed = await remote.list(request({}))
  232. if (!listed.ok) throw new Error('list failed')
  233. const summary = listed.value.items.find(item => item.sessionId === 'resumed-untouched')
  234. expect(summary?.updatedAt).toBe(500)
  235. // A lifecycle boundary is not a human update.
  236. resumed.append('turn/start', { turn: 2 })
  237. const afterBoundary = await remote.list(request({}))
  238. if (!afterBoundary.ok) throw new Error('list failed')
  239. expect(afterBoundary.value.items.find(item => item.sessionId === 'resumed-untouched')?.updatedAt)
  240. .toBe(worked)
  241. const prompt = resumed.append('user/message', createUserMessage({
  242. content: [{ type: 'text', text: 'new prompt' }],
  243. source: { kind: 'user' },
  244. }), { surfaceOp: 'append' })
  245. const after = await remote.list(request({}))
  246. if (!after.ok) throw new Error('list failed')
  247. const moved = after.value.items.find(item => item.sessionId === 'resumed-untouched')
  248. expect(moved?.updatedAt).toBe(prompt.time)
  249. })
  250. })
  251. describe('cold history recovery view', () => {
  252. it('serves the stored interrupted prefix verbatim without activating the session', async () => {
  253. // Semantic crash repair is the resuming agent loop's job (it appends the
  254. // closers durably through its write handle); a cold history read shows the
  255. // stored prefix exactly as persisted.
  256. const ctx = new Context()
  257. await ctx.plugin(SessionStore)
  258. const sessionId = sid('session-interrupted')
  259. const meta = header(sessionId, 1000)
  260. const events = [{ type: 'turn/start', seq: SessionSeq(0), time: 1, data: { turn: 1 } }] as SessionEvent[]
  261. providePersistence(ctx, {
  262. list: () => Promise.resolve([structuredClone(meta)]),
  263. inspect: () => Promise.resolve({ meta: structuredClone(meta), events: structuredClone(events) }),
  264. })
  265. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  266. const history = await remote.page({
  267. address: { kind: 'session', sessionId },
  268. throughSeq: 0,
  269. beforeSeq: 1,
  270. maxMessages: 10,
  271. })
  272. if (!history.ok) throw new Error('history failed')
  273. expect(history.value.records.map(record => record.event)).toMatchInlineSnapshot(`
  274. [
  275. {
  276. "data": {
  277. "turn": 1,
  278. },
  279. "seq": 0,
  280. "time": 1,
  281. "type": "turn/start",
  282. },
  283. ]
  284. `)
  285. expect(ctx.sessions.get(sessionId)).toBeUndefined()
  286. await ctx.fiber.dispose()
  287. })
  288. })
  289. describe('Remote Agent and Session lookup policy', () => {
  290. it('deduplicates a cold resume across Agent and Session parameters', async () => {
  291. const ctx = new Context()
  292. await ctx.plugin(TypertRegistry)
  293. await ctx.plugin(SessionStore)
  294. await ctx.plugin(AgentRegistry)
  295. const sessionId = sid('session-remote-cold')
  296. const meta = header(sessionId, 1000)
  297. const inspect = vi.fn(() => Promise.resolve({ meta, events: [] as SessionEvent[] }))
  298. providePersistence(ctx, {
  299. list: () => Promise.resolve([meta]),
  300. inspect,
  301. })
  302. const resumedSession = { id: sessionId, header: meta, events: [] } as unknown as import('@deepseek-ai/dsh-session').Session
  303. const resumedAgent = { id: sessionId, session: resumedSession, status: 'idle', ctx } as Agent
  304. const release = Promise.withResolvers<undefined>()
  305. const resume = vi.spyOn(ctx.agents, 'resume').mockImplementation(async () => {
  306. await release.promise
  307. return { agent: resumedAgent, dispose: () => Promise.resolve() }
  308. })
  309. const defaultAgentLookup = ctx.typert.lookups.get('agent')
  310. const defaultSessionLookup = ctx.typert.lookups.get('session')
  311. createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  312. await vi.waitFor(() => {
  313. expect(ctx.typert.lookups.get('agent')).not.toBe(defaultAgentLookup)
  314. expect(ctx.typert.lookups.get('session')).not.toBe(defaultSessionLookup)
  315. })
  316. const agentLookup = ctx.typert.lookups.get('agent')
  317. const sessionLookup = ctx.typert.lookups.get('session')
  318. if (agentLookup === undefined || sessionLookup === undefined) throw new Error('core lookup providers were not mounted')
  319. const resolvedAgent = Promise.resolve(agentLookup.resolve(sessionId))
  320. const resolvedSession = Promise.resolve(sessionLookup.resolve(sessionId))
  321. await vi.waitFor(() => { expect(resume).toHaveBeenCalledOnce() })
  322. release.resolve(undefined)
  323. await expect(resolvedAgent).resolves.toBe(resumedAgent)
  324. await expect(resolvedSession).resolves.toBe(resumedSession)
  325. expect(inspect).toHaveBeenCalledOnce()
  326. })
  327. it('preserves the subagent ownership fence for cold and live Remote lookups', async () => {
  328. const ctx = new Context()
  329. await ctx.plugin(TypertRegistry)
  330. await ctx.plugin(SessionStore)
  331. await ctx.plugin(AgentRegistry)
  332. const coldId = sid('session-remote-cold-child')
  333. const coldMeta = header(coldId, 1000, {
  334. parentSession: sid('session-parent'),
  335. origin: 'subagent',
  336. })
  337. const inspect = vi.fn(() => Promise.resolve({ meta: coldMeta, events: [] as SessionEvent[] }))
  338. providePersistence(ctx, {
  339. list: () => Promise.resolve([coldMeta]),
  340. inspect,
  341. })
  342. const liveSession = ctx.sessions.create(sid('session-remote-live-child'), {
  343. meta: { cwd: '/proj', parentSession: sid('session-parent'), origin: 'subagent' },
  344. })
  345. const liveAgent = { id: liveSession.id, session: liveSession, status: 'idle', ctx } as Agent
  346. ctx.agents.register(liveAgent)
  347. const resume = vi.spyOn(ctx.agents, 'resume')
  348. const defaultAgentLookup = ctx.typert.lookups.get('agent')
  349. const defaultSessionLookup = ctx.typert.lookups.get('session')
  350. createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  351. await vi.waitFor(() => {
  352. expect(ctx.typert.lookups.get('agent')).not.toBe(defaultAgentLookup)
  353. expect(ctx.typert.lookups.get('session')).not.toBe(defaultSessionLookup)
  354. })
  355. const agentLookup = ctx.typert.lookups.get('agent')
  356. const sessionLookup = ctx.typert.lookups.get('session')
  357. if (agentLookup === undefined || sessionLookup === undefined) throw new Error('core lookup providers were not mounted')
  358. const ownershipFailure = {
  359. code: 'session/agent-busy',
  360. details: { reason: 'use subagent delivery for this child session' },
  361. }
  362. const coldFailure = Promise.resolve(agentLookup.resolve(coldId))
  363. const liveFailure = Promise.resolve(sessionLookup.resolve(liveSession.id))
  364. await expect(coldFailure).rejects.toMatchObject(ownershipFailure)
  365. await expect(liveFailure).rejects.toMatchObject(ownershipFailure)
  366. expect(resume).not.toHaveBeenCalled()
  367. expect(inspect).toHaveBeenCalledOnce()
  368. })
  369. })
  370. describe('subagent ownership fence', () => {
  371. it('reads a cold child without an Agent and rejects generic resume or adoption', async () => {
  372. const ctx = new Context()
  373. await ctx.plugin(SessionStore)
  374. await ctx.plugin(AgentRegistry)
  375. const sessionId = sid('session-child')
  376. const meta = header('session-child', 1000, {
  377. parentSession: sid('session-parent'),
  378. origin: 'subagent',
  379. })
  380. const events = [
  381. { type: 'turn/start', seq: SessionSeq(0), time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  382. {
  383. type: 'user/message',
  384. seq: SessionSeq(1),
  385. time: 2,
  386. data: createUserMessage({ content: [{ type: 'text', text: 'work' }], source: { kind: 'user' } }),
  387. surfaceOp: 'append',
  388. },
  389. {
  390. type: 'subagent/descriptor',
  391. seq: SessionSeq(2),
  392. time: 3,
  393. data: snapshotSubagentDescriptor({
  394. mode: 'continuable',
  395. provider: 'spawn',
  396. label: 'child',
  397. }),
  398. },
  399. { type: 'turn/end', seq: SessionSeq(3), time: 4, data: { turn: 1, reason: { kind: 'completed' } } },
  400. ] as SessionEvent[]
  401. const inspect = vi.fn(() => Promise.resolve({ meta, events }))
  402. providePersistence(ctx, {
  403. list: () => Promise.resolve([meta]),
  404. inspect,
  405. })
  406. const resume = vi.spyOn(ctx.agents, 'resume')
  407. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  408. ctx.sessionProjections.register(subagentIdentityProjectionDefinition)
  409. const history = await new SessionHistoryController(
  410. ctx,
  411. (observation) => { observation[Symbol.dispose]() },
  412. ).page({
  413. address: {
  414. kind: 'subagent',
  415. parentSessionId: meta.parentSession as SessionId,
  416. childSessionId: sessionId,
  417. mode: 'continuable',
  418. },
  419. throughSeq: 3,
  420. }, new AbortController().signal)
  421. expect(history.records.map(record => record.event.type))
  422. .toEqual(events.map(event => event.type))
  423. expect(ctx.agents.get(sessionId)).toBeUndefined()
  424. const prompt = await remote.prompt(promptRequest({
  425. sessionId,
  426. mode: 'queue',
  427. content: [{ type: 'text', text: 'follow up' }],
  428. }))
  429. expect(prompt.ok).toBe(false)
  430. if (!prompt.ok) {
  431. expect(prompt.error).toMatchObject({
  432. code: 'session/agent-busy',
  433. details: { reason: 'use subagent delivery for this child session' },
  434. })
  435. }
  436. const create = await remote.create(request({ sessionId, cwd: '/proj' }))
  437. expect(create.ok).toBe(false)
  438. if (!create.ok) expect(create.error.code).toBe('session/agent-busy')
  439. expect(resume).not.toHaveBeenCalled()
  440. expect(ctx.agents.get(sessionId)).toBeUndefined()
  441. // One log open serves all three cold reads: the observation cache reuses
  442. // the prepared Session while the stat revision is unchanged.
  443. expect(inspect).toHaveBeenCalledTimes(1)
  444. })
  445. it('no longer treats a descriptor-only cold child without origin as subagent-owned', async () => {
  446. const ctx = new Context()
  447. await ctx.plugin(SessionStore)
  448. await ctx.plugin(AgentRegistry)
  449. const sessionId = sid('session-legacy-child')
  450. const meta = header('session-legacy-child', 1000, {
  451. parentSession: sid('session-parent'),
  452. })
  453. const events = [
  454. {
  455. type: 'subagent/descriptor',
  456. seq: SessionSeq(0),
  457. time: 1,
  458. data: { version: 2, mode: 'continuable', provider: 'spawn', label: 'child' },
  459. },
  460. ] as SessionEvent[]
  461. providePersistence(ctx, {
  462. list: () => Promise.resolve([meta]),
  463. inspect: () => Promise.resolve({ meta, events }) })
  464. // Stores whose headers predate `origin` classify a child only through the
  465. // descriptor event; the pre-release decision stops recognizing them, so
  466. // the ownership fence lets generic resume reach the registry instead of
  467. // answering `agent-busy`.
  468. const resume = vi.spyOn(ctx.agents, 'resume')
  469. .mockRejectedValue(new Error('registry unavailable in this bench'))
  470. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  471. const prompt = await remote.prompt(promptRequest({
  472. sessionId,
  473. mode: 'queue',
  474. content: [{ type: 'text', text: 'follow up' }],
  475. }))
  476. expect(resume).toHaveBeenCalledTimes(1)
  477. expect(prompt.ok).toBe(false)
  478. if (!prompt.ok) expect(prompt.error.code).toBe('gateway/internal')
  479. })
  480. it('rejects origin-marked and runtime-owned live children from generic controls', async () => {
  481. const ctx = new Context()
  482. await ctx.plugin(SessionStore)
  483. await ctx.plugin(AgentRegistry)
  484. const parentSession = ctx.sessions.create(sid('session-parent'), { meta: { cwd: '/proj' } })
  485. const parent = { id: parentSession.id, session: parentSession, status: 'idle', ctx } as Agent
  486. ctx.agents.register(parent)
  487. const originSession = ctx.sessions.create(sid('session-origin-child'), {
  488. meta: { cwd: '/proj', parentSession: parent.id, origin: 'subagent' },
  489. })
  490. const cancel = vi.fn()
  491. const updateInbox = vi.fn(() => 'applied' as const)
  492. const originChild = {
  493. id: originSession.id,
  494. session: originSession,
  495. status: 'idle',
  496. ctx,
  497. cancel,
  498. updateInbox,
  499. } as unknown as Agent
  500. ctx.agents.register(originChild)
  501. const startingSession = ctx.sessions.create(sid('session-starting-child'), {
  502. meta: { cwd: '/proj', parentSession: parent.id },
  503. })
  504. const startingChild = { id: startingSession.id, session: startingSession, status: 'idle', ctx } as Agent
  505. ctx.agents.enter(startingChild, parent)
  506. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  507. const stopped = await remote.cancel(request({ sessionId: originChild.id }))
  508. expect(stopped.ok).toBe(false)
  509. if (!stopped.ok) expect(stopped.error.code).toBe('session/agent-busy')
  510. expect(cancel).not.toHaveBeenCalled()
  511. const queued = await remote.updateQueue(request({
  512. sessionId: originChild.id,
  513. itemId: MessageId('queued-item'),
  514. action: { kind: 'remove' },
  515. }))
  516. expect(queued.ok).toBe(false)
  517. if (!queued.ok) expect(queued.error.code).toBe('session/agent-busy')
  518. expect(updateInbox).not.toHaveBeenCalled()
  519. const selection = await remote.selectModel(request({
  520. sessionId: startingChild.id,
  521. provider: 'p',
  522. model: 'm',
  523. }))
  524. expect(selection.ok).toBe(false)
  525. if (!selection.ok) expect(selection.error.code).toBe('session/agent-busy')
  526. const create = await remote.create(request({ sessionId: originChild.id, cwd: '/proj' }))
  527. expect(create.ok).toBe(false)
  528. if (!create.ok) expect(create.error.code).toBe('session/agent-busy')
  529. expect(ctx.agents.get(originChild.id)).toBe(originChild)
  530. })
  531. it('does not classify an ordinary fork from an inherited ancestor descriptor', async () => {
  532. const ctx = new Context()
  533. await ctx.plugin(SessionStore)
  534. await ctx.plugin(AgentRegistry)
  535. const session = ctx.sessions.create(sid('session-ordinary-fork'), {
  536. seed: [{
  537. type: 'subagent/descriptor',
  538. seq: SessionSeq(0),
  539. time: 1,
  540. data: { version: 2, mode: 'continuable', provider: 'spawn', label: 'ancestor' },
  541. }],
  542. meta: { cwd: '/proj', parentSession: sid('session-source'), isSeeded: true },
  543. inheritedEventCount: SessionLogOffset(1),
  544. })
  545. const followup = vi.fn()
  546. const agent = { id: session.id, session, status: 'idle', ctx, followup } as unknown as Agent
  547. ctx.agents.register(agent)
  548. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  549. const response = await remote.prompt(promptRequest({
  550. sessionId: agent.id,
  551. mode: 'queue',
  552. content: [{ type: 'text', text: 'ordinary work' }],
  553. }))
  554. expect(response.ok).toBe(true)
  555. expect(followup).toHaveBeenCalledOnce()
  556. })
  557. it('canonicalizes a supplied browser zone on the exact prompt and rejects invalid names', async () => {
  558. const ctx = new Context()
  559. await ctx.plugin(SessionStore)
  560. await ctx.plugin(AgentRegistry)
  561. const session = ctx.sessions.create(sid('session-browser-zone'), { meta: { cwd: '/proj' } })
  562. const followup = vi.fn()
  563. const agent = { id: session.id, session, status: 'idle', ctx, followup } as unknown as Agent
  564. ctx.agents.register(agent)
  565. const remote = createSessionTestRemote(ctx, {
  566. defaultModelSelection: () => ({ provider: 'p', model: 'm' }),
  567. cwd: '/tmp',
  568. })
  569. const alias = 'US/Pacific'
  570. const canonical = new Intl.DateTimeFormat('en-US', { timeZone: alias })
  571. .resolvedOptions().timeZone
  572. const zonedRequest = promptRequest({
  573. sessionId: agent.id,
  574. mode: 'queue' as const,
  575. content: [{ type: 'text' as const, text: 'zoned work' }],
  576. clientTimeZone: alias,
  577. })
  578. await expect(remote.prompt(zonedRequest)).resolves.toMatchObject({ ok: true })
  579. expect(followup).toHaveBeenNthCalledWith(1, expect.objectContaining({
  580. source: { kind: 'user', rpcId: zonedRequest.requestId, clientTimeZone: canonical },
  581. }))
  582. const utcRequest = promptRequest({
  583. sessionId: agent.id,
  584. mode: 'queue' as const,
  585. content: [{ type: 'text' as const, text: 'UTC work' }],
  586. clientTimeZone: 'UTC',
  587. })
  588. await expect(remote.prompt(utcRequest)).resolves.toMatchObject({ ok: true })
  589. expect(followup).toHaveBeenNthCalledWith(2, expect.objectContaining({
  590. source: { kind: 'user', rpcId: utcRequest.requestId, clientTimeZone: 'UTC' },
  591. }))
  592. const unzonedRequest = promptRequest({
  593. sessionId: agent.id,
  594. mode: 'queue' as const,
  595. content: [{ type: 'text' as const, text: 'headless work' }],
  596. })
  597. await expect(remote.prompt(unzonedRequest)).resolves.toMatchObject({ ok: true })
  598. expect(followup).toHaveBeenNthCalledWith(3, expect.objectContaining({
  599. source: { kind: 'user', rpcId: unzonedRequest.requestId },
  600. }))
  601. for (const clientTimeZone of ['', ' UTC', 'CST', 'Not/A_Real_Zone']) {
  602. const invalid = await remote.prompt(promptRequest({
  603. sessionId: agent.id,
  604. mode: 'queue' as const,
  605. content: [{ type: 'text' as const, text: 'invalid zone' }],
  606. clientTimeZone,
  607. }))
  608. expect(invalid).toMatchObject({
  609. ok: false,
  610. error: {
  611. code: 'session/invalid-time-zone',
  612. message: 'clientTimeZone must be UTC or a valid IANA Area/Location name',
  613. details: { value: clientTimeZone },
  614. },
  615. })
  616. }
  617. expect(followup).toHaveBeenCalledTimes(3)
  618. })
  619. })
  620. describe('degenerate composition (no persistence, no factory)', () => {
  621. it('lists no cold rows and reports an absent point source as not found', async () => {
  622. const ctx = new Context()
  623. await ctx.plugin(SessionStore)
  624. await ctx.plugin(AgentRegistry)
  625. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  626. const listed = await remote.list(request({}))
  627. expect(listed.ok).toBe(true)
  628. if (listed.ok) expect(listed.value.items).toEqual([])
  629. // No persistence means cold history cannot inspect a transcript.
  630. const response = await remote.page({
  631. address: { kind: 'session', sessionId: sid('session-ghost') },
  632. throughSeq: -1,
  633. })
  634. expect(response.ok).toBe(false)
  635. if (!response.ok) {
  636. expect(response.error.code).toBe('session/not-found')
  637. }
  638. })
  639. it('maps a missing direct persistence read to session-not-found', async () => {
  640. const ctx = new Context()
  641. await ctx.plugin(SessionStore)
  642. await ctx.plugin(AgentRegistry)
  643. const inspect = vi.fn()
  644. const stat = vi.fn(() => Promise.resolve(undefined))
  645. providePersistence(ctx, {
  646. list: () => Promise.resolve([]),
  647. stat,
  648. inspect,
  649. })
  650. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  651. const response = await remote.page({
  652. address: { kind: 'session', sessionId: sid('session-missing') },
  653. throughSeq: -1,
  654. })
  655. expect(response.ok).toBe(false)
  656. if (!response.ok) expect(response.error.code).toBe('session/not-found')
  657. // Absence is decided by the stat preflight; the log itself is never opened.
  658. expect(stat).toHaveBeenCalledOnce()
  659. expect(inspect).not.toHaveBeenCalled()
  660. })
  661. })
  662. describe('sessions.prompt synchronous rejection', () => {
  663. it('maps a synchronous send throw (disposed/invalid input) to agent-busy with the reason attached', async () => {
  664. const ctx = new Context()
  665. await ctx.plugin(SessionStore)
  666. await ctx.plugin(AgentRegistry)
  667. const session = ctx.sessions.create(sid('session-throwing'))
  668. // A live structural stub whose delivery verbs throw synchronously, the
  669. // shape a disposed loop presents at this gateway boundary.
  670. ctx.agents.register({
  671. id: session.id,
  672. session,
  673. status: 'idle',
  674. ctx,
  675. followup: () => { throw new Error('agent "session-throwing" lifecycle disposed') },
  676. steer: () => { throw new Error('agent "session-throwing" lifecycle disposed') },
  677. } as unknown as Agent)
  678. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  679. for (const mode of ['queue', 'steer'] as const) {
  680. const response = await remote.prompt(promptRequest({
  681. sessionId: session.id, mode, content: [{ type: 'text' as const, text: 'x' }],
  682. }))
  683. expect(response.ok).toBe(false)
  684. if (!response.ok) {
  685. expect(response.error.code).toBe('session/agent-busy')
  686. expect(response.error.message).toBe('prompt rejected')
  687. expect(response.error.details).toEqual({
  688. reason: 'Error: agent "session-throwing" lifecycle disposed',
  689. })
  690. }
  691. }
  692. })
  693. it('classifies a raced cold-resume ID collision as agent-busy', async () => {
  694. const ctx = new Context()
  695. await ctx.plugin(SessionStore)
  696. await ctx.plugin(AgentRegistry)
  697. const sessionId = sid('race-resume')
  698. const meta: SessionHeader = header('race-resume', 1000)
  699. providePersistence(ctx, {
  700. list: () => Promise.resolve([meta]),
  701. inspect: () => Promise.resolve({ meta, events: [] as SessionEvent[] }) })
  702. // The raced winner: a live parent-owned subagent publishes the identity
  703. // while the generic cold resume is in flight, so the resume collides.
  704. const parentSession = ctx.sessions.create(sid('race-parent'), { meta: { cwd: '/proj' } })
  705. const parent = { id: parentSession.id, session: parentSession, status: 'idle', ctx } as Agent
  706. ctx.agents.register(parent)
  707. const childSession = ctx.sessions.create(sessionId, {
  708. meta: { cwd: '/proj', parentSession: parent.id, origin: 'subagent' },
  709. })
  710. const child = { id: sessionId, session: childSession, status: 'idle', ctx } as unknown as Agent
  711. vi.spyOn(ctx.agents, 'resume').mockImplementationOnce(async () => {
  712. // The parent's `enter()` wins the identity between the pre-resume
  713. // re-check and publication; the generic resume then collides.
  714. ctx.agents.register(child)
  715. throw new Error('session id already published')
  716. })
  717. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  718. const selection = await remote.selectModel(request({ sessionId, provider: 'p', model: 'm' }))
  719. expect(selection.ok).toBe(false)
  720. if (!selection.ok) {
  721. expect(selection.error).toMatchObject({
  722. code: 'session/agent-busy',
  723. details: { reason: 'use subagent delivery for this child session' },
  724. })
  725. }
  726. })
  727. })