session-cold.host.spec.ts 30 KB

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