session-cold.host.spec.ts 30 KB

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