session-cold.host.spec.ts 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  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, { agentEvents, Inbox } 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 StoredPrefix,
  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 stored: StoredPrefix<never> = {
  338. meta,
  339. events: [{ type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }],
  340. revision: SessionPersistenceRevision('history-recovery-test:1'),
  341. }
  342. const backend: PersistenceBackend<never> = {
  343. name: 'history-recovery-test',
  344. loadStored: id => Promise.resolve(id === sessionId ? structuredClone(stored) : undefined),
  345. readStoredRevision: id => Promise.resolve(
  346. id === sessionId ? SessionPersistenceRevision('history-recovery-test:1') : undefined,
  347. ),
  348. appendBatch: () => Promise.resolve(),
  349. commitRepair: () => Promise.resolve(),
  350. list: () => Promise.resolve([structuredClone(meta)]),
  351. }
  352. const coordinator = new PersistenceCoordinator(ctx, backend)
  353. providePersistence(ctx, {
  354. list: (signal?: AbortSignal) => backend.list(signal),
  355. inspect: (id: SessionId, signal?: AbortSignal) => coordinator.inspect(id, signal),
  356. borrowSession: (id: SessionId, signal?: AbortSignal) => coordinator.borrowSession(id, signal),
  357. locate: () => undefined,
  358. })
  359. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  360. const history = await remote.page({
  361. address: { kind: 'session', sessionId },
  362. throughSeq: 1,
  363. beforeSeq: 2,
  364. maxMessages: 10,
  365. })
  366. if (!history.ok) throw new Error('history failed')
  367. expect(history.value.records.map(record => record.event)).toMatchInlineSnapshot(`
  368. [
  369. {
  370. "data": {
  371. "turn": 1,
  372. },
  373. "seq": 0,
  374. "time": 1,
  375. "type": "turn/start",
  376. },
  377. {
  378. "data": {
  379. "reason": {
  380. "kind": "interrupted",
  381. },
  382. "turn": 1,
  383. },
  384. "seq": 1,
  385. "time": 1,
  386. "type": "turn/end",
  387. },
  388. ]
  389. `)
  390. expect(ctx.sessions.get(sessionId)).toBeUndefined()
  391. await ctx.fiber.dispose()
  392. })
  393. })
  394. describe('Remote Agent and Session lookup policy', () => {
  395. it('resumes a cold session before mutating a restored queue row', async () => {
  396. const ctx = new Context()
  397. await ctx.plugin(SessionStore)
  398. await ctx.plugin(AgentRegistry)
  399. const sessionId = sid('session-cold-queue-mutation')
  400. const meta = header(sessionId, 1000)
  401. const message = createUserMessage({
  402. content: [{ type: 'text', text: 'survives restart' }],
  403. source: { kind: 'user' },
  404. })
  405. const events = [{
  406. type: 'agent/inbox/spliced',
  407. seq: 0,
  408. time: 1001,
  409. data: { target: 'next-turn', start: 0, inserted: [message] },
  410. }] as SessionEvent[]
  411. providePersistence(ctx, {
  412. list: () => Promise.resolve([meta]),
  413. inspect: () => Promise.resolve({ meta, events }),
  414. locate: () => undefined,
  415. })
  416. let resumedAgent: Agent | undefined
  417. const resume = vi.spyOn(ctx.agents, 'resume').mockImplementation(async () => {
  418. const session = ctx.sessions.create(sessionId, {
  419. seed: events,
  420. meta: { cwd: '/proj', createdAt: meta.createdAt },
  421. })
  422. resumedAgent = {
  423. id: session.id,
  424. options: {},
  425. session,
  426. inbox: undefined as never,
  427. status: 'idle',
  428. ctx,
  429. send() {},
  430. followup() {},
  431. steer() {},
  432. inject() {},
  433. cancel() {},
  434. runMaintenance: task => task(new AbortController().signal),
  435. whenIdle: () => Promise.resolve(),
  436. } satisfies Agent
  437. Object.assign(resumedAgent, {
  438. inbox: new Inbox(ctx, resumedAgent.session, agentEvents(ctx, resumedAgent)),
  439. })
  440. ctx.agents.register(resumedAgent)
  441. return { agent: resumedAgent, dispose: () => Promise.resolve() }
  442. })
  443. const remote = createSessionTestRemote(ctx, {
  444. defaultModelSelection: () => ({ provider: 'p', model: 'm' }),
  445. cwd: '/tmp',
  446. })
  447. const response = await remote.updateQueue(request({
  448. sessionId,
  449. itemId: message.id,
  450. action: { kind: 'remove' },
  451. }))
  452. expect(response).toEqual({ ok: true, value: { accepted: true } })
  453. expect(resume).toHaveBeenCalledOnce()
  454. expect(resumedAgent?.inbox.nextTurn).toEqual([])
  455. expect(resumedAgent?.session.events.at(-1)).toMatchObject({
  456. type: 'agent/inbox/spliced',
  457. data: { target: 'next-turn', start: 0, removedCount: 1, inserted: [], outcome: 'canceled' },
  458. })
  459. })
  460. it('keeps queue-item-not-found for a cold session when no persistence backend is composed', async () => {
  461. const ctx = new Context()
  462. await ctx.plugin(SessionStore)
  463. await ctx.plugin(AgentRegistry)
  464. const remote = createSessionTestRemote(ctx, {
  465. defaultModelSelection: () => ({ provider: 'p', model: 'm' }),
  466. cwd: '/tmp',
  467. })
  468. const response = await remote.updateQueue(request({
  469. sessionId: sid('session-no-persistence'),
  470. itemId: MessageId('queued-item'),
  471. action: { kind: 'remove' },
  472. }))
  473. expect(response.ok).toBe(false)
  474. if (!response.ok) expect(response.error.code).toBe('queue-item-not-found')
  475. })
  476. it('deduplicates a cold resume across Agent and Session parameters', async () => {
  477. const ctx = new Context()
  478. await ctx.plugin(TypertRegistry)
  479. await ctx.plugin(SessionStore)
  480. await ctx.plugin(AgentRegistry)
  481. const sessionId = sid('session-remote-cold')
  482. const meta = header(sessionId, 1000)
  483. const inspect = vi.fn(() => Promise.resolve({ meta, events: [] as SessionEvent[] }))
  484. providePersistence(ctx, {
  485. list: () => Promise.resolve([meta]),
  486. inspect,
  487. locate: () => undefined,
  488. })
  489. const resumedSession = { id: sessionId, header: meta, events: [] } as unknown as import('@deepseek-ai/dsh-session').Session
  490. const resumedAgent = { id: sessionId, session: resumedSession, status: 'idle', ctx } as Agent
  491. const release = Promise.withResolvers<undefined>()
  492. const resume = vi.spyOn(ctx.agents, 'resume').mockImplementation(async () => {
  493. await release.promise
  494. return { agent: resumedAgent, dispose: () => Promise.resolve() }
  495. })
  496. const defaultAgentLookup = ctx.typert.lookups.get('agent')
  497. const defaultSessionLookup = ctx.typert.lookups.get('session')
  498. createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  499. await vi.waitFor(() => {
  500. expect(ctx.typert.lookups.get('agent')).not.toBe(defaultAgentLookup)
  501. expect(ctx.typert.lookups.get('session')).not.toBe(defaultSessionLookup)
  502. })
  503. const agentLookup = ctx.typert.lookups.get('agent')
  504. const sessionLookup = ctx.typert.lookups.get('session')
  505. if (agentLookup === undefined || sessionLookup === undefined) throw new Error('core lookup providers were not mounted')
  506. const resolvedAgent = Promise.resolve(agentLookup.resolve(sessionId))
  507. const resolvedSession = Promise.resolve(sessionLookup.resolve(sessionId))
  508. await vi.waitFor(() => { expect(resume).toHaveBeenCalledOnce() })
  509. release.resolve(undefined)
  510. await expect(resolvedAgent).resolves.toBe(resumedAgent)
  511. await expect(resolvedSession).resolves.toBe(resumedSession)
  512. expect(inspect).toHaveBeenCalledOnce()
  513. })
  514. it('preserves the subagent ownership fence for cold and live Remote lookups', async () => {
  515. const ctx = new Context()
  516. await ctx.plugin(TypertRegistry)
  517. await ctx.plugin(SessionStore)
  518. await ctx.plugin(AgentRegistry)
  519. const coldId = sid('session-remote-cold-child')
  520. const coldMeta = header(coldId, 1000, {
  521. parentSession: sid('session-parent'),
  522. origin: 'subagent',
  523. })
  524. const inspect = vi.fn(() => Promise.resolve({ meta: coldMeta, events: [] as SessionEvent[] }))
  525. providePersistence(ctx, {
  526. list: () => Promise.resolve([coldMeta]),
  527. inspect,
  528. locate: () => undefined,
  529. })
  530. const liveSession = ctx.sessions.create(sid('session-remote-live-child'), {
  531. meta: { cwd: '/proj', parentSession: sid('session-parent'), origin: 'subagent' },
  532. })
  533. const liveAgent = { id: liveSession.id, session: liveSession, status: 'idle', ctx } as Agent
  534. ctx.agents.register(liveAgent)
  535. const resume = vi.spyOn(ctx.agents, 'resume')
  536. const defaultAgentLookup = ctx.typert.lookups.get('agent')
  537. const defaultSessionLookup = ctx.typert.lookups.get('session')
  538. createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  539. await vi.waitFor(() => {
  540. expect(ctx.typert.lookups.get('agent')).not.toBe(defaultAgentLookup)
  541. expect(ctx.typert.lookups.get('session')).not.toBe(defaultSessionLookup)
  542. })
  543. const agentLookup = ctx.typert.lookups.get('agent')
  544. const sessionLookup = ctx.typert.lookups.get('session')
  545. if (agentLookup === undefined || sessionLookup === undefined) throw new Error('core lookup providers were not mounted')
  546. const ownershipFailure = {
  547. failure: {
  548. code: 'agent-busy',
  549. details: { reason: 'use subagent delivery for this child session' },
  550. },
  551. }
  552. const coldFailure = Promise.resolve(agentLookup.resolve(coldId))
  553. const liveFailure = Promise.resolve(sessionLookup.resolve(liveSession.id))
  554. await expect(coldFailure).rejects.toBeInstanceOf(TypertLookupFailure)
  555. await expect(coldFailure).rejects.toMatchObject(ownershipFailure)
  556. await expect(liveFailure).rejects.toBeInstanceOf(TypertLookupFailure)
  557. await expect(liveFailure).rejects.toMatchObject(ownershipFailure)
  558. expect(resume).not.toHaveBeenCalled()
  559. expect(inspect).toHaveBeenCalledOnce()
  560. })
  561. it('reapplies the subagent ownership fence after a successful resume publishes the Agent', async () => {
  562. const ctx = new Context()
  563. await ctx.plugin(TypertRegistry)
  564. await ctx.plugin(SessionStore)
  565. await ctx.plugin(AgentRegistry)
  566. const sessionId = sid('session-remote-resumed-child')
  567. const meta = header(sessionId, 1000)
  568. providePersistence(ctx, {
  569. list: () => Promise.resolve([meta]),
  570. inspect: () => Promise.resolve({ meta, events: [] as SessionEvent[] }),
  571. locate: () => undefined,
  572. })
  573. vi.spyOn(ctx.agents, 'resume').mockImplementationOnce(async () => {
  574. const session = ctx.sessions.create(sessionId, {
  575. meta: { cwd: '/proj', origin: 'subagent' },
  576. })
  577. const published = { id: session.id, session, status: 'idle', ctx } as Agent
  578. ctx.agents.register(published)
  579. return { agent: published, dispose: () => Promise.resolve() }
  580. })
  581. const defaultLookup = ctx.typert.lookups.get('agent')
  582. createSessionTestRemote(ctx, {
  583. defaultModelSelection: () => ({ provider: 'p', model: 'm' }),
  584. cwd: '/tmp',
  585. })
  586. await vi.waitFor(() => { expect(ctx.typert.lookups.get('agent')).not.toBe(defaultLookup) })
  587. const lookup = ctx.typert.lookups.get('agent')
  588. if (lookup === undefined) throw new Error('Agent lookup provider was not mounted')
  589. const resolution = lookup.resolve(sessionId)
  590. await expect(resolution).rejects.toBeInstanceOf(TypertLookupFailure)
  591. await expect(resolution).rejects.toMatchObject({ failure: { code: 'agent-busy' } })
  592. })
  593. })
  594. describe('subagent ownership fence', () => {
  595. it('reads a cold child without an Agent and rejects generic resume or adoption', async () => {
  596. const ctx = new Context()
  597. await ctx.plugin(SessionStore)
  598. await ctx.plugin(AgentRegistry)
  599. const sessionId = sid('session-child')
  600. const meta = header('session-child', 1000, {
  601. parentSession: sid('session-parent'),
  602. seedLength: 0,
  603. origin: 'subagent',
  604. })
  605. const events = [
  606. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  607. {
  608. type: 'user/message',
  609. seq: 1,
  610. time: 2,
  611. data: createUserMessage({ content: [{ type: 'text', text: 'work' }], source: { kind: 'user' } }),
  612. surfaceOp: 'append',
  613. },
  614. {
  615. type: 'subagent/descriptor',
  616. seq: 2,
  617. time: 3,
  618. data: snapshotSubagentDescriptor({
  619. mode: 'continuable',
  620. provider: 'spawn',
  621. label: 'child',
  622. }),
  623. },
  624. { type: 'turn/end', seq: 3, time: 4, data: { turn: 1, reason: { kind: 'completed' } } },
  625. ] as SessionEvent[]
  626. const inspect = vi.fn(() => Promise.resolve({ meta, events }))
  627. providePersistence(ctx, {
  628. list: () => Promise.resolve([meta]),
  629. inspect,
  630. locate: () => undefined,
  631. })
  632. const resume = vi.spyOn(ctx.agents, 'resume')
  633. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  634. ctx.sessionProjections.register(subagentIdentityProjectionDefinition)
  635. const history = await new SessionHistoryController(
  636. ctx,
  637. (observation) => { observation[Symbol.dispose]() },
  638. ).page({
  639. address: {
  640. kind: 'subagent',
  641. parentSessionId: meta.parentSession as SessionId,
  642. childSessionId: sessionId,
  643. mode: 'continuable',
  644. },
  645. throughSeq: 3,
  646. }, new AbortController().signal)
  647. expect(history.records.map(record => record.event.type))
  648. .toEqual(events.map(event => event.type))
  649. expect(ctx.agents.get(sessionId)).toBeUndefined()
  650. const prompt = await remote.prompt(promptRequest({
  651. sessionId,
  652. mode: 'queue',
  653. content: [{ type: 'text', text: 'follow up' }],
  654. }))
  655. expect(prompt.ok).toBe(false)
  656. if (!prompt.ok) {
  657. expect(prompt.error).toMatchObject({
  658. code: 'agent-busy',
  659. details: { reason: 'use subagent delivery for this child session' },
  660. })
  661. }
  662. const create = await remote.create(request({ sessionId, cwd: '/proj' }))
  663. expect(create.ok).toBe(false)
  664. if (!create.ok) expect(create.error.code).toBe('agent-busy')
  665. expect(resume).not.toHaveBeenCalled()
  666. expect(ctx.agents.get(sessionId)).toBeUndefined()
  667. expect(inspect).toHaveBeenCalledTimes(3)
  668. })
  669. it('no longer treats a descriptor-only cold child without origin as subagent-owned', async () => {
  670. const ctx = new Context()
  671. await ctx.plugin(SessionStore)
  672. await ctx.plugin(AgentRegistry)
  673. const sessionId = sid('session-legacy-child')
  674. const meta = header('session-legacy-child', 1000, {
  675. parentSession: sid('session-parent'),
  676. seedLength: 0,
  677. })
  678. const events = [
  679. {
  680. type: 'subagent/descriptor',
  681. seq: 0,
  682. time: 1,
  683. data: { version: 2, mode: 'continuable', provider: 'spawn', label: 'child' },
  684. },
  685. ] as SessionEvent[]
  686. providePersistence(ctx, {
  687. list: () => Promise.resolve([meta]),
  688. inspect: () => Promise.resolve({ meta, events }),
  689. locate: () => undefined,
  690. })
  691. // Stores whose headers predate `origin` classify a child only through the
  692. // descriptor event; the pre-release decision stops recognizing them, so
  693. // the ownership fence lets generic resume reach the registry instead of
  694. // answering `agent-busy`.
  695. const resume = vi.spyOn(ctx.agents, 'resume')
  696. .mockRejectedValue(new Error('registry unavailable in this bench'))
  697. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  698. const prompt = await remote.prompt(promptRequest({
  699. sessionId,
  700. mode: 'queue',
  701. content: [{ type: 'text', text: 'follow up' }],
  702. }))
  703. expect(resume).toHaveBeenCalledTimes(1)
  704. expect(prompt.ok).toBe(false)
  705. if (!prompt.ok) expect(prompt.error.code).toBe('internal')
  706. })
  707. it('rejects origin-marked and runtime-owned live children from generic controls', async () => {
  708. const ctx = new Context()
  709. await ctx.plugin(SessionStore)
  710. await ctx.plugin(AgentRegistry)
  711. const parentSession = ctx.sessions.create(sid('session-parent'), { meta: { cwd: '/proj' } })
  712. const parent = { id: parentSession.id, session: parentSession, status: 'idle', ctx } as Agent
  713. ctx.agents.register(parent)
  714. const originSession = ctx.sessions.create(sid('session-origin-child'), {
  715. meta: { cwd: '/proj', parentSession: parent.id, origin: 'subagent' },
  716. })
  717. const cancel = vi.fn()
  718. const updateInbox = vi.fn(() => 'applied' as const)
  719. const originChild = {
  720. id: originSession.id,
  721. session: originSession,
  722. status: 'idle',
  723. ctx,
  724. cancel,
  725. updateInbox,
  726. } as unknown as Agent
  727. ctx.agents.register(originChild)
  728. const startingSession = ctx.sessions.create(sid('session-starting-child'), {
  729. meta: { cwd: '/proj', parentSession: parent.id },
  730. })
  731. const startingChild = { id: startingSession.id, session: startingSession, status: 'idle', ctx } as Agent
  732. ctx.agents.enter(startingChild, parent)
  733. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  734. const stopped = await remote.cancel(request({ sessionId: originChild.id }))
  735. expect(stopped.ok).toBe(false)
  736. if (!stopped.ok) expect(stopped.error.code).toBe('agent-busy')
  737. expect(cancel).not.toHaveBeenCalled()
  738. const queued = await remote.updateQueue(request({
  739. sessionId: originChild.id,
  740. itemId: MessageId('queued-item'),
  741. action: { kind: 'remove' },
  742. }))
  743. expect(queued.ok).toBe(false)
  744. if (!queued.ok) expect(queued.error.code).toBe('agent-busy')
  745. expect(updateInbox).not.toHaveBeenCalled()
  746. const selection = await remote.selectModel(request({
  747. sessionId: startingChild.id,
  748. provider: 'p',
  749. model: 'm',
  750. }))
  751. expect(selection.ok).toBe(false)
  752. if (!selection.ok) expect(selection.error.code).toBe('agent-busy')
  753. const create = await remote.create(request({ sessionId: originChild.id, cwd: '/proj' }))
  754. expect(create.ok).toBe(false)
  755. if (!create.ok) expect(create.error.code).toBe('agent-busy')
  756. expect(ctx.agents.get(originChild.id)).toBe(originChild)
  757. })
  758. it('does not classify an ordinary fork from an inherited ancestor descriptor', async () => {
  759. const ctx = new Context()
  760. await ctx.plugin(SessionStore)
  761. await ctx.plugin(AgentRegistry)
  762. const session = ctx.sessions.create(sid('session-ordinary-fork'), {
  763. seed: [{
  764. type: 'subagent/descriptor',
  765. seq: 0,
  766. time: 1,
  767. data: { version: 2, mode: 'continuable', provider: 'spawn', label: 'ancestor' },
  768. }],
  769. meta: { cwd: '/proj', parentSession: sid('session-source'), seedLength: 1 },
  770. })
  771. const followup = vi.fn()
  772. const agent = { id: session.id, session, status: 'idle', ctx, followup } as unknown as Agent
  773. ctx.agents.register(agent)
  774. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  775. const response = await remote.prompt(promptRequest({
  776. sessionId: agent.id,
  777. mode: 'queue',
  778. content: [{ type: 'text', text: 'ordinary work' }],
  779. }))
  780. expect(response.ok).toBe(true)
  781. expect(followup).toHaveBeenCalledOnce()
  782. })
  783. it('canonicalizes a supplied browser zone on the exact prompt and rejects invalid names', async () => {
  784. const ctx = new Context()
  785. await ctx.plugin(SessionStore)
  786. await ctx.plugin(AgentRegistry)
  787. const session = ctx.sessions.create(sid('session-browser-zone'), { meta: { cwd: '/proj' } })
  788. const followup = vi.fn()
  789. const agent = { id: session.id, session, status: 'idle', ctx, followup } as unknown as Agent
  790. ctx.agents.register(agent)
  791. const remote = createSessionTestRemote(ctx, {
  792. defaultModelSelection: () => ({ provider: 'p', model: 'm' }),
  793. cwd: '/tmp',
  794. })
  795. const alias = 'US/Pacific'
  796. const canonical = new Intl.DateTimeFormat('en-US', { timeZone: alias })
  797. .resolvedOptions().timeZone
  798. const zonedRequest = promptRequest({
  799. sessionId: agent.id,
  800. mode: 'queue' as const,
  801. content: [{ type: 'text' as const, text: 'zoned work' }],
  802. clientTimeZone: alias,
  803. })
  804. await expect(remote.prompt(zonedRequest)).resolves.toMatchObject({ ok: true })
  805. expect(followup).toHaveBeenNthCalledWith(1, expect.objectContaining({
  806. source: { kind: 'user', rpcId: zonedRequest.requestId, clientTimeZone: canonical },
  807. }))
  808. const utcRequest = promptRequest({
  809. sessionId: agent.id,
  810. mode: 'queue' as const,
  811. content: [{ type: 'text' as const, text: 'UTC work' }],
  812. clientTimeZone: 'UTC',
  813. })
  814. await expect(remote.prompt(utcRequest)).resolves.toMatchObject({ ok: true })
  815. expect(followup).toHaveBeenNthCalledWith(2, expect.objectContaining({
  816. source: { kind: 'user', rpcId: utcRequest.requestId, clientTimeZone: 'UTC' },
  817. }))
  818. const unzonedRequest = promptRequest({
  819. sessionId: agent.id,
  820. mode: 'queue' as const,
  821. content: [{ type: 'text' as const, text: 'headless work' }],
  822. })
  823. await expect(remote.prompt(unzonedRequest)).resolves.toMatchObject({ ok: true })
  824. expect(followup).toHaveBeenNthCalledWith(3, expect.objectContaining({
  825. source: { kind: 'user', rpcId: unzonedRequest.requestId },
  826. }))
  827. for (const clientTimeZone of ['', ' UTC', 'CST', 'Not/A_Real_Zone']) {
  828. const invalid = await remote.prompt(promptRequest({
  829. sessionId: agent.id,
  830. mode: 'queue' as const,
  831. content: [{ type: 'text' as const, text: 'invalid zone' }],
  832. clientTimeZone,
  833. }))
  834. expect(invalid).toEqual({
  835. ok: false,
  836. error: {
  837. code: 'invalid-time-zone',
  838. message: 'clientTimeZone must be UTC or a valid IANA Area/Location name',
  839. details: { value: clientTimeZone },
  840. },
  841. })
  842. }
  843. expect(followup).toHaveBeenCalledTimes(3)
  844. })
  845. })
  846. describe('degenerate composition (no persistence, no factory)', () => {
  847. it('lists no cold rows and reports an absent point source as not found', async () => {
  848. const ctx = new Context()
  849. await ctx.plugin(SessionStore)
  850. await ctx.plugin(AgentRegistry)
  851. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  852. const listed = await remote.list(request({}))
  853. expect(listed.ok).toBe(true)
  854. if (listed.ok) expect(listed.value.items).toEqual([])
  855. // No persistence means cold history cannot inspect a transcript.
  856. const response = await remote.page({
  857. address: { kind: 'session', sessionId: sid('session-ghost') },
  858. throughSeq: -1,
  859. })
  860. expect(response.ok).toBe(false)
  861. if (!response.ok) {
  862. expect(response.error.code).toBe('session-not-found')
  863. }
  864. })
  865. it('maps a missing direct persistence read to session-not-found', async () => {
  866. const ctx = new Context()
  867. await ctx.plugin(SessionStore)
  868. await ctx.plugin(AgentRegistry)
  869. const inspect = vi.fn()
  870. providePersistence(ctx, {
  871. list: () => Promise.resolve([]),
  872. inspect,
  873. })
  874. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  875. const response = await remote.page({
  876. address: { kind: 'session', sessionId: sid('session-missing') },
  877. throughSeq: -1,
  878. })
  879. expect(response.ok).toBe(false)
  880. if (!response.ok) expect(response.error.code).toBe('session-not-found')
  881. expect(inspect).toHaveBeenCalledOnce()
  882. })
  883. })
  884. describe('sessions.prompt synchronous rejection', () => {
  885. it('maps a synchronous send throw (disposed/invalid input) to agent-busy with the reason attached', async () => {
  886. const ctx = new Context()
  887. await ctx.plugin(SessionStore)
  888. await ctx.plugin(AgentRegistry)
  889. const session = ctx.sessions.create(sid('session-throwing'))
  890. // A live structural stub whose delivery verbs throw synchronously, the
  891. // shape a disposed loop presents at this gateway boundary.
  892. ctx.agents.register({
  893. id: session.id,
  894. session,
  895. status: 'idle',
  896. ctx,
  897. followup: () => { throw new Error('agent "session-throwing" lifecycle disposed') },
  898. steer: () => { throw new Error('agent "session-throwing" lifecycle disposed') },
  899. } as unknown as Agent)
  900. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  901. for (const mode of ['queue', 'steer'] as const) {
  902. const response = await remote.prompt(promptRequest({
  903. sessionId: session.id, mode, content: [{ type: 'text' as const, text: 'x' }],
  904. }))
  905. expect(response.ok).toBe(false)
  906. if (!response.ok) {
  907. expect(response.error.code).toBe('agent-busy')
  908. expect(response.error.message).toBe('prompt rejected')
  909. expect(response.error.details).toEqual({
  910. reason: 'Error: agent "session-throwing" lifecycle disposed',
  911. })
  912. }
  913. }
  914. })
  915. it('classifies a raced cold-resume ID collision as agent-busy', async () => {
  916. const ctx = new Context()
  917. await ctx.plugin(SessionStore)
  918. await ctx.plugin(AgentRegistry)
  919. const sessionId = sid('race-resume')
  920. const meta: SessionHeader = header('race-resume', 1000)
  921. providePersistence(ctx, {
  922. list: () => Promise.resolve([meta]),
  923. inspect: () => Promise.resolve({ meta, events: [] as SessionEvent[] }),
  924. locate: () => undefined,
  925. })
  926. // The raced winner: a live parent-owned subagent publishes the identity
  927. // while the generic cold resume is in flight, so the resume collides.
  928. const parentSession = ctx.sessions.create(sid('race-parent'), { meta: { cwd: '/proj' } })
  929. const parent = { id: parentSession.id, session: parentSession, status: 'idle', ctx } as Agent
  930. ctx.agents.register(parent)
  931. const childSession = ctx.sessions.create(sessionId, {
  932. meta: { cwd: '/proj', parentSession: parent.id, origin: 'subagent' },
  933. })
  934. const child = { id: sessionId, session: childSession, status: 'idle', ctx } as unknown as Agent
  935. vi.spyOn(ctx.agents, 'resume').mockImplementationOnce(async () => {
  936. // The parent's `enter()` wins the identity between the pre-resume
  937. // re-check and publication; the generic resume then collides.
  938. ctx.agents.register(child)
  939. throw new Error('session id already published')
  940. })
  941. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  942. const selection = await remote.selectModel(request({ sessionId, provider: 'p', model: 'm' }))
  943. expect(selection.ok).toBe(false)
  944. if (!selection.ok) {
  945. expect(selection.error).toMatchObject({
  946. code: 'agent-busy',
  947. details: { reason: 'use subagent delivery for this child session' },
  948. })
  949. }
  950. })
  951. })