session-cold.host.spec.ts 32 KB

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