session-cold.host.spec.ts 37 KB

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