sessions-service.client.spec.ts 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210
  1. /**
  2. * ClientSessions: list store projection (manager → {ids, byId, current}
  3. * with derived titles), the current-selection account (open validation and
  4. * persisted mask semantics), scope-tree
  5. * lifecycle (lazy mint / frozen survival / removed teardown with staged
  6. * deferral — the stage follows list.current), binding identity, breadcrumb
  7. * projection, create.
  8. */
  9. import { Context } from '@deepseek-ai/cordis'
  10. import { afterEach, describe, expect, it, vi } from 'vitest'
  11. import type { SessionId } from '@deepseek-ai/dsh-api-remotes/client'
  12. import { RemoteError } from '@deepseek-ai/dsh-typert-protocol'
  13. import { LlmAttemptId } from '@deepseek-ai/dsh-llm'
  14. import { RemoteStreamCarrierError } from '@deepseek-ai/dsh-api-gateway/client'
  15. import { ClientSessions, SessionCreateError } from '../src/client/sessions/service.ts'
  16. import { scopeOf } from '../src/client/scope.ts'
  17. import type { SessionFollowFrame } from '../src/types.ts'
  18. import {
  19. FakeApiClient,
  20. deferred,
  21. err,
  22. fakeRemote,
  23. ok,
  24. type RuntimeRemotes,
  25. } from './fake-api.client.ts'
  26. const sid = (s: string): SessionId => s as SessionId
  27. interface Bench {
  28. ctx: Context
  29. api: FakeApiClient
  30. svc: ClientSessions
  31. }
  32. function bench(configureRemote?: (remote: RuntimeRemotes) => RuntimeRemotes): Bench {
  33. const ctx = new Context()
  34. const api = new FakeApiClient()
  35. const remote = fakeRemote(api)
  36. const svc = new ClientSessions(ctx, configureRemote?.(remote) ?? remote)
  37. return { ctx, api, svc }
  38. }
  39. /** Refresh the manager list from programmable rows and flush the microtask batch. */
  40. type FeedRow = {
  41. id: string
  42. cwd?: string
  43. parentId?: string
  44. origin?: 'subagent'
  45. running?: boolean
  46. blank?: boolean
  47. projections?: Record<string, unknown>
  48. }
  49. async function feedList(b: Bench, rows: FeedRow[]): Promise<void> {
  50. b.api.onList = () => Promise.resolve(ok({
  51. items: rows.map(r => ({
  52. sessionId: sid(r.id), updatedAt: 1, running: r.running ?? false, blank: r.blank ?? false,
  53. ...(r.cwd !== undefined ? { cwd: r.cwd } : {}),
  54. ...(r.parentId !== undefined ? { parentSessionId: sid(r.parentId) } : {}),
  55. ...(r.origin !== undefined ? { origin: r.origin } : {}),
  56. ...(r.projections === undefined
  57. ? {}
  58. : { projections: { asOfSeq: 0, values: r.projections } }),
  59. })),
  60. }) as never)
  61. await b.svc.refresh()
  62. await Promise.resolve() // manager notifier flush
  63. }
  64. describe('list store projection', () => {
  65. it('projects durable titles separately from cwd/id display fallbacks and parent links', async () => {
  66. const b = bench()
  67. b.svc.handleControlFrame({
  68. type: 'projection', sessionId: sid('s1'), key: 'title', value: 'Durable title', seq: 2,
  69. })
  70. await feedList(b, [
  71. { id: 's1', cwd: '/home/u/proj-a/' },
  72. { id: 's2', parentId: 's1', origin: 'subagent', running: true },
  73. ])
  74. const state = b.svc.list.getSnapshot()
  75. expect(state.ids).toEqual(['s1', 's2'])
  76. expect(state.byId[sid('s1')]).toMatchObject({ title: 'Durable title', displayTitle: 'Durable title', cwd: '/home/u/proj-a/' })
  77. expect(state.byId[sid('s2')]).toMatchObject({
  78. displayTitle: 's2', parentId: 's1', origin: 'subagent', running: true,
  79. })
  80. expect(state.byId[sid('s2')]?.title).toBeUndefined()
  81. })
  82. it('reprojects a blank session from the generic agent-preset projection', async () => {
  83. const b = bench()
  84. await feedList(b, [{ id: 's1', blank: true, projections: { agentPreset: 'standard' } }])
  85. expect(b.svc.list.getSnapshot().byId[sid('s1')]?.projectionValues?.agentPreset).toBe('standard')
  86. b.svc.handleControlFrame({
  87. type: 'projection', sessionId: sid('s1'), key: 'agentPreset', value: 'minimal', seq: 1,
  88. })
  89. await Promise.resolve()
  90. expect(b.svc.list.getSnapshot().byId[sid('s1')]?.projectionValues?.agentPreset).toBe('minimal')
  91. })
  92. it('reflects live increments (host stream via manager) into the store', async () => {
  93. const b = bench()
  94. await feedList(b, [{ id: 's1' }])
  95. b.svc.handleSessionAdded({
  96. sessionId: sid('s2'), updatedAt: 2, running: false, blank: true,
  97. })
  98. await Promise.resolve()
  99. expect(b.svc.list.getSnapshot().ids).toContain('s2')
  100. })
  101. })
  102. describe('search', () => {
  103. it('delegates transient content search without changing the list snapshot', async () => {
  104. const b = bench()
  105. await feedList(b, [{ id: 's1' }])
  106. const before = b.svc.list.getSnapshot()
  107. b.api.onSearch = () => Promise.resolve(ok({
  108. items: [{ sessionId: sid('s1'), snippet: 'matching excerpt' }],
  109. hasMore: false,
  110. }))
  111. const signal = new AbortController().signal
  112. await expect(b.svc.search('needle', signal)).resolves.toEqual({
  113. ok: true,
  114. value: {
  115. items: [{ sessionId: 's1', snippet: 'matching excerpt' }],
  116. hasMore: false,
  117. },
  118. })
  119. expect(b.api.lastSearchSignal).toBe(signal)
  120. expect(b.svc.list.getSnapshot()).toBe(before)
  121. })
  122. })
  123. describe('scope tree', () => {
  124. it('publishes live assistant chunks and durable settlement atomically through one event source', async () => {
  125. const b = bench()
  126. await feedList(b, [{ id: 's1' }])
  127. b.svc.open(sid('s1'))
  128. const binding = b.svc.binding(sid('s1'))
  129. if (binding === undefined) throw new Error('expected Session binding')
  130. await vi.waitFor(() => {
  131. expect(binding.session.getSnapshot().openState).toBe('open')
  132. })
  133. const attemptId = LlmAttemptId('web-live-attempt')
  134. const durableChunk = {
  135. type: 'event' as const,
  136. event: {
  137. type: 'assistant/chunk', seq: 0, time: 1,
  138. data: { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'live' } },
  139. },
  140. }
  141. const durableMessage = {
  142. type: 'event' as const,
  143. event: {
  144. type: 'assistant/message', seq: 1, time: 2,
  145. data: {
  146. turn: 1,
  147. step: 1,
  148. message: {
  149. role: 'assistant',
  150. content: [{ type: 'text', text: 'live' }],
  151. source: { kind: 'model', provider: 'p', model: 'm' },
  152. id: 'message-1',
  153. },
  154. },
  155. sourceEventSeqs: [0],
  156. surfaceOp: 'append' as const,
  157. },
  158. }
  159. const publications: string[][] = []
  160. const dispose = binding.eventSource.subscribe(() => {
  161. publications.push(binding.eventSource.getSnapshot().entries.map(entry => entry.event.type))
  162. })
  163. await b.api.pushFollow(sid('s1'), {
  164. type: 'assistant-stream',
  165. frame: {
  166. type: 'start', attemptId, revision: 1, startedTime: 1,
  167. turn: 1, step: 1,
  168. },
  169. })
  170. await b.api.pushFollow(sid('s1'), durableChunk)
  171. await Promise.resolve()
  172. expect(binding.eventSource.getSnapshot().entries).toEqual([])
  173. await b.api.pushFollow(sid('s1'), {
  174. type: 'assistant-stream',
  175. frame: {
  176. type: 'chunk', attemptId, revision: 2, index: 0,
  177. chunk: durableChunk.event.data.chunk,
  178. legacyChunkSeq: 0,
  179. },
  180. })
  181. await vi.waitFor(() => {
  182. expect(binding.eventSource.getSnapshot().entries).toHaveLength(1)
  183. })
  184. await b.api.pushFollow(sid('s1'), durableMessage)
  185. await Promise.resolve()
  186. expect(binding.eventSource.getSnapshot().entries).toHaveLength(1)
  187. await b.api.pushFollow(sid('s1'), {
  188. type: 'assistant-stream',
  189. frame: {
  190. type: 'end', attemptId, revision: 3, index: 1,
  191. outcome: 'committed',
  192. legacyChunkSeqs: [0],
  193. },
  194. })
  195. await vi.waitFor(() => {
  196. expect(binding.eventSource.getSnapshot().entries).toHaveLength(2)
  197. })
  198. expect(publications).toEqual([
  199. ['assistant/chunk'],
  200. ['assistant/chunk', 'assistant/message'],
  201. ])
  202. dispose()
  203. })
  204. it('replaces an active assistant baseline on reconnect without duplicate chunks', async () => {
  205. const b = bench()
  206. const attemptId = LlmAttemptId('reconnect-attempt')
  207. const first = {
  208. type: 'event' as const,
  209. event: {
  210. type: 'assistant/chunk', seq: 0, time: 1,
  211. data: { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'a' } },
  212. },
  213. }
  214. const second = {
  215. type: 'event' as const,
  216. event: {
  217. type: 'assistant/chunk', seq: 1, time: 2,
  218. data: { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'b' } },
  219. },
  220. }
  221. let records = [first] as never[]
  222. b.api.onHistory = () => Promise.resolve(ok({ records, hasMore: false }))
  223. b.api.assistantStreamBaseline = {
  224. revision: 2,
  225. attempts: [{
  226. attemptId, startedTime: 1, turn: 1, step: 1,
  227. chunks: [first.event.data.chunk], legacyChunkSeqs: [0],
  228. }],
  229. }
  230. await feedList(b, [{ id: 's1' }])
  231. b.svc.open(sid('s1'))
  232. const binding = b.svc.binding(sid('s1'))
  233. if (binding === undefined) throw new Error('expected Session binding')
  234. await vi.waitFor(() => {
  235. expect(binding.eventSource.getSnapshot().entries).toHaveLength(1)
  236. })
  237. records = [first, second] as never[]
  238. b.api.assistantStreamBaseline = {
  239. revision: 3,
  240. attempts: [{
  241. attemptId, startedTime: 1, turn: 1, step: 1,
  242. chunks: [first.event.data.chunk, second.event.data.chunk],
  243. legacyChunkSeqs: [0, 1],
  244. }],
  245. }
  246. b.api.failStreams(new RemoteStreamCarrierError('lost'))
  247. await vi.waitFor(() => {
  248. expect(b.api.followStarts.filter(id => id === sid('s1'))).toHaveLength(2)
  249. expect(binding.eventSource.getSnapshot().entries).toHaveLength(2)
  250. })
  251. expect(binding.eventSource.getSnapshot().entries.map(entry => entry.event.seq)).toEqual([0, 1])
  252. })
  253. it('publishes a baseline-framed chunk when its durable event follows the opening cut', async () => {
  254. const b = bench()
  255. const attemptId = LlmAttemptId('opening-cut-attempt')
  256. const chunk = {
  257. type: 'event' as const,
  258. event: {
  259. type: 'assistant/chunk', seq: 0, time: 1,
  260. data: { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'late durable' } },
  261. },
  262. }
  263. b.api.onHistory = () => Promise.resolve(ok({ records: [], hasMore: false }))
  264. b.api.followCursor = -1
  265. b.api.assistantStreamBaseline = {
  266. revision: 2,
  267. attempts: [{
  268. attemptId, startedTime: 1, turn: 1, step: 1,
  269. chunks: [chunk.event.data.chunk], legacyChunkSeqs: [0],
  270. }],
  271. }
  272. await feedList(b, [{ id: 's1' }])
  273. b.svc.open(sid('s1'))
  274. const binding = b.svc.binding(sid('s1'))
  275. if (binding === undefined) throw new Error('expected Session binding')
  276. await vi.waitFor(() => {
  277. expect(binding.session.getSnapshot().openState).toBe('open')
  278. })
  279. await b.api.pushFollow(sid('s1'), chunk)
  280. await vi.waitFor(() => {
  281. expect(binding.eventSource.getSnapshot().entries.map(entry => entry.event.seq)).toEqual([0])
  282. })
  283. expect(b.api.followStarts.filter(id => id === sid('s1'))).toHaveLength(1)
  284. })
  285. it('stages a reconnect-tail assistant settlement behind its exact active attempt', async () => {
  286. const b = bench()
  287. const attemptId = LlmAttemptId('reconnect-settlement-attempt')
  288. const priorChunk = {
  289. type: 'event' as const,
  290. event: {
  291. type: 'assistant/chunk', seq: 0, time: 10,
  292. data: { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'retry ' } },
  293. },
  294. }
  295. const priorMessage = {
  296. type: 'event' as const,
  297. event: {
  298. type: 'assistant/message', seq: 1, time: 11,
  299. data: {
  300. turn: 1,
  301. step: 1,
  302. message: {
  303. role: 'assistant',
  304. content: [{ type: 'text', text: 'retry ' }],
  305. source: { kind: 'model', provider: 'p', model: 'm' },
  306. id: 'prior-attempt-message',
  307. },
  308. },
  309. sourceEventSeqs: [0],
  310. surfaceOp: 'append' as const,
  311. },
  312. }
  313. const currentChunk = {
  314. type: 'event' as const,
  315. event: {
  316. type: 'assistant/chunk', seq: 2, time: 20,
  317. data: { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'settled' } },
  318. },
  319. }
  320. const currentMessage = {
  321. type: 'event' as const,
  322. event: {
  323. type: 'assistant/message', seq: 3, time: 21,
  324. data: {
  325. turn: 1,
  326. step: 1,
  327. message: {
  328. role: 'assistant',
  329. content: [{ type: 'text', text: 'settled' }],
  330. source: { kind: 'model', provider: 'p', model: 'm' },
  331. id: 'current-attempt-message',
  332. },
  333. },
  334. sourceEventSeqs: [2],
  335. surfaceOp: 'append' as const,
  336. },
  337. }
  338. b.api.onHistory = () => Promise.resolve(ok({
  339. records: [priorChunk, priorMessage, currentChunk] as never[],
  340. hasMore: false,
  341. }))
  342. b.api.assistantStreamBaseline = {
  343. revision: 2,
  344. attempts: [{
  345. attemptId,
  346. startedTime: 20,
  347. turn: 1,
  348. step: 1,
  349. chunks: [currentChunk.event.data.chunk],
  350. legacyChunkSeqs: [2],
  351. }],
  352. }
  353. await feedList(b, [{ id: 's1' }])
  354. b.svc.open(sid('s1'))
  355. const binding = b.svc.binding(sid('s1'))
  356. if (binding === undefined) throw new Error('expected Session binding')
  357. await vi.waitFor(() => {
  358. expect(binding.session.getSnapshot().openState).toBe('open')
  359. })
  360. expect(binding.eventSource.getSnapshot().entries.map(entry => entry.event.seq)).toEqual([0, 1, 2])
  361. expect(binding.eventSource.getSnapshot().entries.at(1)?.event).toBe(priorMessage.event)
  362. expect(binding.eventSource.getSnapshot().entries.at(-1)?.event).toBe(currentChunk.event)
  363. await b.api.pushFollow(sid('s1'), currentMessage)
  364. await Promise.resolve()
  365. expect(binding.eventSource.getSnapshot().entries.map(entry => entry.event.seq)).toEqual([0, 1, 2])
  366. await b.api.pushFollow(sid('s1'), {
  367. type: 'assistant-stream',
  368. frame: {
  369. type: 'end', attemptId, revision: 3, index: 1,
  370. outcome: 'committed', legacyChunkSeqs: [2],
  371. },
  372. })
  373. await vi.waitFor(() => {
  374. expect(binding.eventSource.getSnapshot().entries.map(entry => entry.event.seq)).toEqual([0, 1, 2, 3])
  375. })
  376. expect(binding.eventSource.getSnapshot().change).toEqual({
  377. kind: 'append', entries: [currentMessage],
  378. })
  379. })
  380. it('replaces an invalid settlement with the authoritative post-end baseline', async () => {
  381. const b = bench()
  382. const attemptId = LlmAttemptId('reconnect-end-index-attempt')
  383. const chunk = {
  384. type: 'event' as const,
  385. event: {
  386. type: 'assistant/chunk', seq: 0, time: 20,
  387. data: { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'settled' } },
  388. },
  389. }
  390. const message = {
  391. type: 'event' as const,
  392. event: {
  393. type: 'assistant/message', seq: 1, time: 21,
  394. data: {
  395. turn: 1,
  396. step: 1,
  397. message: {
  398. role: 'assistant',
  399. content: [{ type: 'text', text: 'settled' }],
  400. source: { kind: 'model', provider: 'p', model: 'm' },
  401. id: 'current-attempt-message',
  402. },
  403. },
  404. sourceEventSeqs: [0],
  405. surfaceOp: 'append' as const,
  406. },
  407. }
  408. let records = [chunk] as never[]
  409. b.api.onHistory = () => Promise.resolve(ok({
  410. records,
  411. hasMore: false,
  412. }))
  413. b.api.assistantStreamBaseline = {
  414. revision: 2,
  415. attempts: [{
  416. attemptId,
  417. startedTime: 20,
  418. turn: 1,
  419. step: 1,
  420. chunks: [chunk.event.data.chunk],
  421. legacyChunkSeqs: [0],
  422. }],
  423. }
  424. await feedList(b, [{ id: 's1' }])
  425. b.svc.open(sid('s1'))
  426. const binding = b.svc.binding(sid('s1'))
  427. if (binding === undefined) throw new Error('expected Session binding')
  428. await vi.waitFor(() => {
  429. expect(binding.eventSource.getSnapshot().entries.map(entry => entry.event.seq)).toEqual([0])
  430. })
  431. await b.api.pushFollow(sid('s1'), message)
  432. await Promise.resolve()
  433. expect(binding.eventSource.getSnapshot().entries.map(entry => entry.event.seq)).toEqual([0])
  434. records = [chunk, message] as never[]
  435. b.api.assistantStreamBaseline = { revision: 3, attempts: [] }
  436. await b.api.pushFollow(sid('s1'), {
  437. type: 'assistant-stream',
  438. frame: {
  439. type: 'end', attemptId, revision: 3, index: 0,
  440. outcome: 'committed', legacyChunkSeqs: [0],
  441. },
  442. })
  443. await vi.waitFor(() => {
  444. expect(b.api.followStarts.filter(id => id === sid('s1'))).toHaveLength(2)
  445. expect(binding.eventSource.getSnapshot().entries.map(entry => entry.event.seq)).toEqual([0, 1])
  446. })
  447. })
  448. it('retains a Host-addressed scope until the first Session baseline owns pruning', async () => {
  449. const b = bench()
  450. const scoped = b.svc.resolveAgentScope(sid('s-early'))
  451. expect(scopeOf(scoped)).toBe('s-early')
  452. b.svc.handleControlFrame({
  453. type: 'baseline',
  454. value: { queues: {}, jobs: {}, projections: {} },
  455. })
  456. await Promise.resolve()
  457. expect(b.svc.resolveAgentScope(sid('s-early'))).toBe(scoped)
  458. await feedList(b, [])
  459. expect(b.svc.scope(sid('s-early'))).toBeUndefined()
  460. })
  461. it('mints lazily on first resolution, tags the ctx, and keeps binding identity stable', async () => {
  462. const b = bench()
  463. await feedList(b, [{ id: 's1' }])
  464. expect(b.svc.scope(sid('unknown'))).toBeUndefined()
  465. const scoped = b.svc.scope(sid('s1'))
  466. expect(scoped).toBeDefined()
  467. expect(scopeOf(scoped as Context)).toBe('s1')
  468. expect(scopeOf(b.ctx)).toBeUndefined()
  469. const binding = b.svc.binding(sid('s1'))
  470. b.svc.open(sid('s1'))
  471. expect(b.svc.sessionOf(scoped as Context)).toBe(binding?.session)
  472. expect(b.svc.binding(sid('s1'))).toBe(binding)
  473. expect(binding?.ctx).toBe(scoped)
  474. })
  475. it('tears down an off-stage removed session but defers the staged one until the stage moves', async () => {
  476. const b = bench()
  477. await feedList(b, [{ id: 's1' }, { id: 's2' }])
  478. const ctx1 = b.svc.scope(sid('s1'))
  479. b.svc.open(sid('s1')) // s1 staged (current)
  480. b.svc.scope(sid('s2')) // s2 scoped but off stage
  481. await feedList(b, [{ id: 's1' }]) // s2 removed, off stage: torn down
  482. expect(b.svc.scope(sid('s2'))).toBeUndefined()
  483. await feedList(b, []) // s1 removed while staged (current masks): deferred, scope survives
  484. expect(b.svc.scope(sid('s1'))).toBe(ctx1)
  485. await feedList(b, [{ id: 's3' }])
  486. b.svc.open(sid('s3')) // stage moves: deferred teardown sweeps s1
  487. expect(b.svc.scope(sid('s1'))).toBeUndefined()
  488. })
  489. it('keeps the scope when the session merely stops running (frozen ≠ removed)', async () => {
  490. const b = bench()
  491. await feedList(b, [{ id: 's1', running: true }])
  492. const scoped = b.svc.scope(sid('s1'))
  493. await feedList(b, [{ id: 's1', running: false }])
  494. expect(b.svc.scope(sid('s1'))).toBe(scoped)
  495. })
  496. it('cancels a deferred teardown when the id reappears in the list', async () => {
  497. const b = bench()
  498. await feedList(b, [{ id: 's1' }])
  499. const scoped = b.svc.scope(sid('s1'))
  500. b.svc.open(sid('s1'))
  501. await feedList(b, []) // removed while staged → deferred
  502. await feedList(b, [{ id: 's1' }, { id: 's2' }]) // reappears (current resurfaces, stage unchanged)
  503. b.svc.open(sid('s2')) // stage moves; sweep must NOT tear down the re-listed s1
  504. expect(b.svc.scope(sid('s1'))).toBe(scoped)
  505. })
  506. it('closes an opened journal when its removed scope drops', async () => {
  507. const b = bench()
  508. await feedList(b, [{ id: 's1' }])
  509. b.svc.open(sid('s1'))
  510. const session = b.svc.binding(sid('s1'))?.session
  511. if (session === undefined) throw new Error('expected the selected Session binding')
  512. await vi.waitFor(() => { expect(b.api.activeFollows(sid('s1'))).toBe(1) })
  513. const notified = vi.fn()
  514. session.subscribe(notified)
  515. await feedList(b, [])
  516. await feedList(b, [{ id: 's2' }])
  517. b.svc.open(sid('s2'))
  518. await vi.waitFor(() => { expect(b.api.activeFollows(sid('s1'))).toBe(0) })
  519. notified.mockClear()
  520. await b.api.pushFollow(sid('s1'), {
  521. type: 'event',
  522. event: { seq: 0, timestamp: 0, type: 'turn/start', data: { turn: 0 } } as never,
  523. })
  524. await Promise.resolve()
  525. expect(b.api.followStarts.filter(id => id === sid('s1'))).toHaveLength(1)
  526. expect(notified).not.toHaveBeenCalled()
  527. })
  528. })
  529. describe('Agent scope disposal lifecycle', () => {
  530. it('root disposal runs Agent scope effects', async () => {
  531. const b = bench()
  532. const readiness = b.ctx.plugin(() => undefined)
  533. await readiness
  534. b.svc.handleSessionAdded({
  535. sessionId: sid('live'), updatedAt: 1, running: false, blank: true,
  536. })
  537. await Promise.resolve()
  538. const scoped = b.svc.scope(sid('live'))
  539. if (scoped === undefined) throw new Error('fixture Agent Context was not minted')
  540. await scoped.fiber.await()
  541. const scopeDisposed = vi.fn()
  542. scoped.effect(() => scopeDisposed, 'fixture Agent scope effect')
  543. await b.ctx.fiber.dispose()
  544. expect(scopeDisposed).toHaveBeenCalledOnce()
  545. expect(b.svc.sessionOf(scoped)).toBeUndefined()
  546. })
  547. it('root disposal waits for an opened Session source to finish closing', async () => {
  548. const closeGate = deferred<undefined>()
  549. const abortObserved = vi.fn()
  550. let followSignal: AbortSignal | undefined
  551. const b = bench(remote => ({
  552. ...remote,
  553. session: {
  554. ...remote.session,
  555. follow: (request, signal) => {
  556. if (signal === undefined) throw new Error('fixture requires a signal')
  557. followSignal = signal
  558. let opened = false
  559. return {
  560. [Symbol.asyncIterator]: () => ({
  561. next: () => {
  562. if (!opened) {
  563. opened = true
  564. return Promise.resolve({
  565. done: false,
  566. value: {
  567. type: 'snapshot',
  568. header: {
  569. version: 1,
  570. id: request.address.kind === 'session'
  571. ? request.address.sessionId
  572. : request.address.childSessionId,
  573. createdAt: 0,
  574. },
  575. cursor: -1,
  576. records: [],
  577. hasMore: false,
  578. projections: { asOfSeq: -1, values: {} },
  579. assistantStream: { revision: 0, attempts: [] },
  580. } as const,
  581. })
  582. }
  583. return new Promise((_resolve, reject) => {
  584. signal.addEventListener('abort', () => {
  585. abortObserved()
  586. void closeGate.promise.then(() => {
  587. reject(signal.reason instanceof Error
  588. ? signal.reason
  589. : new Error(String(signal.reason)))
  590. })
  591. }, { once: true })
  592. })
  593. },
  594. }),
  595. }
  596. },
  597. },
  598. }))
  599. const readiness = b.ctx.plugin(() => undefined)
  600. await readiness
  601. await feedList(b, [{ id: 's1' }])
  602. b.svc.open(sid('s1'))
  603. await vi.waitFor(() => {
  604. expect(b.svc.binding(sid('s1'))?.session.getSnapshot().openState).toBe('open')
  605. })
  606. const disposal = b.ctx.fiber.dispose()
  607. const settled = vi.fn()
  608. const observed = disposal.then(settled)
  609. await vi.waitFor(() => { expect(abortObserved).toHaveBeenCalledOnce() })
  610. expect(followSignal?.aborted).toBe(true)
  611. expect(settled).not.toHaveBeenCalled()
  612. closeGate.resolve(undefined)
  613. await observed
  614. expect(settled).toHaveBeenCalledOnce()
  615. })
  616. it('root disposal joins every Session drop already started by pruning under load', async () => {
  617. const closeGates = new Map<SessionId, ReturnType<typeof deferred<undefined>>>()
  618. const aborted = new Set<SessionId>()
  619. const b = bench(remote => ({
  620. ...remote,
  621. session: {
  622. ...remote.session,
  623. follow: (request, signal) => {
  624. if (signal === undefined) throw new Error('fixture requires a signal')
  625. const sessionId = request.address.kind === 'session'
  626. ? request.address.sessionId
  627. : request.address.childSessionId
  628. const closeGate = deferred<undefined>()
  629. closeGates.set(sessionId, closeGate)
  630. let opened = false
  631. return {
  632. [Symbol.asyncIterator]: () => ({
  633. next: () => {
  634. if (!opened) {
  635. opened = true
  636. return Promise.resolve({
  637. done: false,
  638. value: {
  639. type: 'snapshot',
  640. header: { version: 1, id: sessionId, createdAt: 0 },
  641. cursor: -1,
  642. records: [],
  643. hasMore: false,
  644. projections: { asOfSeq: -1, values: {} },
  645. assistantStream: { revision: 0, attempts: [] },
  646. } as const,
  647. })
  648. }
  649. return new Promise<IteratorResult<SessionFollowFrame>>((_resolve, reject) => {
  650. signal.addEventListener('abort', () => {
  651. aborted.add(sessionId)
  652. void closeGate.promise.then(() => {
  653. reject(signal.reason instanceof Error
  654. ? signal.reason
  655. : new Error(String(signal.reason)))
  656. })
  657. }, { once: true })
  658. })
  659. },
  660. }),
  661. }
  662. },
  663. },
  664. }))
  665. const readiness = b.ctx.plugin(() => undefined)
  666. await readiness
  667. const sessionIds = Array.from({ length: 24 }, (_, index) => sid(`load-${String(index)}`))
  668. const retained = sessionIds.at(-1)
  669. const held = sessionIds[0]
  670. if (retained === undefined || held === undefined) throw new Error('fixture requires sessions')
  671. await feedList(b, sessionIds.map(id => ({ id })))
  672. for (const id of sessionIds) b.svc.open(id)
  673. await vi.waitFor(() => {
  674. for (const id of sessionIds) {
  675. expect(b.svc.binding(id)?.session.getSnapshot().openState).toBe('open')
  676. }
  677. })
  678. const pruned = sessionIds.slice(0, -1)
  679. await feedList(b, [{ id: retained }])
  680. await vi.waitFor(() => { expect(aborted.size).toBe(pruned.length) })
  681. for (const id of pruned) expect(b.svc.scope(id)).toBeUndefined()
  682. const disposal = b.ctx.fiber.dispose()
  683. const settled = vi.fn()
  684. const observed = disposal.then(settled)
  685. await vi.waitFor(() => { expect(aborted.size).toBe(sessionIds.length) })
  686. const otherClosures: Promise<void>[] = []
  687. for (const [id, gate] of closeGates) {
  688. if (id === held) continue
  689. gate.resolve(undefined)
  690. otherClosures.push(gate.promise)
  691. }
  692. await Promise.all(otherClosures)
  693. await new Promise((resolve) => { setTimeout(resolve, 0) })
  694. expect(settled).not.toHaveBeenCalled()
  695. closeGates.get(held)?.resolve(undefined)
  696. await observed
  697. expect(settled).toHaveBeenCalledOnce()
  698. })
  699. })
  700. describe('current selection (migrated from ui-layout, arbitrated into the list snapshot)', () => {
  701. afterEach(() => { vi.unstubAllGlobals() })
  702. it('open() writes list.current; unknown ids fail loud', async () => {
  703. const b = bench()
  704. await feedList(b, [{ id: 's1' }])
  705. expect(b.svc.list.getSnapshot().current).toBeUndefined()
  706. b.svc.open(sid('s1'))
  707. expect(b.svc.list.getSnapshot().current).toBe('s1')
  708. expect(() => { b.svc.open(sid('ghost')) }).toThrow(/unknown session ghost/)
  709. expect(b.svc.list.getSnapshot().current).toBe('s1') // failed open leaves the selection alone
  710. })
  711. it('clear() blanks list.current and the persisted selection', async () => {
  712. const storage = new Map<string, string>()
  713. vi.stubGlobal('localStorage', {
  714. getItem: (k: string) => storage.get(k) ?? null,
  715. setItem: (k: string, v: string) => { storage.set(k, v) },
  716. removeItem: (k: string) => { storage.delete(k) },
  717. clear: () => { storage.clear() },
  718. })
  719. const b = bench()
  720. await feedList(b, [{ id: 's1' }])
  721. b.svc.open(sid('s1'))
  722. expect(storage.get('dsh.sessions.current')).toContain('s1')
  723. b.svc.clear()
  724. expect(b.svc.list.getSnapshot().current).toBeUndefined()
  725. // Persisted wipe: a fresh service with the same storage stays on empty.
  726. const again = bench()
  727. await feedList(again, [{ id: 's1' }])
  728. expect(again.svc.list.getSnapshot().current).toBeUndefined()
  729. })
  730. it('masks (not destroys) the selection while its session is off the list', async () => {
  731. const b = bench()
  732. await feedList(b, [{ id: 's1' }, { id: 's2' }])
  733. b.svc.open(sid('s1'))
  734. await feedList(b, [{ id: 's2' }]) // s1 removed → current falls to the empty state
  735. expect(b.svc.list.getSnapshot().current).toBeUndefined()
  736. await feedList(b, [{ id: 's1' }, { id: 's2' }]) // s1 returns → selection resurfaces
  737. expect(b.svc.list.getSnapshot().current).toBe('s1')
  738. })
  739. it('persists the selection under dsh.sessions.current and rehydrates it into a fresh service', async () => {
  740. const storage = new Map<string, string>()
  741. vi.stubGlobal('localStorage', {
  742. getItem: (k: string) => storage.get(k) ?? null,
  743. setItem: (k: string, v: string) => { storage.set(k, v) },
  744. })
  745. const first = bench()
  746. await feedList(first, [{ id: 's1' }])
  747. first.svc.open(sid('s1'))
  748. expect(storage.get('dsh.sessions.current')).toContain('s1')
  749. // A fresh boot (same storage) recovers the selection once the list holds the session.
  750. const second = bench()
  751. await feedList(second, [{ id: 's1' }])
  752. expect(second.svc.list.getSnapshot().current).toBe('s1')
  753. })
  754. })
  755. describe('binding and stage lifecycle', () => {
  756. it('binding() is pure resolution: no staging, no deferred sweep', async () => {
  757. const b = bench()
  758. await feedList(b, [{ id: 's1' }, { id: 's2' }])
  759. b.svc.open(sid('s1')) // staged
  760. b.svc.binding(sid('s2')) // resolution only — must NOT move the stage
  761. await feedList(b, [{ id: 's2' }]) // s1 removed: still staged → deferred, scope survives
  762. expect(b.svc.scope(sid('s1'))).toBeDefined()
  763. })
  764. it('staging (current write) opens the session event window; resolution and re-staging do not re-pull', async () => {
  765. const b = bench()
  766. await feedList(b, [{ id: 's1' }, { id: 's2' }])
  767. const followStarts = () => b.api.followStarts.map(String)
  768. // Resolution is addressing, not staging: no window pull.
  769. b.svc.scope(sid('s1'))
  770. b.svc.binding(sid('s1'))
  771. expect(followStarts()).toEqual([])
  772. b.svc.open(sid('s1'))
  773. await vi.waitFor(() => {
  774. expect(followStarts()).toEqual(['s1'])
  775. })
  776. // Same current again: no second pull.
  777. b.svc.open(sid('s1'))
  778. expect(followStarts()).toHaveLength(1)
  779. // Stage moves: the new occupant opens.
  780. b.svc.open(sid('s2'))
  781. await vi.waitFor(() => {
  782. expect(followStarts()).toEqual(['s1', 's2'])
  783. })
  784. })
  785. it('startup restore: a persisted selection validated by the first projection opens its window unprompted', async () => {
  786. const storage = new Map<string, string>([
  787. ['dsh.sessions.current', JSON.stringify({ sessionId: 's1' })],
  788. ])
  789. vi.stubGlobal('localStorage', {
  790. getItem: (k: string) => storage.get(k) ?? null,
  791. setItem: (k: string, v: string) => { storage.set(k, v) },
  792. })
  793. try {
  794. const b = bench()
  795. expect(b.api.followStarts).toEqual([])
  796. await feedList(b, [{ id: 's1' }]) // projection validates the persisted id → current lands → stage follows
  797. await vi.waitFor(() => {
  798. expect(b.api.followStarts.map(String)).toEqual(['s1'])
  799. })
  800. } finally {
  801. vi.unstubAllGlobals()
  802. }
  803. })
  804. })
  805. describe('catalog-addressed navigation', () => {
  806. it('uses catalog labels for a listed addressed route', async () => {
  807. const b = bench()
  808. b.api.onSubagentList = (payload) => {
  809. const parentSessionId = payload as SessionId
  810. if (parentSessionId === sid('root')) {
  811. return Promise.resolve(ok({
  812. entries: [{
  813. kind: 'child', id: sid('child'), mode: 'continuable', label: 'Child',
  814. activity: 'inactive', hasChildren: true,
  815. }] as never[],
  816. parentAvailable: true,
  817. }))
  818. }
  819. if (parentSessionId === sid('child')) {
  820. return Promise.resolve(ok({
  821. entries: [{
  822. kind: 'child', id: sid('grandchild'), mode: 'continuable', label: 'Grandchild',
  823. activity: 'inactive', hasChildren: false,
  824. }] as never[],
  825. parentAvailable: false,
  826. }))
  827. }
  828. return Promise.resolve(ok({ entries: [], parentAvailable: false }))
  829. }
  830. await feedList(b, [
  831. { id: 'root' },
  832. { id: 'child', cwd: '/summary-child', parentId: 'root', origin: 'subagent' },
  833. { id: 'grandchild', cwd: '/summary-grandchild', parentId: 'child', origin: 'subagent' },
  834. ])
  835. await b.svc.refreshSubagents(sid('root'))
  836. await b.svc.refreshSubagents(sid('child'))
  837. b.svc.openSubagent({
  838. parentSessionId: sid('child'), childSessionId: sid('grandchild'), mode: 'continuable',
  839. })
  840. expect(b.svc.list.getSnapshot().byId[sid('child')]?.displayTitle).toBe('Child')
  841. expect(b.svc.list.getSnapshot().byId[sid('grandchild')]?.displayTitle).toBe('Grandchild')
  842. })
  843. it('projects a directly opened descendant route without retaining ancestor scopes or addresses', async () => {
  844. const b = bench()
  845. b.api.onSubagentList = (payload) => {
  846. const parentSessionId = payload as SessionId
  847. if (parentSessionId === sid('root')) {
  848. return Promise.resolve(ok({
  849. entries: [{
  850. kind: 'child', id: sid('child'), mode: 'continuable', label: 'Child',
  851. activity: 'inactive', hasChildren: true,
  852. }] as never[],
  853. parentAvailable: true,
  854. }))
  855. }
  856. if (parentSessionId === sid('child')) {
  857. return Promise.resolve(ok({
  858. entries: [{
  859. kind: 'child', id: sid('grandchild'), mode: 'continuable', label: 'Grandchild',
  860. activity: 'inactive', hasChildren: false,
  861. }] as never[],
  862. parentAvailable: false,
  863. }))
  864. }
  865. return Promise.resolve(ok({ entries: [], parentAvailable: false }))
  866. }
  867. await feedList(b, [{ id: 'root' }])
  868. await b.svc.refreshSubagents(sid('root'))
  869. await b.svc.refreshSubagents(sid('child'))
  870. b.svc.openSubagent({
  871. parentSessionId: sid('child'), childSessionId: sid('grandchild'), mode: 'continuable',
  872. })
  873. const list = b.svc.list.getSnapshot()
  874. expect(list.ids).toEqual([sid('root')])
  875. expect(list.byId[sid('child')]).toMatchObject({ parentId: sid('root'), origin: 'subagent' })
  876. expect(list.byId[sid('grandchild')]).toMatchObject({ parentId: sid('child'), origin: 'subagent' })
  877. expect(b.svc.binding(sid('child'))).toBeUndefined()
  878. expect(b.svc.subagentAddress(sid('child'))).toBeUndefined()
  879. b.svc.open(sid('child'))
  880. expect(b.svc.list.getSnapshot().current).toBe(sid('child'))
  881. expect(b.svc.subagentAddress(sid('child'))).toEqual({
  882. parentSessionId: sid('root'), childSessionId: sid('child'), mode: 'continuable',
  883. })
  884. })
  885. })
  886. describe('create', () => {
  887. it('passes a preallocated id and preserves it on ordinary failure', async () => {
  888. const b = bench()
  889. b.api.onCreate = () => Promise.resolve(ok({ sessionId: sid('fresh') }))
  890. await expect(b.svc.create({ cwd: '/w', sessionId: sid('fresh') })).resolves.toBe('fresh')
  891. expect(b.api.callsOf('session.create')).toEqual([{ cwd: '/w', sessionId: 'fresh' }])
  892. b.api.onCreate = () => Promise.resolve(err(new RemoteError('gateway/internal', '爆了', {})))
  893. const failure = await b.svc.create({ sessionId: sid('candidate') }).catch((error: unknown) => error)
  894. expect(failure).toBeInstanceOf(SessionCreateError)
  895. expect(failure).toMatchObject({
  896. requestedSessionId: 'candidate',
  897. rpcError: { code: 'gateway/internal', message: '爆了' },
  898. })
  899. })
  900. it('resolves with the session already listed and binding-resolvable (no flush wait)', async () => {
  901. const b = bench()
  902. b.api.onCreate = () => Promise.resolve(ok({ sessionId: sid('born') }))
  903. const born = await b.svc.create({ workspaceId: 'ws' as never })
  904. // Synchronously after resolution — the draft hand-off contract: the
  905. // create echo IS the entity entering the client's view (blank row +
  906. // resolvable scope/binding), no notifier flush in between.
  907. expect(b.svc.list.getSnapshot().byId[born]).toMatchObject({ id: 'born', blank: true })
  908. expect(b.svc.binding(born)).toBeDefined()
  909. expect(b.svc.scope(born)).toBeDefined()
  910. })
  911. it('lists the published id after Workspace attachment fails (publication precedes attachment)', async () => {
  912. const b = bench()
  913. b.api.onCreate = () => Promise.resolve(err(new RemoteError(
  914. 'session/workspace-attach-failed',
  915. 'ledger unavailable',
  916. { sessionId: sid('published'), workspaceId: 'ws' },
  917. )))
  918. const failure = await b.svc.create({
  919. workspaceId: 'ws' as never,
  920. sessionId: sid('published'),
  921. }).catch((error: unknown) => error)
  922. await Promise.resolve()
  923. expect(failure).toBeInstanceOf(SessionCreateError)
  924. expect(failure).toMatchObject({
  925. requestedSessionId: 'published',
  926. rpcError: { code: 'session/workspace-attach-failed' },
  927. })
  928. expect(b.svc.list.getSnapshot().byId[sid('published')]).toMatchObject({ id: 'published', blank: true })
  929. })
  930. })
  931. describe('fork', () => {
  932. it.each([
  933. ['Roadmap', 'Roadmap (1)'],
  934. ['Roadmap (1)', 'Roadmap (2)'],
  935. ['计划(1)', '计划(2)'],
  936. ['计划 (9)', '计划 (10)'],
  937. ])('increments the durable title %j after the child is published', async (sourceTitle, childTitle) => {
  938. const b = bench()
  939. b.svc.handleControlFrame({
  940. type: 'projection', sessionId: sid('source'), key: 'title', value: sourceTitle, seq: 2,
  941. })
  942. await feedList(b, [{ id: 'source', cwd: '/work' }])
  943. b.api.onFork = () => Promise.resolve(ok({ sessionId: sid('child') }))
  944. b.api.onRename = (payload) => {
  945. const { title } = payload as { title: string }
  946. return Promise.resolve(ok({ title, seq: 3 }))
  947. }
  948. await expect(b.svc.fork({
  949. sessionId: sid('source'), atSeq: 7, increaseTitle: true,
  950. })).resolves.toBe('child')
  951. expect(b.api.callsOf('session.fork')).toEqual([{ sessionId: 'source', atSeq: 7 }])
  952. expect(b.api.callsOf('session.rename')).toEqual([{ sessionId: 'child', title: childTitle }])
  953. await Promise.resolve()
  954. expect(b.svc.list.getSnapshot().byId[sid('child')]).toMatchObject({
  955. title: childTitle,
  956. displayTitle: childTitle,
  957. parentId: 'source',
  958. })
  959. })
  960. it('floors a fractional anchor to the real event seq the wire accepts', async () => {
  961. const b = bench()
  962. await feedList(b, [{ id: 'source', cwd: '/work' }])
  963. b.api.onFork = () => Promise.resolve(ok({ sessionId: sid('child') }))
  964. // The frozen node of an interrupted turn carries turnEnd.seq - 0.9.
  965. await expect(b.svc.fork({ sessionId: sid('source'), atSeq: 41.1 })).resolves.toBe('child')
  966. expect(b.api.callsOf('session.fork')).toEqual([{ sessionId: 'source', atSeq: 41 }])
  967. })
  968. it('does not rename without the title policy or a durable source title', async () => {
  969. const b = bench()
  970. await feedList(b, [{ id: 'source', cwd: '/work' }])
  971. b.api.onFork = () => Promise.resolve(ok({ sessionId: sid('child') }))
  972. await expect(b.svc.fork({ sessionId: sid('source'), increaseTitle: true })).resolves.toBe('child')
  973. expect(b.api.callsOf('session.rename')).toEqual([])
  974. b.api.onFork = () => Promise.resolve(ok({ sessionId: sid('child-2') }))
  975. await expect(b.svc.fork({ sessionId: sid('source') })).resolves.toBe('child-2')
  976. expect(b.api.callsOf('session.rename')).toEqual([])
  977. })
  978. it('rejects when child rename fails while keeping the published child addressable', async () => {
  979. const b = bench()
  980. b.svc.handleControlFrame({
  981. type: 'projection', sessionId: sid('source'), key: 'title', value: 'Roadmap', seq: 2,
  982. })
  983. await feedList(b, [{ id: 'source' }])
  984. b.api.onFork = () => Promise.resolve(ok({ sessionId: sid('child') }))
  985. b.api.onRename = () => Promise.resolve(err(new RemoteError('session/title-invalid', 'rejected', { sessionId: sid('child') })))
  986. await expect(b.svc.fork({ sessionId: sid('source'), increaseTitle: true }))
  987. .rejects.toThrow('fork child rename failed: session/title-invalid: rejected')
  988. expect(b.svc.binding(sid('child'))).toBeDefined()
  989. })
  990. })
  991. describe('scope lifecycle rides the list mirror (entity parity: no client-side pre-birth)', () => {
  992. it('a session-added frame births the row (blank) and makes the scope resolvable; removal prunes it', async () => {
  993. const b = bench()
  994. await feedList(b, [])
  995. expect(b.svc.scope(sid('s-new'))).toBeUndefined() // not in view: no scope, no exceptions
  996. b.svc.handleSessionAdded({
  997. sessionId: sid('s-new'), updatedAt: 2, running: false, blank: true, cwd: '/w/a',
  998. })
  999. await Promise.resolve()
  1000. const scoped = b.svc.scope(sid('s-new'))
  1001. expect(scoped).toBeDefined()
  1002. expect(scopeOf(scoped as Context)).toBe('s-new')
  1003. b.svc.handleSessionRemoved(sid('s-new'))
  1004. await Promise.resolve()
  1005. expect(b.svc.scope(sid('s-new'))).toBeUndefined()
  1006. })
  1007. })
  1008. describe('blank mirror', () => {
  1009. it('flips blank=false from the running:true status frame (cross-client conversion)', async () => {
  1010. const b = bench()
  1011. await feedList(b, [{ id: 's1', blank: true }])
  1012. expect(b.svc.list.getSnapshot().byId[sid('s1')]).toMatchObject({ blank: true })
  1013. b.svc.handleSessionStatus(sid('s1'), true)
  1014. await Promise.resolve()
  1015. expect(b.svc.list.getSnapshot().byId[sid('s1')]).toMatchObject({ blank: false, running: true })
  1016. // The instantiated Session mirrors the same flip.
  1017. expect(b.svc.binding(sid('s1'))?.session.getSnapshot().blank).toBe(false)
  1018. })
  1019. it('flips blank=false on prompt ACCEPTANCE, not on the attempt', async () => {
  1020. const b = bench()
  1021. await feedList(b, [{ id: 's1', blank: true, cwd: '/w/a' }])
  1022. const session = b.svc.binding(sid('s1'))!.session
  1023. expect(session.getSnapshot().blank).toBe(true)
  1024. const gate = deferred<Awaited<ReturnType<FakeApiClient['onPrompt']>>>()
  1025. b.api.onPrompt = () => gate.promise
  1026. const send = session.prompt([{ type: 'text', text: 'hi' }], 'queue')
  1027. // In flight: still blank (the flip point is the success response, which
  1028. // proves the user message reached the host log).
  1029. expect(session.getSnapshot().blank).toBe(true)
  1030. gate.resolve(ok({ accepted: true as const }))
  1031. await send
  1032. expect(session.getSnapshot().blank).toBe(false)
  1033. await Promise.resolve()
  1034. expect(b.svc.list.getSnapshot().byId[sid('s1')]).toMatchObject({ blank: false })
  1035. })
  1036. it('keeps a rejected first prompt blank: hidden and still reusable', async () => {
  1037. const b = bench()
  1038. await feedList(b, [{ id: 's1', blank: true, cwd: '/w/a' }])
  1039. const session = b.svc.binding(sid('s1'))!.session
  1040. b.api.onPrompt = () => Promise.resolve(err(new RemoteError('gateway/internal', 'agent busy', {})))
  1041. const result = await session.prompt([{ type: 'text', text: 'hi' }], 'queue')
  1042. expect(result.ok).toBe(false)
  1043. // No flip on failure: local stays aligned with the host authority
  1044. // (events.length still 0), so the session stays hidden and reusable.
  1045. expect(session.getSnapshot().blank).toBe(true)
  1046. await Promise.resolve()
  1047. expect(b.svc.list.getSnapshot().byId[sid('s1')]).toMatchObject({ blank: true })
  1048. })
  1049. it('takes session-added blank=true as the hidden birth and list blank as reconnect authority', async () => {
  1050. const b = bench()
  1051. await feedList(b, [])
  1052. b.svc.handleSessionAdded({
  1053. sessionId: sid('s-new'), updatedAt: 2, running: false, blank: true, cwd: '/w/a',
  1054. })
  1055. await Promise.resolve()
  1056. expect(b.svc.list.getSnapshot().byId[sid('s-new')]).toMatchObject({ blank: true })
  1057. // Reconnect re-pull: the summary's blank=false wins (authoritative alignment).
  1058. await feedList(b, [{ id: 's-new', blank: false, cwd: '/w/a' }])
  1059. expect(b.svc.list.getSnapshot().byId[sid('s-new')]).toMatchObject({ blank: false })
  1060. })
  1061. it('never re-blanks: a stale blank=true summary cannot hide an engaged session', async () => {
  1062. const b = bench()
  1063. await feedList(b, [{ id: 's1', blank: true }])
  1064. const session = b.svc.binding(sid('s1'))!.session
  1065. await session.prompt([{ type: 'text', text: 'hi' }], 'queue')
  1066. await Promise.resolve()
  1067. expect(b.svc.list.getSnapshot().byId[sid('s1')]).toMatchObject({ blank: false })
  1068. // The next list pull still claims blank (host hasn't logged the message yet).
  1069. await feedList(b, [{ id: 's1', blank: true }])
  1070. expect(b.svc.binding(sid('s1'))?.session.getSnapshot().blank).toBe(false)
  1071. })
  1072. })
  1073. describe('coverage tails (branch duals)', () => {
  1074. it('displayTitleOf falls back to the id for empty and separator-only cwd', async () => {
  1075. const b = bench()
  1076. await feedList(b, [{ id: 'no-base', cwd: '///' }, { id: 'empty-cwd', cwd: '' }])
  1077. const { byId } = b.svc.list.getSnapshot()
  1078. expect(byId[sid('no-base')]?.displayTitle).toBe('no-base')
  1079. expect(byId[sid('empty-cwd')]?.displayTitle).toBe('empty-cwd')
  1080. expect(byId[sid('no-base')]?.title).toBeUndefined()
  1081. })
  1082. it('binding for an unknown session returns undefined and leaves the staged scope intact', async () => {
  1083. const b = bench()
  1084. await feedList(b, [{ id: 's1' }])
  1085. b.svc.open(sid('s1'))
  1086. expect(b.svc.binding(sid('ghost'))).toBeUndefined()
  1087. // Stage unchanged: removing s1 defers (still staged), proving the ghost lookup touched nothing.
  1088. await feedList(b, [])
  1089. expect(b.svc.scope(sid('s1'))).toBeDefined()
  1090. })
  1091. it('a masked current gap holds the stage (no teardown, no re-open) until the stage moves', async () => {
  1092. const b = bench()
  1093. await feedList(b, [{ id: 's1' }])
  1094. b.svc.open(sid('s1'))
  1095. await vi.waitFor(() => { expect(b.api.followStarts).toHaveLength(1) })
  1096. await feedList(b, []) // removed while staged: current masks to undefined, stage holds → deferred
  1097. expect(b.svc.scope(sid('s1'))).toBeDefined()
  1098. // Resurfacing re-projects current = s1: same stage occupant, no second pull.
  1099. await feedList(b, [{ id: 's1' }])
  1100. expect(b.api.followStarts).toHaveLength(1)
  1101. expect(b.svc.list.getSnapshot().current).toBe('s1')
  1102. })
  1103. it('sweep hits both deferral edges: staged-id skip and an already-vacated scope record', async () => {
  1104. const b = bench()
  1105. await feedList(b, [{ id: 'a' }, { id: 'b' }])
  1106. b.svc.scope(sid('a'))
  1107. b.svc.open(sid('b')) // stage: b; both scoped
  1108. await feedList(b, []) // a removed off stage → torn immediately; b removed staged → deferred
  1109. // Move the stage to a THIRD id while b stays deferred: sweep walks a set
  1110. // containing b (torn).
  1111. await feedList(b, [{ id: 'c' }])
  1112. b.svc.open(sid('c'))
  1113. expect(b.svc.scope(sid('b'))).toBeUndefined()
  1114. // Deferral for an id whose record was never minted: force the deferral
  1115. // via removed list state — sweep must tolerate the missing record.
  1116. await feedList(b, []) // c removed while staged → deferred (scope exists)
  1117. await feedList(b, [{ id: 'd' }])
  1118. b.svc.open(sid('d')) // sweep tears c
  1119. expect(b.svc.scope(sid('c'))).toBeUndefined()
  1120. })
  1121. })