session-cold.host.spec.ts 34 KB

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