fake-api.client.ts 24 KB

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