fake-api.ts 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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). Streams are hand pumps: pushMux/pushHost.
  4. import type {
  5. ClientResponse, HostFrame, IApiClient, MuxFrame, RpcError, RpcReceipt, RpcRequest, RpcResponse, SessionId,
  6. WorkspaceId, WorkspaceView,
  7. } from '@deepseek-ai/dsh-client-connection/client'
  8. import { RpcId } from '@deepseek-ai/dsh-client-connection/client'
  9. /** Programmable-default workspace row (branded id, ISO-ish times). */
  10. function fakeWorkspace(id: string, over: Partial<WorkspaceView> = {}): WorkspaceView {
  11. return {
  12. workspaceId: id as WorkspaceId,
  13. path: '/f/ws',
  14. title: 'ws',
  15. sessionIds: [],
  16. createdAt: '2026-01-01T00:00:00.000Z',
  17. updatedAt: '2026-01-01T00:00:00.000Z',
  18. ...over,
  19. }
  20. }
  21. export interface Deferred<T> {
  22. promise: Promise<T>
  23. resolve(value: T): void
  24. reject(error: unknown): void
  25. }
  26. /** Test-held settlement: the case decides when an RPC lands (history-pending injections etc.). */
  27. export function deferred<T>(): Deferred<T> {
  28. let resolve!: (value: T) => void
  29. let reject!: (error: unknown) => void
  30. const promise = new Promise<T>((res, rej) => {
  31. resolve = res
  32. reject = rej
  33. })
  34. return { promise, resolve, reject }
  35. }
  36. let nextRpc = 0
  37. export function ok<T>(value: T): RpcResponse<T> {
  38. return { rpcId: RpcId(`fake-${nextRpc++}`), result: { ok: true, value } }
  39. }
  40. export function err<T>(error: RpcError): RpcResponse<T> {
  41. return { rpcId: RpcId(`fake-${nextRpc++}`), result: { ok: false, error } }
  42. }
  43. type StreamItem<F> = { kind: 'frame'; envelope: RpcRequest<F> } | { kind: 'end' } | { kind: 'fail'; error: unknown }
  44. interface StreamConn<F> {
  45. feed(item: StreamItem<F>): void
  46. }
  47. export class FakeApiClient implements IApiClient {
  48. /** Chronological call record: [method, payload]. */
  49. readonly calls: { method: string; payload: unknown }[] = []
  50. // Programmable slots (defaults answer OK-empty); reassign per case.
  51. onList: (payload: unknown) => Promise<RpcResponse<{ items: never[] }>> = () => Promise.resolve(ok({ items: [] }))
  52. onCreate: (payload: unknown) => Promise<RpcResponse<{ sessionId: SessionId }>> = () => Promise.resolve(ok({ sessionId: 'fk-new' as SessionId }))
  53. onHistory: (payload: { sessionId: SessionId; beforeSeq?: number; maxMessages?: number })
  54. => Promise<RpcResponse<{ events: never[]; hasMore: boolean }>> =
  55. () => Promise.resolve(ok({ events: [], hasMore: false }))
  56. onPrompt: (payload: unknown) => Promise<RpcResponse<{ accepted: true }>> = () => Promise.resolve(ok({ accepted: true as const }))
  57. onCancel: (payload: unknown) => Promise<RpcResponse<{ accepted: true }>> = () => Promise.resolve(ok({ accepted: true as const }))
  58. onDescribe: (payload: unknown) => Promise<RpcResponse<{ version: string; cwd: string; attachedSessions: number }>> =
  59. () => Promise.resolve(ok({ version: '0-fake', cwd: '/f', attachedSessions: 0 }))
  60. private readonly muxConns: StreamConn<MuxFrame>[] = []
  61. private readonly hostConns: StreamConn<HostFrame>[] = []
  62. // Parameters carry local structural annotations: the CI lint lane runs
  63. // without built lib/, so IApiClient's indexed-access types collapse to any
  64. // and inferred parameters would trip no-unsafe-argument.
  65. readonly sessions: IApiClient['sessions'] = {
  66. list: (payload: unknown) => this.record('session.list', payload, this.onList(payload)),
  67. create: (payload: unknown) => this.record('session.create', payload, this.onCreate(payload)),
  68. history: (payload: { sessionId: SessionId; beforeSeq?: number; maxMessages?: number }) =>
  69. this.record('session.history', payload, this.onHistory(payload)),
  70. prompt: (payload: unknown) => this.record('session.prompt', payload, this.onPrompt(payload)),
  71. cancel: (payload: unknown) => this.record('session.cancel', payload, this.onCancel(payload)),
  72. }
  73. readonly host: IApiClient['host'] = {
  74. describe: (payload: unknown) => this.record('host.describe', payload, this.onDescribe(payload)),
  75. }
  76. onWorkspaceList: (payload: unknown) => Promise<RpcResponse<{ items: never[] }>> = () => Promise.resolve(ok({ items: [] }))
  77. onWorkspaceCreate: (payload: unknown) => Promise<RpcResponse<{ workspace: WorkspaceView; created: boolean }>> =
  78. () => Promise.resolve(ok({ workspace: fakeWorkspace('fk-ws'), created: true }))
  79. onWorkspaceRename: (payload: unknown) => Promise<RpcResponse<{ workspace: WorkspaceView }>> =
  80. () => Promise.resolve(ok({ workspace: fakeWorkspace('fk-ws') }))
  81. onWorkspaceInsertSessionBefore: (payload: unknown) => Promise<RpcResponse<{ workspace: WorkspaceView }>> =
  82. () => Promise.resolve(ok({ workspace: fakeWorkspace('fk-ws') }))
  83. readonly workspace: IApiClient['workspace'] = {
  84. list: (payload: unknown) => this.record('workspace.list', payload, this.onWorkspaceList(payload)),
  85. create: (payload: unknown) => this.record('workspace.create', payload, this.onWorkspaceCreate(payload)),
  86. rename: (payload: unknown) => this.record('workspace.rename', payload, this.onWorkspaceRename(payload)),
  87. insertSessionBefore: (payload: unknown) =>
  88. this.record('workspace.insertSessionBefore', payload, this.onWorkspaceInsertSessionBefore(payload)),
  89. }
  90. /** When true, streams never fire onOpen (misbehaving-carrier material for the handshake timeout guard). */
  91. suppressStreamOpen = false
  92. /** When true, onOpen callbacks are parked instead of fired; releaseStreamOpens() fires them.
  93. * Lets a case hold the readiness handshake open (describe done, streams not yet "established"). */
  94. holdStreamOpen = false
  95. private heldOpens: (() => void)[] = []
  96. releaseStreamOpens(): void {
  97. const held = this.heldOpens
  98. this.heldOpens = []
  99. for (const fire of held) fire()
  100. }
  101. readonly events: IApiClient['events'] = {
  102. mux: (_payload: unknown, signal: AbortSignal, onOpen?: () => void) => this.openStream(this.muxConns, signal, onOpen),
  103. host: (_payload: unknown, signal: AbortSignal, onOpen?: () => void) => this.openStream(this.hostConns, signal, onOpen),
  104. }
  105. onRespond: (message: ClientResponse) => Promise<RpcReceipt> = () => Promise.resolve({ accepted: true })
  106. respond(message: ClientResponse): Promise<RpcReceipt> {
  107. return this.record('respond', message, this.onRespond(message))
  108. }
  109. /** Push one mux frame to every open mux stream (rpcId minted unless pinned by the case). */
  110. pushMux(frame: MuxFrame, rpcId?: string): void {
  111. for (const conn of [...this.muxConns]) conn.feed({ kind: 'frame', envelope: { rpcId: RpcId(rpcId ?? `push-${nextRpc++}`), payload: frame } })
  112. }
  113. pushHost(frame: HostFrame, rpcId?: string): void {
  114. for (const conn of [...this.hostConns]) conn.feed({ kind: 'frame', envelope: { rpcId: RpcId(rpcId ?? `push-${nextRpc++}`), payload: frame } })
  115. }
  116. /** End (clean close) or fail (throw) every open stream — reconnect-path material. */
  117. endStreams(): void {
  118. for (const conn of [...this.muxConns, ...this.hostConns]) conn.feed({ kind: 'end' })
  119. }
  120. failStreams(error: unknown): void {
  121. for (const conn of [...this.muxConns, ...this.hostConns]) conn.feed({ kind: 'fail', error })
  122. }
  123. get openMuxCount(): number {
  124. return this.muxConns.length
  125. }
  126. callsOf(method: string): unknown[] {
  127. return this.calls.filter(c => c.method === method).map(c => c.payload)
  128. }
  129. private record<T>(method: string, payload: unknown, response: Promise<T>): Promise<T> {
  130. this.calls.push({ method, payload })
  131. return response
  132. }
  133. private async *openStream<F>(registry: StreamConn<F>[], signal: AbortSignal, onOpen?: () => void): AsyncGenerator<RpcRequest<F>> {
  134. const inbox: StreamItem<F>[] = []
  135. let wake: (() => void) | null = null
  136. const conn: StreamConn<F> = {
  137. feed: (item) => {
  138. inbox.push(item)
  139. wake?.()
  140. },
  141. }
  142. registry.push(conn)
  143. if (this.holdStreamOpen && onOpen !== undefined) this.heldOpens.push(onOpen)
  144. else if (!this.suppressStreamOpen) onOpen?.()
  145. try {
  146. while (!signal.aborted) {
  147. while (inbox.length > 0) {
  148. const item = inbox.shift() as StreamItem<F>
  149. if (item.kind === 'end') return
  150. if (item.kind === 'fail') throw item.error
  151. yield item.envelope
  152. }
  153. await new Promise<void>((resolve) => {
  154. wake = resolve
  155. signal.addEventListener('abort', () => { resolve() }, { once: true })
  156. })
  157. wake = null
  158. }
  159. } finally {
  160. registry.splice(registry.indexOf(conn), 1)
  161. }
  162. }
  163. }