fake-api.client.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. // Test-local programmable IApiClient fake (NOT the fixture: fixture is a demo
  2. // data source on a real clock; behavior tests need per-case responses and
  3. // deferred-controlled timing). Session streams are hand pumps: pushFollow/pushControl.
  4. import type {
  5. IApiClient,
  6. RpcError, RpcResponse, SessionId, SessionSearchItem, SkillEntry,
  7. WorkspaceId, WorkspaceView,
  8. } from '@deepseek-ai/dsh-api-remotes/client'
  9. import type {
  10. SessionAddress,
  11. SessionControlBaseline,
  12. SessionControlFrame,
  13. SessionFollowFrame,
  14. SessionFollowRequest,
  15. SessionPage,
  16. SessionPageRequest,
  17. SessionProjectionBaseline,
  18. SessionSelectModelRequest,
  19. SessionSelectModelValue,
  20. } from '@deepseek-ai/dsh-api-session-controller/types'
  21. import type { WorkspaceRemote } from '@deepseek-ai/dsh-api-workspace-controller/client'
  22. import type { WorkspaceFollowFrame } from '@deepseek-ai/dsh-api-workspace-controller/types'
  23. import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
  24. import {
  25. RemoteStream,
  26. RemoteStreamError,
  27. type RemoteStreamOptions,
  28. } from '@deepseek-ai/dsh-api-gateway/client'
  29. import { RpcId } from '@deepseek-ai/dsh-client-connection/client'
  30. import type { SessionRemotes } from '../src/client/sessions/remotes.ts'
  31. import { historyRecordLastSeq } from '../src/client/sessions/history-records.ts'
  32. const AVAILABLE_STREAM_CONNECTION = {
  33. hostDescription: {
  34. getSnapshot: () => ({
  35. version: 'fixture', cwd: '/f', attachedSessions: 0, home: '/h', canOpenPath: true,
  36. }),
  37. subscribe: () => () => {},
  38. },
  39. }
  40. /** Programmable-default workspace row (branded id, ISO-ish times). */
  41. function fakeWorkspace(id: string, over: Partial<WorkspaceView> = {}): WorkspaceView {
  42. return {
  43. workspaceId: id as WorkspaceId,
  44. path: '/f/ws',
  45. title: 'ws',
  46. sessionIds: [],
  47. createdAt: '2026-01-01T00:00:00.000Z',
  48. updatedAt: '2026-01-01T00:00:00.000Z',
  49. ...over,
  50. }
  51. }
  52. function addressSessionId(address: SessionAddress): SessionId {
  53. return address.kind === 'session' ? address.sessionId : address.childSessionId
  54. }
  55. export interface Deferred<T> {
  56. promise: Promise<T>
  57. resolve(value: T): void
  58. reject(error: unknown): void
  59. }
  60. /** Test-held settlement: the case decides when an RPC lands (history-pending injections etc.). */
  61. export function deferred<T>(): Deferred<T> {
  62. let resolve!: (value: T) => void
  63. let reject!: (error: unknown) => void
  64. const promise = new Promise<T>((res, rej) => {
  65. resolve = res
  66. reject = rej
  67. })
  68. return { promise, resolve, reject }
  69. }
  70. let nextRpc = 0
  71. export function ok<T>(value: T): RpcResponse<T> {
  72. return { rpcId: RpcId(`fake-${nextRpc++}`), result: { ok: true, value } }
  73. }
  74. export function err<T>(error: RpcError): RpcResponse<T> {
  75. return { rpcId: RpcId(`fake-${nextRpc++}`), result: { ok: false, error } }
  76. }
  77. /** Successful generated Remote result for programmable domain fakes. */
  78. function remoteOk<T>(value: T): RemoteResult<T> {
  79. return { ok: true, value }
  80. }
  81. type ValueStreamItem<F> =
  82. | { kind: 'frame'; value: F; delivered?: () => void }
  83. | { kind: 'end' }
  84. | { kind: 'fail'; error: unknown }
  85. interface ValueStreamConn<F> {
  86. feed(item: ValueStreamItem<F>): void
  87. }
  88. interface OpenValueStream<F> {
  89. readonly values: AsyncGenerator<F>
  90. dispose(): void
  91. }
  92. /**
  93. * Commands Remote double: the generated face delivers the carrier's outcome, so
  94. * a test that programs nothing sees an empty catalog and an unmatched line.
  95. * @returns the Remote namespaces the session cluster calls.
  96. */
  97. export type RuntimeRemotes = SessionRemotes & { readonly workspace: WorkspaceRemote }
  98. export function fakeRemote(api = new FakeApiClient()): RuntimeRemotes {
  99. return api.sessionRemotes()
  100. }
  101. export class FakeApiClient implements IApiClient {
  102. /** Chronological call record: [method, payload]. */
  103. readonly calls: { method: string; payload: unknown }[] = []
  104. /** Session ids in physical follow-generation opening order. */
  105. readonly followStarts: SessionId[] = []
  106. // Programmable slots (defaults answer OK-empty); reassign per case.
  107. onList: (payload: unknown) => Promise<RpcResponse<{ items: never[] }>> = () => Promise.resolve(ok({ items: [] }))
  108. onSearch: (payload: unknown) => Promise<RpcResponse<{ items: SessionSearchItem[]; hasMore: boolean }>> =
  109. () => Promise.resolve(ok({ items: [], hasMore: false }))
  110. onCreate: (payload: unknown) => Promise<RpcResponse<{ sessionId: SessionId }>> = () => Promise.resolve(ok({ sessionId: 'fk-new' as SessionId }))
  111. onSelectModel: (payload: SessionSelectModelRequest) => Promise<RpcResponse<SessionSelectModelValue>> =
  112. payload => Promise.resolve(ok({
  113. selected: {
  114. provider: payload.provider,
  115. model: payload.model,
  116. ...(payload.reasoningEffort === undefined
  117. ? {}
  118. : { reasoningEffort: payload.reasoningEffort }),
  119. },
  120. }))
  121. onRename: (payload: unknown) => Promise<RpcResponse<{ title: string; seq: number }>> = () => Promise.resolve(ok({ title: 'fk-renamed', seq: 0 }))
  122. onFork: (payload: unknown) => Promise<RpcResponse<{ sessionId: SessionId }>> = () => Promise.resolve(ok({ sessionId: 'fk-fork' as SessionId }))
  123. onHistory: (payload: { sessionId: SessionId; throughSeq?: number; beforeSeq?: number; maxMessages?: number })
  124. => Promise<RpcResponse<SessionPage & { readonly projections?: SessionProjectionBaseline }>> =
  125. () => Promise.resolve(ok({ records: [], hasMore: false }))
  126. onPrompt: (payload: unknown) => Promise<RpcResponse<{ accepted: true }>> = () => Promise.resolve(ok({ accepted: true as const }))
  127. onAttachment: (payload: unknown) => Promise<RpcResponse<{ attachment: { attachmentId: never; mediaType: 'image/png'; bytes: number; width: number; height: number }; data: string }>> =
  128. () => Promise.resolve(ok({ attachment: { attachmentId: 'a' as never, mediaType: 'image/png', bytes: 1, width: 1, height: 1 }, data: 'AA==' }))
  129. onUpdateQueue: (payload: unknown) => Promise<RpcResponse<{ accepted: true }>> = () => Promise.resolve(ok({ accepted: true as const }))
  130. onCancel: (payload: unknown) => Promise<RpcResponse<{ accepted: true }>> = () => Promise.resolve(ok({ accepted: true as const }))
  131. onDescribe: (payload: unknown) => Promise<RpcResponse<{
  132. version: string
  133. cwd: string
  134. attachedSessions: number
  135. home: string
  136. canOpenPath: boolean
  137. }>> =
  138. () => Promise.resolve(ok({
  139. version: '0-fake', cwd: '/f', attachedSessions: 0, home: '/h', canOpenPath: true,
  140. }))
  141. onPickDirectory: (payload: unknown) => Promise<RpcResponse<{ path: string | null }>> =
  142. () => Promise.resolve(ok({ path: null }))
  143. onOpenPath: (payload: unknown) => Promise<RpcResponse<{ opened: true }>> =
  144. () => Promise.resolve(ok({ opened: true as const }))
  145. onListDirectory: (payload: unknown) => Promise<RpcResponse<{
  146. path: string
  147. home: string
  148. crumbs: { name: string; path: string; hidden: boolean }[]
  149. entries: { name: string; path: string; hidden: boolean }[]
  150. truncated: boolean
  151. }>> =
  152. () => Promise.resolve(ok({ path: '/home/fake', home: '/home/fake', crumbs: [{ name: '/', path: '/', hidden: false }], entries: [], truncated: false }))
  153. onCreateDirectory: (payload: unknown) => Promise<RpcResponse<{ path: string }>> =
  154. () => Promise.resolve(ok({ path: '/home/fake/new' }))
  155. private readonly followConns = new Map<SessionId, ValueStreamConn<SessionFollowFrame>[]>()
  156. private readonly controlConns: ValueStreamConn<SessionControlFrame>[] = []
  157. private readonly workspaceConns: ValueStreamConn<WorkspaceFollowFrame>[] = []
  158. /** Optional Host opening cursor override for stale-page and reconnect tests. */
  159. followCursor: number | undefined
  160. controlBaseline: SessionControlBaseline = {
  161. queues: {},
  162. jobs: {},
  163. projections: {},
  164. }
  165. workspaceBaseline: Extract<WorkspaceFollowFrame, { type: 'baseline' }>['value'] = {
  166. items: [],
  167. archivedSessionIds: [],
  168. }
  169. lastSearchSignal: AbortSignal | undefined
  170. onSubagentList: (payload: unknown) => Promise<RpcResponse<{ entries: never[]; parentAvailable: boolean }>>
  171. = () => Promise.resolve(ok({ entries: [], parentAvailable: true }))
  172. onSubagentPrompt: (payload: unknown) => Promise<RpcResponse<{ messageId: never }>>
  173. = () => Promise.resolve(ok({ messageId: 'fake-message' as never }))
  174. onSubagentInterrupt: (payload: unknown) => Promise<RpcResponse<{ accepted: true }>>
  175. = () => Promise.resolve(ok({ accepted: true as const }))
  176. readonly subagents: IApiClient['subagents'] = {
  177. list: (payload: unknown) => this.record('subagent.list', payload, this.onSubagentList(payload)),
  178. prompt: (payload: unknown) => this.record('subagent.prompt', payload, this.onSubagentPrompt(payload)),
  179. interrupt: (payload: unknown) => this.record('subagent.interrupt', payload, this.onSubagentInterrupt(payload)),
  180. }
  181. readonly host: IApiClient['host'] = {
  182. describe: (payload: unknown) => this.record('host.describe', payload, this.onDescribe(payload)),
  183. pickDirectory: (payload: unknown) => this.record('host.pickDirectory', payload, this.onPickDirectory(payload)),
  184. listDirectory: (payload: unknown) => this.record('host.listDirectory', payload, this.onListDirectory(payload)),
  185. createDirectory: (payload: unknown) => this.record('host.createDirectory', payload, this.onCreateDirectory(payload)),
  186. openPath: (payload: unknown) => this.record('host.openPath', payload, this.onOpenPath(payload)),
  187. }
  188. onWorkspaceCreate: (payload: unknown) => Promise<RemoteResult<{ workspace: WorkspaceView; created: boolean }>> =
  189. () => Promise.resolve(remoteOk({ workspace: fakeWorkspace('fk-ws'), created: true }))
  190. onWorkspaceRename: (payload: unknown) => Promise<RemoteResult<{ workspace: WorkspaceView }>> =
  191. () => Promise.resolve(remoteOk({ workspace: fakeWorkspace('fk-ws') }))
  192. onWorkspaceDelete: (payload: unknown) => Promise<RemoteResult<{ deleted: true }>> =
  193. () => Promise.resolve(remoteOk({ deleted: true }))
  194. onWorkspaceInsertBefore: (payload: unknown) => Promise<RemoteResult<{ workspaceIds: WorkspaceId[] }>> =
  195. () => Promise.resolve(remoteOk({ workspaceIds: [] }))
  196. onWorkspaceInsertSessionBefore: (payload: unknown) => Promise<RemoteResult<{ workspace: WorkspaceView }>> =
  197. () => Promise.resolve(remoteOk({ workspace: fakeWorkspace('fk-ws') }))
  198. onWorkspaceArchiveSession: (payload: unknown) => Promise<RemoteResult<{ archivedSessionIds: SessionId[] }>> =
  199. payload => Promise.resolve(remoteOk({ archivedSessionIds: [(payload as { sessionId: SessionId }).sessionId] }))
  200. // Payloads stay `unknown` (lint-lane note above); response rows are the real
  201. // wire shapes so cases can program requires-bearing catalogs and dual-address
  202. // skill lists without casts.
  203. onSkillList: (payload: unknown) => Promise<RpcResponse<{ skills: SkillEntry[] }>>
  204. = () => Promise.resolve(ok({ skills: [] }))
  205. readonly agentPresets: IApiClient['agentPresets'] = {
  206. list: (payload: unknown) => this.record('agentPreset.list', payload, Promise.resolve(ok({ presets: [], authorable: false, hasDocument: false }))),
  207. select: (payload: { agentPreset: string }) =>
  208. this.record('agentPreset.select', payload, Promise.resolve(ok({ agentPreset: payload.agentPreset }))),
  209. read: (payload: { agentPreset: string }) =>
  210. this.record('agentPreset.read', payload, Promise.resolve(ok({
  211. agentPreset: payload.agentPreset, trust: 'user' as const, content: '',
  212. }))),
  213. copy: (payload: { agentPreset: string }) =>
  214. this.record('agentPreset.copy', payload, Promise.resolve(ok({ agentPreset: payload.agentPreset }))),
  215. openDocument: (payload: { agentPreset: string }) =>
  216. this.record('agentPreset.openDocument', payload, Promise.resolve(ok({ opened: true as const }))),
  217. remove: (payload: { agentPreset: string }) =>
  218. this.record('agentPreset.remove', payload, Promise.resolve(ok({}))),
  219. }
  220. readonly skills: IApiClient['skills'] = {
  221. list: (payload: unknown) => this.record('skill.list', payload, this.onSkillList(payload)),
  222. }
  223. readonly settings: IApiClient['settings'] = {
  224. describe: payload => this.record('settings.describe', payload, Promise.resolve(ok({ writable: true, hasDocument: false, namespaces: [] }))),
  225. openDocument: payload => this.record('settings.openDocument', payload, Promise.resolve(ok({ opened: true as const }))),
  226. update: payload => this.record('settings.update', payload, Promise.resolve(ok({ ns: 'fake', schema: {}, value: {}, applies: 'live' as const, secrets: [], revision: 0 }))),
  227. replace: payload => this.record('settings.replace', payload, Promise.resolve(ok({ ns: 'fake', schema: {}, value: {}, applies: 'live' as const, secrets: [], revision: 0 }))),
  228. mutate: payload => this.record('settings.mutate', payload, Promise.resolve(ok({ ns: 'fake', schema: {}, value: {}, applies: 'live' as const, secrets: [], revision: 0 }))),
  229. }
  230. readonly credentials: IApiClient['credentials'] = {
  231. describe: payload => this.record('credentials.describe', payload, Promise.resolve(ok({ credentials: {} }))),
  232. set: payload => this.record('credentials.set', payload, Promise.resolve(ok({}))),
  233. unset: payload => this.record('credentials.unset', payload, Promise.resolve(ok({}))),
  234. }
  235. readonly llm: IApiClient['llm'] = {
  236. providers: payload => this.record('llm.providers', payload, Promise.resolve(ok({ providers: [] }))),
  237. models: payload => this.record('llm.models', payload, Promise.resolve(ok({
  238. default: { provider: 'fixture', model: 'fixture' },
  239. routableProviders: [],
  240. groups: [],
  241. failures: [],
  242. }))),
  243. discoverModels: payload => this.record('llm.discoverModels', payload, Promise.resolve(ok({ models: [] }))),
  244. }
  245. /** Remote namespaces bound to this fake's programmable unary slots and stream pumps. */
  246. sessionRemotes(): RuntimeRemotes {
  247. return {
  248. $stream: <Item>(options: RemoteStreamOptions<Item>) => (
  249. new RemoteStream(AVAILABLE_STREAM_CONNECTION, options)
  250. ),
  251. commands: {
  252. execute: () => Promise.resolve({ ok: true, value: undefined }),
  253. },
  254. session: {
  255. list: payload => this.remoteResult('session.list', payload, this.onList(payload)),
  256. search: (payload, signal) => {
  257. this.lastSearchSignal = signal
  258. return this.remoteResult('session.search', payload, this.onSearch(payload))
  259. },
  260. create: payload => this.remoteResult('session.create', payload, this.onCreate(payload)),
  261. selectModel: payload => this.remoteResult(
  262. 'session.selectModel',
  263. payload,
  264. this.onSelectModel(payload),
  265. ),
  266. rename: payload => this.remoteResult('session.rename', payload, this.onRename(payload)),
  267. fork: payload => this.remoteResult('session.fork', payload, this.onFork(payload)),
  268. prompt: payload => this.remoteResult('session.prompt', payload, this.onPrompt(payload)),
  269. attachment: payload => this.remoteResult('session.attachment', payload, this.onAttachment(payload)),
  270. updateQueue: payload => this.remoteResult('session.updateQueue', payload, this.onUpdateQueue(payload)),
  271. cancel: payload => this.remoteResult('session.cancel', payload, this.onCancel(payload)),
  272. page: request => this.page(request),
  273. follow: (request, signal) => this.openFollow(request, signal),
  274. control: signal => this.openControl(signal),
  275. },
  276. workspace: {
  277. create: payload => this.record('workspace.create', payload, this.onWorkspaceCreate(payload)),
  278. rename: payload => this.record('workspace.rename', payload, this.onWorkspaceRename(payload)),
  279. delete: payload => this.record('workspace.delete', payload, this.onWorkspaceDelete(payload)),
  280. insertBefore: payload => this.record(
  281. 'workspace.insertBefore',
  282. payload,
  283. this.onWorkspaceInsertBefore(payload),
  284. ),
  285. insertSessionBefore: payload => this.record(
  286. 'workspace.insertSessionBefore',
  287. payload,
  288. this.onWorkspaceInsertSessionBefore(payload),
  289. ),
  290. archiveSession: payload => this.record(
  291. 'workspace.archiveSession',
  292. payload,
  293. this.onWorkspaceArchiveSession(payload),
  294. ),
  295. follow: signal => this.openWorkspace(signal),
  296. },
  297. }
  298. }
  299. /** Push one live Session event to every follower of that Session. */
  300. async pushFollow(
  301. sessionId: SessionId,
  302. frame: Extract<SessionFollowFrame, { type: 'event' }>,
  303. ): Promise<void> {
  304. await Promise.all([...(this.followConns.get(sessionId) ?? [])].map(conn => new Promise<void>((resolve) => {
  305. conn.feed({ kind: 'frame', value: frame, delivered: resolve })
  306. })))
  307. }
  308. /** Push one Host-wide control update. */
  309. pushControl(frame: Exclude<SessionControlFrame, { type: 'baseline' }>): void {
  310. for (const conn of [...this.controlConns]) conn.feed({ kind: 'frame', value: frame })
  311. }
  312. /** Push one Workspace projection increment. */
  313. pushWorkspace(frame: Exclude<WorkspaceFollowFrame, { type: 'baseline' }>): void {
  314. for (const conn of [...this.workspaceConns]) conn.feed({ kind: 'frame', value: frame })
  315. }
  316. /** End (clean close) or fail (throw) every open stream — reconnect-path material. */
  317. endStreams(): void {
  318. for (const conns of this.followConns.values()) {
  319. for (const conn of [...conns]) conn.feed({ kind: 'end' })
  320. }
  321. for (const conn of [...this.controlConns]) conn.feed({ kind: 'end' })
  322. for (const conn of [...this.workspaceConns]) conn.feed({ kind: 'end' })
  323. }
  324. failStreams(error: unknown): void {
  325. for (const conns of this.followConns.values()) {
  326. for (const conn of [...conns]) conn.feed({ kind: 'fail', error })
  327. }
  328. for (const conn of [...this.controlConns]) conn.feed({ kind: 'fail', error })
  329. for (const conn of [...this.workspaceConns]) conn.feed({ kind: 'fail', error })
  330. }
  331. callsOf(method: string): unknown[] {
  332. return this.calls.filter(c => c.method === method).map(c => c.payload)
  333. }
  334. /** Number of currently attached journal generations for one Session. */
  335. activeFollows(sessionId: SessionId): number {
  336. return this.followConns.get(sessionId)?.length ?? 0
  337. }
  338. private record<T>(method: string, payload: unknown, response: Promise<T>): Promise<T> {
  339. this.calls.push({ method, payload })
  340. return response
  341. }
  342. private async remoteResult<T>(
  343. method: string,
  344. payload: unknown,
  345. response: Promise<RpcResponse<T>>,
  346. ): Promise<RemoteResult<T>> {
  347. return (await this.record(method, payload, response)).result
  348. }
  349. private page(request: SessionPageRequest): Promise<RemoteResult<SessionPage>> {
  350. return this.fetchPage(request)
  351. }
  352. private async fetchPage(
  353. request: SessionPageRequest,
  354. response?: Promise<RpcResponse<SessionPage>>,
  355. ): Promise<RemoteResult<SessionPage>> {
  356. const sessionId = addressSessionId(request.address)
  357. const payload = request.address.kind === 'session'
  358. ? {
  359. sessionId,
  360. throughSeq: request.throughSeq,
  361. ...request.beforeSeq === undefined ? {} : { beforeSeq: request.beforeSeq },
  362. ...request.maxMessages === undefined ? {} : { maxMessages: request.maxMessages },
  363. }
  364. : {
  365. parentSessionId: request.address.parentSessionId,
  366. childSessionId: request.address.childSessionId,
  367. mode: request.address.mode,
  368. throughSeq: request.throughSeq,
  369. ...request.beforeSeq === undefined ? {} : { beforeSeq: request.beforeSeq },
  370. ...request.maxMessages === undefined ? {} : { maxMessages: request.maxMessages },
  371. }
  372. const method = request.address.kind === 'session' ? 'session.history' : 'subagent.history'
  373. const result = await this.remoteResult(method, payload, response ?? this.onHistory({
  374. sessionId,
  375. throughSeq: request.throughSeq,
  376. ...request.beforeSeq === undefined ? {} : { beforeSeq: request.beforeSeq },
  377. ...request.maxMessages === undefined ? {} : { maxMessages: request.maxMessages },
  378. }))
  379. if (!result.ok) return result
  380. return {
  381. ok: true,
  382. value: {
  383. ...result.value,
  384. records: result.value.records
  385. .filter(record => historyRecordLastSeq(record) <= request.throughSeq),
  386. },
  387. }
  388. }
  389. private async *openFollow(
  390. request: SessionFollowRequest,
  391. signal: AbortSignal = new AbortController().signal,
  392. ): AsyncGenerator<SessionFollowFrame> {
  393. const sessionId = addressSessionId(request.address)
  394. this.followStarts.push(sessionId)
  395. this.calls.push({ method: 'session.follow', payload: request })
  396. const conns = this.followConns.get(sessionId) ?? []
  397. if (!this.followConns.has(sessionId)) this.followConns.set(sessionId, conns)
  398. const stream = this.openValueStream(conns, signal)
  399. try {
  400. const response = await this.onHistory({
  401. sessionId,
  402. maxMessages: request.maxMessages ?? 50,
  403. })
  404. if (!response.result.ok) {
  405. throw new RemoteStreamError(
  406. response.result.error.code,
  407. response.result.error.message,
  408. response.result.error.details,
  409. )
  410. }
  411. const page = response.result.value
  412. const tail = page.records.at(-1)
  413. const cursor = this.followCursor ?? (tail === undefined ? -1 : historyRecordLastSeq(tail))
  414. yield {
  415. type: 'snapshot',
  416. header: {
  417. version: 0,
  418. id: sessionId,
  419. createdAt: 0,
  420. ...(request.address.kind === 'subagent'
  421. ? { origin: 'subagent' as const, parentSession: request.address.parentSessionId }
  422. : {}),
  423. },
  424. cursor,
  425. records: page.records.filter(record => historyRecordLastSeq(record) <= cursor),
  426. hasMore: page.hasMore,
  427. projections: page.projections ?? { asOfSeq: cursor, values: {} },
  428. }
  429. yield* stream.values
  430. } finally {
  431. stream.dispose()
  432. }
  433. }
  434. private async *openControl(
  435. signal: AbortSignal = new AbortController().signal,
  436. ): AsyncGenerator<SessionControlFrame> {
  437. const stream = this.openValueStream(this.controlConns, signal)
  438. try {
  439. yield { type: 'baseline', value: this.controlBaseline }
  440. yield* stream.values
  441. } finally {
  442. stream.dispose()
  443. }
  444. }
  445. private async *openWorkspace(
  446. signal: AbortSignal = new AbortController().signal,
  447. ): AsyncGenerator<WorkspaceFollowFrame> {
  448. const stream = this.openValueStream(this.workspaceConns, signal)
  449. try {
  450. yield { type: 'baseline', value: this.workspaceBaseline }
  451. yield* stream.values
  452. } finally {
  453. stream.dispose()
  454. }
  455. }
  456. private openValueStream<F>(
  457. registry: ValueStreamConn<F>[],
  458. signal: AbortSignal,
  459. ): OpenValueStream<F> {
  460. const inbox: ValueStreamItem<F>[] = []
  461. let wake: (() => void) | null = null
  462. let inFlightDelivered: (() => void) | undefined
  463. let disposed = false
  464. const conn: ValueStreamConn<F> = {
  465. feed: (item) => {
  466. inbox.push(item)
  467. wake?.()
  468. },
  469. }
  470. registry.push(conn)
  471. const dispose = (): void => {
  472. if (disposed) return
  473. disposed = true
  474. inFlightDelivered?.()
  475. for (const item of inbox) {
  476. if (item.kind === 'frame') item.delivered?.()
  477. }
  478. const index = registry.indexOf(conn)
  479. if (index >= 0) registry.splice(index, 1)
  480. wake?.()
  481. }
  482. const values = (async function* (): AsyncGenerator<F> {
  483. try {
  484. while (!signal.aborted && !disposed) {
  485. while (inbox.length > 0) {
  486. const item = inbox.shift() as ValueStreamItem<F>
  487. if (item.kind === 'end') return
  488. if (item.kind === 'fail') throw item.error
  489. inFlightDelivered = item.delivered
  490. yield item.value
  491. inFlightDelivered?.()
  492. inFlightDelivered = undefined
  493. }
  494. await new Promise<void>((resolve) => {
  495. wake = resolve
  496. signal.addEventListener('abort', () => { resolve() }, { once: true })
  497. })
  498. wake = null
  499. }
  500. } finally {
  501. dispose()
  502. }
  503. })()
  504. return { values, dispose }
  505. }
  506. }