test-remote.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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(events.slice(offset, length === undefined ? undefined : offset + length))
  137. },
  138. append: () => Promise.reject(new SessionReadOnlyError(sessionId, 'append')),
  139. flush: () => Promise.reject(new SessionReadOnlyError(sessionId, 'flush')),
  140. close: () => Promise.resolve(),
  141. [Symbol.asyncDispose]: () => Promise.resolve(),
  142. }
  143. }
  144. /**
  145. * Adapt a compact header/inspect persistence double onto the handle-based
  146. * abstract the production readers consume: `list` snapshots wrap the double's
  147. * headers, `stat` derives a metadata-less snapshot from the listing, and
  148. * `open` serves immutable read handles over the double's `inspect` result.
  149. */
  150. export function testSessionPersistence(
  151. _ctx: Context,
  152. persistence: LegacyTestPersistence,
  153. ): Record<string, unknown> {
  154. const listHeaders = async (signal?: AbortSignal): Promise<readonly SessionHeader[]> =>
  155. await persistence.list?.(signal) ?? []
  156. const adapted: Record<string, unknown> = {
  157. ...persistence,
  158. list: async (options?: SessionPersistenceListOptions) =>
  159. (await listHeaders(options?.signal)).map(header => ({
  160. header,
  161. revision: SessionPersistenceRevision(`test:${header.id}:list`),
  162. })),
  163. }
  164. if (persistence.stat === undefined) {
  165. adapted.stat = async (
  166. sessionId: SessionId,
  167. options?: SessionPersistenceStatOptions,
  168. ): Promise<SessionPersistenceSnapshot | undefined> => {
  169. options?.signal?.throwIfAborted()
  170. const header = (await listHeaders(options?.signal)).find(listed => listed.id === sessionId)
  171. return header === undefined
  172. ? undefined
  173. : { header, revision: SessionPersistenceRevision(`test:${sessionId}:stat`) }
  174. }
  175. }
  176. if (persistence.open === undefined) {
  177. adapted.open = async (
  178. sessionId: SessionId,
  179. access: SessionAccess,
  180. options?: SessionPersistenceOpenOptions,
  181. ): Promise<SessionHandle> => {
  182. options?.signal?.throwIfAborted()
  183. if (access !== 'read') {
  184. throw new Error(`test persistence double only serves read handles (requested "${access}")`)
  185. }
  186. const inspection = await persistence.inspect?.(sessionId, options?.signal)
  187. if (inspection === undefined) throw new SessionPersistenceNotFoundError(sessionId)
  188. return testReadHandle(sessionId, inspection)
  189. }
  190. }
  191. return adapted
  192. }
  193. /** Concrete point-read query used by Session Controller tests that do not exercise search. */
  194. class TestSessionQuery extends SessionQueryEngine {
  195. override searchSessions(): Promise<never> {
  196. return Promise.reject(new Error('session search is not configured in this test'))
  197. }
  198. override searchEvents(): Promise<never> {
  199. return Promise.reject(new Error('event search is not configured in this test'))
  200. }
  201. }
  202. /** Install the required projection and point-query services for direct controller tests. */
  203. export function installSessionReadTestServices(ctx: Context): void {
  204. if (ctx.get('sessionProjections') === undefined) new SessionProjectionRegistry(ctx)
  205. if (ctx.get('sessionQuery') === undefined) new TestSessionQuery(ctx)
  206. }
  207. function installControllers(
  208. ctx: Context,
  209. defaults: TestSessionRemoteDefaults,
  210. ): SessionController {
  211. const found = installed.get(ctx)
  212. if (found !== undefined) return found
  213. if (ctx.get('typert') === undefined) {
  214. const dispose = (): void => {}
  215. ctx.provide('typert', {
  216. lookups: { configure: () => dispose },
  217. contexts: { configureHost: () => dispose },
  218. } as never)
  219. }
  220. if (ctx.get('agentDefaultModel') === undefined) {
  221. ctx.provide('agentDefaultModel', {
  222. currentSelection: defaults.defaultModelSelection,
  223. saveSelection: async (selection: AgentModelSelection) => {
  224. await defaults.saveDefaultModelSelection?.(selection)
  225. },
  226. } as never)
  227. }
  228. if (ctx.get('llm') === undefined) {
  229. ctx.provide('llm', {
  230. listProviders: () => {
  231. const selection = defaults.defaultModelSelection()
  232. return [{ id: selection.provider, name: selection.provider }]
  233. },
  234. } as never)
  235. }
  236. if (ctx.get('attachments') === undefined) {
  237. ctx.provide('attachments', {
  238. imageLimits: TEST_IMAGE_LIMITS,
  239. admitPromptContent: async (
  240. content: readonly AttachmentAdmissionPart[],
  241. ): Promise<AdmittedPromptContentPart[]> => {
  242. const admitted: AdmittedPromptContentPart[] = []
  243. for (const part of content) {
  244. if (part.type === 'image') throw new Error('test did not configure image persistence')
  245. admitted.push(part)
  246. }
  247. return admitted
  248. },
  249. } as never)
  250. }
  251. if (ctx.get('fileUploads') === undefined) {
  252. ctx.provide('fileUploads', {
  253. registerAgentResolver: () => () => {},
  254. resolve: () => undefined,
  255. bindPrompt: () => ({ commit: () => {}, [Symbol.dispose]: () => {} }),
  256. retirePrompt: () => {},
  257. } as never)
  258. }
  259. installSessionReadTestServices(ctx)
  260. const cwd = vi.spyOn(process, 'cwd').mockReturnValue(defaults.cwd)
  261. let controller: SessionController
  262. try {
  263. controller = new SessionController(
  264. ctx,
  265. {
  266. ...defaults.nativeOpen === undefined ? {} : { nativeOpen: defaults.nativeOpen },
  267. },
  268. {
  269. ...defaults.openPath === undefined ? {} : { openPath: defaults.openPath },
  270. ...defaults.canOpenPath === undefined ? {} : { canOpenPath: defaults.canOpenPath },
  271. },
  272. )
  273. } finally {
  274. cwd.mockRestore()
  275. }
  276. installed.set(ctx, controller)
  277. return controller
  278. }
  279. /** Build or return the production Session Controller for a direct unit harness. */
  280. export function createSessionTestController(
  281. ctx: Context,
  282. defaults: TestSessionRemoteDefaults,
  283. ): SessionController {
  284. return installControllers(ctx, defaults)
  285. }
  286. function remoteResult<T>(
  287. operation: () => T | Promise<T>,
  288. signal?: AbortSignal,
  289. ): Promise<RemoteResult<T>> {
  290. return Promise.resolve()
  291. .then(operation)
  292. .then(value => ({ ok: true as const, value }))
  293. .catch((error: unknown) => ({
  294. ok: false as const,
  295. error: signal?.aborted === true
  296. ? new RemoteError('gateway/cancelled', 'request was aborted', {})
  297. : remoteErrorOf(error)
  298. ?? new RemoteError(
  299. 'gateway/internal',
  300. error instanceof Error ? error.message : String(error),
  301. {},
  302. ),
  303. }))
  304. }
  305. /** Build the generated Session Remote's unary result semantics without a carrier. */
  306. export function createSessionTestRemote(
  307. ctx: Context,
  308. defaults: TestSessionRemoteDefaults,
  309. ): TestSessionRemote {
  310. const direct = createSessionTestController(ctx, defaults)
  311. return {
  312. canOpenWorkspacePath: () => remoteResult(() => direct.canOpenWorkspacePath()),
  313. list: (request, signal = new AbortController().signal) => remoteResult(
  314. () => direct.list(request, signal),
  315. signal,
  316. ),
  317. search: (request, signal = new AbortController().signal) => remoteResult(
  318. () => direct.search(request, signal),
  319. signal,
  320. ),
  321. create: request => remoteResult(() => direct.create(request)),
  322. selectModel: request => remoteResult(() => direct.selectModel(request)),
  323. modelCatalog: () => remoteResult(() => direct.modelCatalog()),
  324. rename: request => remoteResult(() => direct.rename(request)),
  325. fork: request => remoteResult(() => direct.fork(request)),
  326. prompt: (request, signal = new AbortController().signal) => remoteResult(
  327. () => direct.prompt(request, signal),
  328. signal,
  329. ),
  330. attachment: request => remoteResult(() => direct.attachment(request)),
  331. updateQueue: request => remoteResult(() => direct.updateQueue(request)),
  332. cancel: request => remoteResult(() => direct.cancel(request)),
  333. openWorkspacePath: (request, signal = new AbortController().signal) => remoteResult(
  334. () => direct.openWorkspacePath(request, signal),
  335. signal,
  336. ),
  337. page: (request, signal = new AbortController().signal) => remoteResult(
  338. () => direct.page(request, signal),
  339. signal,
  340. ),
  341. follow: (request, signal = new AbortController().signal) => direct.follow(request, signal),
  342. control: (signal = new AbortController().signal) => direct.control(signal),
  343. }
  344. }