session-cold.host.spec.ts 30 KB

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