fake-api.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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 { CommandId } from '@deepseek-ai/dsh-commands/brand'
  5. import type {
  6. ClientResponse, CommandDescriptor, HostFrame, IApiClient, ModelTarget, MuxFrame,
  7. RpcError, RpcReceipt, RpcRequest, RpcResponse, SessionId, SessionModels, SessionSearchItem, SkillEntry,
  8. WorkspaceId, WorkspaceView,
  9. } from '@deepseek-ai/dsh-client-connection/client'
  10. import { RpcId } from '@deepseek-ai/dsh-client-connection/client'
  11. /** Programmable-default workspace row (branded id, ISO-ish times). */
  12. function fakeWorkspace(id: string, over: Partial<WorkspaceView> = {}): WorkspaceView {
  13. return {
  14. workspaceId: id as WorkspaceId,
  15. path: '/f/ws',
  16. title: 'ws',
  17. sessionIds: [],
  18. createdAt: '2026-01-01T00:00:00.000Z',
  19. updatedAt: '2026-01-01T00:00:00.000Z',
  20. ...over,
  21. }
  22. }
  23. export interface Deferred<T> {
  24. promise: Promise<T>
  25. resolve(value: T): void
  26. reject(error: unknown): void
  27. }
  28. /** Test-held settlement: the case decides when an RPC lands (history-pending injections etc.). */
  29. export function deferred<T>(): Deferred<T> {
  30. let resolve!: (value: T) => void
  31. let reject!: (error: unknown) => void
  32. const promise = new Promise<T>((res, rej) => {
  33. resolve = res
  34. reject = rej
  35. })
  36. return { promise, resolve, reject }
  37. }
  38. let nextRpc = 0
  39. export function ok<T>(value: T): RpcResponse<T> {
  40. return { rpcId: RpcId(`fake-${nextRpc++}`), result: { ok: true, value } }
  41. }
  42. export function err<T>(error: RpcError): RpcResponse<T> {
  43. return { rpcId: RpcId(`fake-${nextRpc++}`), result: { ok: false, error } }
  44. }
  45. type StreamItem<F> = { kind: 'frame'; envelope: RpcRequest<F> } | { kind: 'end' } | { kind: 'fail'; error: unknown }
  46. interface StreamConn<F> {
  47. feed(item: StreamItem<F>): void
  48. }
  49. export class FakeApiClient implements IApiClient {
  50. /** Chronological call record: [method, payload]. */
  51. readonly calls: { method: string; payload: unknown }[] = []
  52. // Programmable slots (defaults answer OK-empty); reassign per case.
  53. onList: (payload: unknown) => Promise<RpcResponse<{ items: never[] }>> = () => Promise.resolve(ok({ items: [] }))
  54. onSearch: (payload: unknown) => Promise<RpcResponse<{ items: SessionSearchItem[]; hasMore: boolean }>> =
  55. () => Promise.resolve(ok({ items: [], hasMore: false }))
  56. onCreate: (payload: unknown) => Promise<RpcResponse<{ sessionId: SessionId }>> = () => Promise.resolve(ok({ sessionId: 'fk-new' as SessionId }))
  57. readonly defaultModel: ModelTarget = { provider: 'deepseek-official', model: 'deepseek-v4-flash' }
  58. onRename: (payload: unknown) => Promise<RpcResponse<{ title: string; seq: number }>> = () => Promise.resolve(ok({ title: 'fk-renamed', seq: 0 }))
  59. onFork: (payload: unknown) => Promise<RpcResponse<{ sessionId: SessionId }>> = () => Promise.resolve(ok({ sessionId: 'fk-fork' as SessionId }))
  60. onHistory: (payload: { sessionId: SessionId; beforeSeq?: number; maxMessages?: number })
  61. => Promise<RpcResponse<{ events: never[]; hasMore: boolean }>> =
  62. () => Promise.resolve(ok({ events: [], hasMore: false }))
  63. onModels: (payload: unknown) => Promise<RpcResponse<SessionModels>> = () => Promise.resolve(ok({
  64. current: this.defaultModel,
  65. groups: [{
  66. id: 'deepseek-official',
  67. name: 'DeepSeek',
  68. models: [{ id: 'deepseek-v4-flash', name: 'DeepSeek V4 Flash' }],
  69. }],
  70. failures: [],
  71. }))
  72. onSelectModel: (payload: { provider: string; model: string }) =>
  73. Promise<RpcResponse<{ selected: ModelTarget }>> =
  74. payload => Promise.resolve(ok({ selected: { provider: payload.provider, model: payload.model } }))
  75. onPrompt: (payload: unknown) => Promise<RpcResponse<{ accepted: true }>> = () => Promise.resolve(ok({ accepted: true as const }))
  76. onUpdateQueue: (payload: unknown) => Promise<RpcResponse<{ accepted: true }>> = () => Promise.resolve(ok({ accepted: true as const }))
  77. onCancel: (payload: unknown) => Promise<RpcResponse<{ accepted: true }>> = () => Promise.resolve(ok({ accepted: true as const }))
  78. onDescribe: (payload: unknown) => Promise<RpcResponse<{ version: string; cwd: string; attachedSessions: number }>> =
  79. () => Promise.resolve(ok({ version: '0-fake', cwd: '/f', attachedSessions: 0 }))
  80. onPickDirectory: (payload: unknown) => Promise<RpcResponse<{ path: string | null }>> =
  81. () => Promise.resolve(ok({ path: null }))
  82. onOpenPath: (payload: unknown) => Promise<RpcResponse<{ opened: true }>> =
  83. () => Promise.resolve(ok({ opened: true as const }))
  84. onListDirectory: (payload: unknown) => Promise<RpcResponse<{
  85. path: string
  86. home: string
  87. crumbs: { name: string; path: string; hidden: boolean }[]
  88. entries: { name: string; path: string; hidden: boolean }[]
  89. truncated: boolean
  90. }>> =
  91. () => Promise.resolve(ok({ path: '/home/fake', home: '/home/fake', crumbs: [{ name: '/', path: '/', hidden: false }], entries: [], truncated: false }))
  92. onCreateDirectory: (payload: unknown) => Promise<RpcResponse<{ path: string }>> =
  93. () => Promise.resolve(ok({ path: '/home/fake/new' }))
  94. private readonly muxConns: StreamConn<MuxFrame>[] = []
  95. private readonly hostConns: StreamConn<HostFrame>[] = []
  96. lastSearchSignal: AbortSignal | undefined
  97. // Parameters carry local structural annotations: the CI lint lane runs
  98. // without built lib/, so IApiClient's indexed-access types collapse to any
  99. // and inferred parameters would trip no-unsafe-argument.
  100. readonly sessions: IApiClient['sessions'] = {
  101. list: (payload: unknown) => this.record('session.list', payload, this.onList(payload)),
  102. search: (payload: unknown, signal?: AbortSignal) => {
  103. this.lastSearchSignal = signal
  104. return this.record('session.search', payload, this.onSearch(payload))
  105. },
  106. create: (payload: unknown) => this.record('session.create', payload, this.onCreate(payload)),
  107. history: (payload: { sessionId: SessionId; beforeSeq?: number; maxMessages?: number }) =>
  108. this.record('session.history', payload, this.onHistory(payload)),
  109. models: (payload: unknown) => this.record('session.models', payload, this.onModels(payload)),
  110. selectModel: (payload: { provider: string; model: string }) =>
  111. this.record('session.selectModel', payload, this.onSelectModel(payload)),
  112. rename: (payload: unknown) => this.record('session.rename', payload, this.onRename(payload)),
  113. fork: (payload: unknown) => this.record('session.fork', payload, this.onFork(payload)),
  114. prompt: (payload: unknown) => this.record('session.prompt', payload, this.onPrompt(payload)),
  115. updateQueue: (payload: unknown) => this.record('session.updateQueue', payload, this.onUpdateQueue(payload)),
  116. cancel: (payload: unknown) => this.record('session.cancel', payload, this.onCancel(payload)),
  117. }
  118. readonly host: IApiClient['host'] = {
  119. describe: (payload: unknown) => this.record('host.describe', payload, this.onDescribe(payload)),
  120. pickDirectory: (payload: unknown) => this.record('host.pickDirectory', payload, this.onPickDirectory(payload)),
  121. listDirectory: (payload: unknown) => this.record('host.listDirectory', payload, this.onListDirectory(payload)),
  122. createDirectory: (payload: unknown) => this.record('host.createDirectory', payload, this.onCreateDirectory(payload)),
  123. openPath: (payload: unknown) => this.record('host.openPath', payload, this.onOpenPath(payload)),
  124. }
  125. // The archive-set field defaults at the binding below so list stubs keep
  126. // the pre-archive `{ items }` shape; a stub carrying the field wins.
  127. onWorkspaceList: (payload: unknown) => Promise<RpcResponse<{ items: never[]; archivedSessionIds?: never[] }>> =
  128. () => Promise.resolve(ok({ items: [] }))
  129. onWorkspaceCreate: (payload: unknown) => Promise<RpcResponse<{ workspace: WorkspaceView; created: boolean }>> =
  130. () => Promise.resolve(ok({ workspace: fakeWorkspace('fk-ws'), created: true }))
  131. onWorkspaceRename: (payload: unknown) => Promise<RpcResponse<{ workspace: WorkspaceView }>> =
  132. () => Promise.resolve(ok({ workspace: fakeWorkspace('fk-ws') }))
  133. onWorkspaceDelete: (payload: unknown) => Promise<RpcResponse<{ deleted: true }>> =
  134. () => Promise.resolve(ok({ deleted: true }))
  135. onWorkspaceInsertSessionBefore: (payload: unknown) => Promise<RpcResponse<{ workspace: WorkspaceView }>> =
  136. () => Promise.resolve(ok({ workspace: fakeWorkspace('fk-ws') }))
  137. onWorkspaceArchiveSession: (payload: unknown) => Promise<RpcResponse<{ archivedSessionIds: SessionId[] }>> =
  138. payload => Promise.resolve(ok({ archivedSessionIds: [(payload as { sessionId: SessionId }).sessionId] }))
  139. readonly workspace: IApiClient['workspace'] = {
  140. list: (payload: unknown) => this.record('workspace.list', payload, this.onWorkspaceList(payload).then(response => (
  141. response.result.ok
  142. ? { ...response, result: { ok: true as const, value: { archivedSessionIds: [] as never[], ...response.result.value } } }
  143. : response
  144. )) as ReturnType<IApiClient['workspace']['list']>),
  145. create: (payload: unknown) => this.record('workspace.create', payload, this.onWorkspaceCreate(payload)),
  146. rename: (payload: unknown) => this.record('workspace.rename', payload, this.onWorkspaceRename(payload)),
  147. delete: (payload: unknown) => this.record('workspace.delete', payload, this.onWorkspaceDelete(payload)),
  148. insertSessionBefore: (payload: unknown) =>
  149. this.record('workspace.insertSessionBefore', payload, this.onWorkspaceInsertSessionBefore(payload)),
  150. archiveSession: (payload: unknown) =>
  151. this.record('workspace.archiveSession', payload, this.onWorkspaceArchiveSession(payload)),
  152. }
  153. // Payloads stay `unknown` (lint-lane note above); response rows are the real
  154. // wire shapes so cases can program requires-bearing catalogs and dual-address
  155. // skill lists without casts.
  156. onCommandList: (payload: unknown) => Promise<RpcResponse<{ commands: CommandDescriptor[] }>>
  157. = () => Promise.resolve(ok({ commands: [] }))
  158. onCommandExecute: (payload: unknown) => Promise<RpcResponse<{ matched: boolean; commandId?: CommandId }>>
  159. = () => Promise.resolve(ok({ matched: false }))
  160. onSkillList: (payload: unknown) => Promise<RpcResponse<{ skills: SkillEntry[] }>>
  161. = () => Promise.resolve(ok({ skills: [] }))
  162. readonly commands: IApiClient['commands'] = {
  163. list: (payload: unknown) => this.record('command.list', payload, this.onCommandList(payload)),
  164. execute: (payload: unknown) => this.record('command.execute', payload, this.onCommandExecute(payload)),
  165. }
  166. readonly skills: IApiClient['skills'] = {
  167. list: (payload: unknown) => this.record('skill.list', payload, this.onSkillList(payload)),
  168. }
  169. readonly goals: IApiClient['goals'] = {
  170. create: payload => this.record('goal.create', payload, Promise.resolve(ok({ ref: { id: 'fake-goal' as never, revision: 1 } }))),
  171. edit: payload => this.record('goal.edit', payload, Promise.resolve(ok({ ref: { id: 'fake-goal' as never, revision: 1 } }))),
  172. pause: payload => this.record('goal.pause', payload, Promise.resolve(ok({ ref: { id: 'fake-goal' as never, revision: 1 } }))),
  173. resume: payload => this.record('goal.resume', payload, Promise.resolve(ok({ ref: { id: 'fake-goal' as never, revision: 1 } }))),
  174. complete: payload => this.record('goal.complete', payload, Promise.resolve(ok({ ref: { id: 'fake-goal' as never, revision: 1 } }))),
  175. clear: payload => this.record('goal.clear', payload, Promise.resolve(ok({ cleared: true as const }))),
  176. }
  177. readonly settings: IApiClient['settings'] = {
  178. describe: payload => this.record('settings.describe', payload, Promise.resolve(ok({ writable: true, namespaces: [] }))),
  179. update: payload => this.record('settings.update', payload, Promise.resolve(ok({ ns: 'fake', schema: {}, value: {}, applies: 'live' as const, secrets: [], revision: 0 }))),
  180. replace: payload => this.record('settings.replace', payload, Promise.resolve(ok({ ns: 'fake', schema: {}, value: {}, applies: 'live' as const, secrets: [], revision: 0 }))),
  181. mutate: payload => this.record('settings.mutate', payload, Promise.resolve(ok({ ns: 'fake', schema: {}, value: {}, applies: 'live' as const, secrets: [], revision: 0 }))),
  182. }
  183. readonly credentials: IApiClient['credentials'] = {
  184. describe: payload => this.record('credentials.describe', payload, Promise.resolve(ok({ credentials: {} }))),
  185. set: payload => this.record('credentials.set', payload, Promise.resolve(ok({}))),
  186. unset: payload => this.record('credentials.unset', payload, Promise.resolve(ok({}))),
  187. }
  188. readonly llm: IApiClient['llm'] = {
  189. providers: payload => this.record('llm.providers', payload, Promise.resolve(ok({ providers: [] }))),
  190. models: payload => this.record('llm.models', payload, Promise.resolve(ok({ groups: [], failures: [] }))),
  191. }
  192. /** When true, streams never fire onOpen (misbehaving-carrier material for the handshake timeout guard). */
  193. suppressStreamOpen = false
  194. /** When true, onOpen callbacks are parked instead of fired; releaseStreamOpens() fires them.
  195. * Lets a case hold the readiness handshake open (describe done, streams not yet "established"). */
  196. holdStreamOpen = false
  197. private heldOpens: (() => void)[] = []
  198. releaseStreamOpens(): void {
  199. const held = this.heldOpens
  200. this.heldOpens = []
  201. for (const fire of held) fire()
  202. }
  203. readonly events: IApiClient['events'] = {
  204. mux: (_payload: unknown, signal: AbortSignal, onOpen?: () => void) => this.openStream(this.muxConns, signal, onOpen),
  205. host: (_payload: unknown, signal: AbortSignal, onOpen?: () => void) => this.openStream(this.hostConns, signal, onOpen),
  206. }
  207. onRespond: (message: ClientResponse) => Promise<RpcReceipt> = () => Promise.resolve({ accepted: true })
  208. respond(message: ClientResponse): Promise<RpcReceipt> {
  209. return this.record('respond', message, this.onRespond(message))
  210. }
  211. /** Push one mux frame to every open mux stream (rpcId minted unless pinned by the case). */
  212. pushMux(frame: MuxFrame, rpcId?: string): void {
  213. for (const conn of [...this.muxConns]) conn.feed({ kind: 'frame', envelope: { rpcId: RpcId(rpcId ?? `push-${nextRpc++}`), payload: frame } })
  214. }
  215. pushHost(frame: HostFrame, rpcId?: string): void {
  216. for (const conn of [...this.hostConns]) conn.feed({ kind: 'frame', envelope: { rpcId: RpcId(rpcId ?? `push-${nextRpc++}`), payload: frame } })
  217. }
  218. /** End (clean close) or fail (throw) every open stream — reconnect-path material. */
  219. endStreams(): void {
  220. for (const conn of [...this.muxConns, ...this.hostConns]) conn.feed({ kind: 'end' })
  221. }
  222. failStreams(error: unknown): void {
  223. for (const conn of [...this.muxConns, ...this.hostConns]) conn.feed({ kind: 'fail', error })
  224. }
  225. get openMuxCount(): number {
  226. return this.muxConns.length
  227. }
  228. callsOf(method: string): unknown[] {
  229. return this.calls.filter(c => c.method === method).map(c => c.payload)
  230. }
  231. private record<T>(method: string, payload: unknown, response: Promise<T>): Promise<T> {
  232. this.calls.push({ method, payload })
  233. return response
  234. }
  235. private async *openStream<F>(registry: StreamConn<F>[], signal: AbortSignal, onOpen?: () => void): AsyncGenerator<RpcRequest<F>> {
  236. const inbox: StreamItem<F>[] = []
  237. let wake: (() => void) | null = null
  238. const conn: StreamConn<F> = {
  239. feed: (item) => {
  240. inbox.push(item)
  241. wake?.()
  242. },
  243. }
  244. registry.push(conn)
  245. if (this.holdStreamOpen && onOpen !== undefined) this.heldOpens.push(onOpen)
  246. else if (!this.suppressStreamOpen) onOpen?.()
  247. try {
  248. while (!signal.aborted) {
  249. while (inbox.length > 0) {
  250. const item = inbox.shift() as StreamItem<F>
  251. if (item.kind === 'end') return
  252. if (item.kind === 'fail') throw item.error
  253. yield item.envelope
  254. }
  255. await new Promise<void>((resolve) => {
  256. wake = resolve
  257. signal.addEventListener('abort', () => { resolve() }, { once: true })
  258. })
  259. wake = null
  260. }
  261. } finally {
  262. registry.splice(registry.indexOf(conn), 1)
  263. }
  264. }
  265. }