test-remote.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. /** Test-only direct Remote face over the Session Controller's internal controllers. */
  2. import { SessionLogOffset } from '@deepseek-ai/dsh-session'
  3. import type { Context } from '@deepseek-ai/cordis'
  4. import type { ModelSelection as AgentModelSelection } from '@deepseek-ai/dsh-agent'
  5. import type {
  6. AdmittedPromptContentPart,
  7. AttachmentAdmissionPart,
  8. ImageAttachmentLimits,
  9. } from '@deepseek-ai/dsh-attachment'
  10. import type { SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session'
  11. import {
  12. SessionPersistenceNotFoundError,
  13. SessionPersistenceRevision,
  14. SessionReadOnlyError,
  15. type SessionAccess,
  16. type SessionHandle,
  17. type SessionHandleReadOptions,
  18. type SessionPersistenceListOptions,
  19. type SessionPersistenceOpenOptions,
  20. type SessionPersistenceSnapshot,
  21. type SessionPersistenceStatOptions,
  22. } from '@deepseek-ai/dsh-session-persistence'
  23. import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
  24. import SessionQueryEngine from '@deepseek-ai/dsh-session-query'
  25. import { vi } from 'vitest'
  26. import {
  27. RemoteError,
  28. remoteErrorOf,
  29. type RemoteResult,
  30. } from '@deepseek-ai/dsh-typert-protocol'
  31. import SessionController from '../src/index.ts'
  32. import type {
  33. ModelCatalog,
  34. SessionAttachmentRequest,
  35. SessionAttachmentValue,
  36. SessionCancelRequest,
  37. SessionCancelValue,
  38. SessionControlFrame,
  39. SessionCreateRequest,
  40. SessionCreateValue,
  41. SessionForkRequest,
  42. SessionForkValue,
  43. SessionFollowFrame,
  44. SessionFollowRequest,
  45. SessionListRequest,
  46. SessionListValue,
  47. SessionOpenWorkspacePathRequest,
  48. SessionOpenWorkspacePathValue,
  49. SessionPage,
  50. SessionPageRequest,
  51. SessionPromptRequest,
  52. SessionPromptValue,
  53. SessionRenameRequest,
  54. SessionRenameValue,
  55. SessionSearchRequest,
  56. SessionSearchValue,
  57. SessionSelectModelRequest,
  58. SessionSelectModelValue,
  59. SessionUpdateQueueRequest,
  60. SessionUpdateQueueValue,
  61. } from '../src/types.ts'
  62. /** Direct test face matching the generated `ctx.remote.session` unary methods. */
  63. export interface TestSessionRemote {
  64. canOpenWorkspacePath(): Promise<RemoteResult<boolean>>
  65. list(request: SessionListRequest, signal?: AbortSignal): Promise<RemoteResult<SessionListValue>>
  66. search(request: SessionSearchRequest, signal?: AbortSignal): Promise<RemoteResult<SessionSearchValue>>
  67. create(request: SessionCreateRequest): Promise<RemoteResult<SessionCreateValue>>
  68. selectModel(request: SessionSelectModelRequest): Promise<RemoteResult<SessionSelectModelValue>>
  69. modelCatalog(): Promise<RemoteResult<ModelCatalog>>
  70. rename(request: SessionRenameRequest): Promise<RemoteResult<SessionRenameValue>>
  71. fork(request: SessionForkRequest): Promise<RemoteResult<SessionForkValue>>
  72. prompt(request: SessionPromptRequest, signal?: AbortSignal): Promise<RemoteResult<SessionPromptValue>>
  73. attachment(request: SessionAttachmentRequest): Promise<RemoteResult<SessionAttachmentValue>>
  74. updateQueue(request: SessionUpdateQueueRequest): Promise<RemoteResult<SessionUpdateQueueValue>>
  75. cancel(request: SessionCancelRequest): Promise<RemoteResult<SessionCancelValue>>
  76. openWorkspacePath(
  77. request: SessionOpenWorkspacePathRequest,
  78. signal?: AbortSignal,
  79. ): Promise<RemoteResult<SessionOpenWorkspacePathValue>>
  80. page(request: SessionPageRequest, signal?: AbortSignal): Promise<RemoteResult<SessionPage>>
  81. follow(request: SessionFollowRequest, signal?: AbortSignal): AsyncIterable<SessionFollowFrame>
  82. control(signal?: AbortSignal): AsyncIterable<SessionControlFrame>
  83. }
  84. /** Dependencies and policy supplied by a Session Controller unit harness. */
  85. export interface TestSessionRemoteDefaults {
  86. readonly defaultModelSelection: () => AgentModelSelection
  87. readonly cwd: string
  88. readonly nativeOpen?: boolean
  89. readonly saveDefaultModelSelection?: (selection: AgentModelSelection) => void | Promise<void>
  90. readonly openPath?: (path: string, signal: AbortSignal) => Promise<void>
  91. readonly canOpenPath?: () => boolean
  92. }
  93. const installed = new WeakMap<Context, SessionController>()
  94. const TEST_IMAGE_LIMITS: ImageAttachmentLimits = Object.freeze({
  95. maxImageBytes: 5 * 1024 * 1024,
  96. maxImagesPerMessage: 20,
  97. maxMessageImageBytes: 100 * 1024 * 1024,
  98. maxImagePixels: 40_000_000,
  99. maxImageDimension: 2000,
  100. mediaTypes: Object.freeze(['image/png'] as const),
  101. })
  102. /** Compact header-and-events point read a persistence double declares per session. */
  103. interface TestSessionInspection {
  104. readonly meta: SessionHeader
  105. readonly events: readonly SessionEvent[]
  106. }
  107. type LegacyTestPersistence = Record<string, unknown> & {
  108. readonly list?: (signal?: AbortSignal) => Promise<readonly SessionHeader[]>
  109. readonly inspect?: (
  110. sessionId: SessionId,
  111. signal?: AbortSignal,
  112. ) => Promise<TestSessionInspection | undefined>
  113. readonly stat?: (
  114. sessionId: SessionId,
  115. options?: SessionPersistenceStatOptions,
  116. ) => Promise<SessionPersistenceSnapshot | undefined>
  117. readonly open?: (
  118. sessionId: SessionId,
  119. access: SessionAccess,
  120. options?: SessionPersistenceOpenOptions,
  121. ) => Promise<SessionHandle>
  122. }
  123. /** One immutable read handle over a double's inspected header and events. */
  124. function testReadHandle(
  125. sessionId: SessionId,
  126. inspection: TestSessionInspection,
  127. ): SessionHandle {
  128. const events = Object.freeze([...inspection.events])
  129. return {
  130. id: sessionId,
  131. header: inspection.meta,
  132. inheritedEventCount: SessionLogOffset(0),
  133. access: 'read',
  134. read: (offset = 0, length?: number, options?: SessionHandleReadOptions) => {
  135. options?.signal?.throwIfAborted()
  136. return Promise.resolve({
  137. eventState: 'detached',
  138. events: structuredClone(events.slice(offset, length === undefined ? undefined : offset + length)),
  139. } as const)
  140. },
  141. append: () => Promise.reject(new SessionReadOnlyError(sessionId, 'append')),
  142. flush: () => Promise.reject(new SessionReadOnlyError(sessionId, 'flush')),
  143. close: () => Promise.resolve(),
  144. [Symbol.asyncDispose]: () => Promise.resolve(),
  145. }
  146. }
  147. /**
  148. * Adapt a compact header/inspect persistence double onto the handle-based
  149. * abstract the production readers consume: `list` snapshots wrap the double's
  150. * headers, `stat` derives a metadata-less snapshot from the listing, and
  151. * `open` serves immutable read handles over the double's `inspect` result.
  152. */
  153. export function testSessionPersistence(
  154. _ctx: Context,
  155. persistence: LegacyTestPersistence,
  156. ): Record<string, unknown> {
  157. const listHeaders = async (signal?: AbortSignal): Promise<readonly SessionHeader[]> =>
  158. await persistence.list?.(signal) ?? []
  159. const adapted: Record<string, unknown> = {
  160. ...persistence,
  161. list: async (options?: SessionPersistenceListOptions) =>
  162. (await listHeaders(options?.signal)).map(header => ({
  163. header,
  164. revision: SessionPersistenceRevision(`test:${header.id}:list`),
  165. })),
  166. }
  167. if (persistence.stat === undefined) {
  168. adapted.stat = async (
  169. sessionId: SessionId,
  170. options?: SessionPersistenceStatOptions,
  171. ): Promise<SessionPersistenceSnapshot | undefined> => {
  172. options?.signal?.throwIfAborted()
  173. const header = (await listHeaders(options?.signal)).find(listed => listed.id === sessionId)
  174. return header === undefined
  175. ? undefined
  176. : { header, revision: SessionPersistenceRevision(`test:${sessionId}:stat`) }
  177. }
  178. }
  179. if (persistence.open === undefined) {
  180. adapted.open = async (
  181. sessionId: SessionId,
  182. access: SessionAccess,
  183. options?: SessionPersistenceOpenOptions,
  184. ): Promise<SessionHandle> => {
  185. options?.signal?.throwIfAborted()
  186. if (access !== 'read') {
  187. throw new Error(`test persistence double only serves read handles (requested "${access}")`)
  188. }
  189. const inspection = await persistence.inspect?.(sessionId, options?.signal)
  190. if (inspection === undefined) throw new SessionPersistenceNotFoundError(sessionId)
  191. return testReadHandle(sessionId, inspection)
  192. }
  193. }
  194. return adapted
  195. }
  196. /** Concrete point-read query used by Session Controller tests that do not exercise search. */
  197. class TestSessionQuery extends SessionQueryEngine {
  198. override searchSessions(): Promise<never> {
  199. return Promise.reject(new Error('session search is not configured in this test'))
  200. }
  201. override searchEvents(): Promise<never> {
  202. return Promise.reject(new Error('event search is not configured in this test'))
  203. }
  204. }
  205. /** Install the required projection and point-query services for direct controller tests. */
  206. export function installSessionReadTestServices(ctx: Context): void {
  207. if (ctx.get('sessionProjections') === undefined) new SessionProjectionRegistry(ctx)
  208. if (ctx.get('sessionQuery') === undefined) new TestSessionQuery(ctx)
  209. }
  210. function installControllers(
  211. ctx: Context,
  212. defaults: TestSessionRemoteDefaults,
  213. ): SessionController {
  214. const found = installed.get(ctx)
  215. if (found !== undefined) return found
  216. if (ctx.get('typert') === undefined) {
  217. const dispose = (): void => {}
  218. ctx.provide('typert', {
  219. lookups: { configure: () => dispose },
  220. contexts: { configureHost: () => dispose },
  221. } as never)
  222. }
  223. if (ctx.get('agentDefaultModel') === undefined) {
  224. ctx.provide('agentDefaultModel', {
  225. currentSelection: defaults.defaultModelSelection,
  226. saveSelection: async (selection: AgentModelSelection) => {
  227. await defaults.saveDefaultModelSelection?.(selection)
  228. },
  229. } as never)
  230. }
  231. if (ctx.get('llm') === undefined) {
  232. ctx.provide('llm', {
  233. listProviders: () => {
  234. const selection = defaults.defaultModelSelection()
  235. return [{ id: selection.provider, name: selection.provider }]
  236. },
  237. } as never)
  238. }
  239. if (ctx.get('attachments') === undefined) {
  240. ctx.provide('attachments', {
  241. imageLimits: TEST_IMAGE_LIMITS,
  242. admitPromptContent: async (
  243. content: readonly AttachmentAdmissionPart[],
  244. ): Promise<AdmittedPromptContentPart[]> => {
  245. const admitted: AdmittedPromptContentPart[] = []
  246. for (const part of content) {
  247. if (part.type === 'image') throw new Error('test did not configure image persistence')
  248. admitted.push(part)
  249. }
  250. return admitted
  251. },
  252. } as never)
  253. }
  254. if (ctx.get('fileUploads') === undefined) {
  255. ctx.provide('fileUploads', {
  256. registerAgentResolver: () => () => {},
  257. resolve: () => undefined,
  258. bindPrompt: () => ({ commit: () => {}, [Symbol.dispose]: () => {} }),
  259. retirePrompt: () => {},
  260. } as never)
  261. }
  262. installSessionReadTestServices(ctx)
  263. const cwd = vi.spyOn(process, 'cwd').mockReturnValue(defaults.cwd)
  264. let controller: SessionController
  265. try {
  266. controller = new SessionController(
  267. ctx,
  268. {
  269. ...defaults.nativeOpen === undefined ? {} : { nativeOpen: defaults.nativeOpen },
  270. },
  271. {
  272. ...defaults.openPath === undefined ? {} : { openPath: defaults.openPath },
  273. ...defaults.canOpenPath === undefined ? {} : { canOpenPath: defaults.canOpenPath },
  274. },
  275. )
  276. } finally {
  277. cwd.mockRestore()
  278. }
  279. installed.set(ctx, controller)
  280. return controller
  281. }
  282. /** Build or return the production Session Controller for a direct unit harness. */
  283. export function createSessionTestController(
  284. ctx: Context,
  285. defaults: TestSessionRemoteDefaults,
  286. ): SessionController {
  287. return installControllers(ctx, defaults)
  288. }
  289. function remoteResult<T>(
  290. operation: () => T | Promise<T>,
  291. signal?: AbortSignal,
  292. ): Promise<RemoteResult<T>> {
  293. return Promise.resolve()
  294. .then(operation)
  295. .then(value => ({ ok: true as const, value }))
  296. .catch((error: unknown) => ({
  297. ok: false as const,
  298. error: signal?.aborted === true
  299. ? new RemoteError('gateway/cancelled', 'request was aborted', {})
  300. : remoteErrorOf(error)
  301. ?? new RemoteError(
  302. 'gateway/internal',
  303. error instanceof Error ? error.message : String(error),
  304. {},
  305. ),
  306. }))
  307. }
  308. /** Build the generated Session Remote's unary result semantics without a carrier. */
  309. export function createSessionTestRemote(
  310. ctx: Context,
  311. defaults: TestSessionRemoteDefaults,
  312. ): TestSessionRemote {
  313. const direct = createSessionTestController(ctx, defaults)
  314. return {
  315. canOpenWorkspacePath: () => remoteResult(() => direct.canOpenWorkspacePath()),
  316. list: (request, signal = new AbortController().signal) => remoteResult(
  317. () => direct.list(request, signal),
  318. signal,
  319. ),
  320. search: (request, signal = new AbortController().signal) => remoteResult(
  321. () => direct.search(request, signal),
  322. signal,
  323. ),
  324. create: request => remoteResult(() => direct.create(request)),
  325. selectModel: request => remoteResult(() => direct.selectModel(request)),
  326. modelCatalog: () => remoteResult(() => direct.modelCatalog()),
  327. rename: request => remoteResult(() => direct.rename(request)),
  328. fork: request => remoteResult(() => direct.fork(request)),
  329. prompt: (request, signal = new AbortController().signal) => remoteResult(
  330. () => direct.prompt(request, signal),
  331. signal,
  332. ),
  333. attachment: request => remoteResult(() => direct.attachment(request)),
  334. updateQueue: request => remoteResult(() => direct.updateQueue(request)),
  335. cancel: request => remoteResult(() => direct.cancel(request)),
  336. openWorkspacePath: (request, signal = new AbortController().signal) => remoteResult(
  337. () => direct.openWorkspacePath(request, signal),
  338. signal,
  339. ),
  340. page: (request, signal = new AbortController().signal) => remoteResult(
  341. () => direct.page(request, signal),
  342. signal,
  343. ),
  344. follow: (request, signal = new AbortController().signal) => direct.follow(request, signal),
  345. control: (signal = new AbortController().signal) => direct.control(signal),
  346. }
  347. }