session-cold.host.spec.ts 36 KB

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