sessions-service.client.spec.ts 47 KB

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