session-cold.host.spec.ts 36 KB

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