session-cold.host.spec.ts 32 KB

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