session-cold.host.spec.ts 38 KB

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