session-cold.host.spec.ts 32 KB

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