browser-plugin.client.spec.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. /**
  2. * Web reference source coverage: Remote-backed file/session discovery,
  3. * deterministic ordering and labels, quoted-path suppression, pick projections, codec
  4. * round-trip, and registration lifecycle.
  5. */
  6. import { Context, Service } from '@deepseek-ai/cordis'
  7. import { describe, expect, it, vi } from 'vitest'
  8. import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client'
  9. import type { SessionId } from '@deepseek-ai/dsh-session/types'
  10. import type {
  11. CandidateRequest, ClientSessionContext, InputTriggerCandidate, InputTriggerSource,
  12. } from '@deepseek-ai/dsh-client-ui-input-trigger/client'
  13. import type { FileReferenceCandidate } from '@deepseek-ai/dsh-file-reference/types'
  14. import type { SessionReferenceMentionCandidate } from '@deepseek-ai/dsh-session-reference/types'
  15. import { apply, inject } from '../src/client/index.ts'
  16. import { apply as nodeApply } from '../src/index.ts'
  17. const sid = (value: string): SessionId => value as SessionId
  18. const session: ClientSessionContext = { sessionId: sid('target') }
  19. type RemoteEnvelope<T> =
  20. | { ok: true; value: T }
  21. | { ok: false; error: { code: string; message: string; details: object } }
  22. type RemoteLookup<T> = (
  23. agentId: SessionId,
  24. query: string,
  25. signal?: AbortSignal,
  26. ) => Promise<RemoteEnvelope<T[]>>
  27. function request(
  28. query: string,
  29. options: { quoted?: boolean; signal?: AbortSignal } = {},
  30. ): CandidateRequest {
  31. return {
  32. query,
  33. quoted: options.quoted ?? false,
  34. position: 'inline',
  35. signal: options.signal ?? new AbortController().signal,
  36. }
  37. }
  38. async function bench(
  39. files: RemoteLookup<FileReferenceCandidate> = vi.fn(() => Promise.resolve({
  40. ok: true as const,
  41. value: [
  42. { path: 'src', kind: 'directory' as const },
  43. { path: 'docs/a b.md', kind: 'file' as const },
  44. ],
  45. })),
  46. sessions: RemoteLookup<SessionReferenceMentionCandidate> = vi.fn(() => Promise.resolve({
  47. ok: true as const,
  48. value: [{
  49. sessionId: sid('source'),
  50. label: 'Research',
  51. cwd: '/project',
  52. createdAt: 1_700_000_000_000,
  53. mention: '@[Research](dsh-session:InNvdXJjZSI)',
  54. }],
  55. })),
  56. ): Promise<{ ctx: Context; fiber: ReturnType<Context['plugin']>; source: InputTriggerSource }> {
  57. const ctx = new Context()
  58. let source: InputTriggerSource | undefined
  59. ctx.provide('inputTriggers', {
  60. registerSource(candidate: InputTriggerSource) {
  61. source = candidate
  62. return () => { source = undefined }
  63. },
  64. })
  65. class RemoteService extends Service {
  66. constructor(serviceCtx: Context) {
  67. super(serviceCtx, 'remote')
  68. }
  69. }
  70. new RemoteService(ctx)
  71. ctx.provide('remote.fileReferences', { list: files })
  72. ctx.provide('remote.sessionReferenceResolver', { candidates: sessions })
  73. ctx.provide('locale', new LocaleRuntime(ctx))
  74. const fiber = ctx.plugin({ inject: [...inject], apply })
  75. await fiber.await()
  76. if (source === undefined) throw new Error('reference source was not registered')
  77. return { ctx, fiber, source }
  78. }
  79. describe('apply', () => {
  80. it('declares its services and releases the @ reference registration on disposal', async () => {
  81. expect(inject).toEqual([
  82. 'inputTriggers', 'locale', 'remote', 'remote.fileReferences', 'remote.sessionReferenceResolver',
  83. ])
  84. const { fiber } = await bench()
  85. let registered: InputTriggerSource | undefined
  86. const ctx = new Context()
  87. ctx.provide('inputTriggers', {
  88. registerSource(source: InputTriggerSource) {
  89. registered = source
  90. return () => { registered = undefined }
  91. },
  92. })
  93. class RemoteService extends Service {
  94. constructor(serviceCtx: Context) {
  95. super(serviceCtx, 'remote')
  96. }
  97. }
  98. new RemoteService(ctx)
  99. ctx.provide('remote.fileReferences', { list: () => Promise.resolve({ ok: true, value: [] }) })
  100. ctx.provide('remote.sessionReferenceResolver', { candidates: () => Promise.resolve({ ok: true, value: [] }) })
  101. ctx.provide('locale', new LocaleRuntime(ctx))
  102. const ownFiber = ctx.plugin({ inject: [...inject], apply })
  103. await ownFiber.await()
  104. expect(registered).toMatchObject({ trigger: '@', name: 'reference', showGroupTitle: false })
  105. await ownFiber.dispose()
  106. expect(registered).toBeUndefined()
  107. await fiber.dispose()
  108. })
  109. it('the node half applies without host-side behavior', () => {
  110. expect(() => { nodeApply() }).not.toThrow()
  111. })
  112. })
  113. describe('candidates', () => {
  114. it('starts both Remote lookups together and renders files before sessions with stable labels', async () => {
  115. let releaseFiles!: () => void
  116. let releaseSessions!: () => void
  117. const files = vi.fn(() => new Promise<{
  118. ok: true
  119. value: { path: string; kind: 'file' | 'directory' }[]
  120. }>((resolve) => {
  121. releaseFiles = () => {
  122. resolve({
  123. ok: true,
  124. value: [
  125. { path: 'src', kind: 'directory' },
  126. { path: 'docs/a b.md', kind: 'file' },
  127. ],
  128. })
  129. }
  130. }))
  131. const sessions = vi.fn(() => new Promise<{
  132. ok: true
  133. value: {
  134. sessionId: SessionId
  135. label: string
  136. cwd: string
  137. createdAt: number
  138. mention: string
  139. }[]
  140. }>((resolve) => {
  141. releaseSessions = () => {
  142. resolve({
  143. ok: true,
  144. value: [{
  145. sessionId: sid('source'),
  146. label: 'Research',
  147. cwd: '/project',
  148. createdAt: 1_700_000_000_000,
  149. mention: '@[Research](dsh-session:InNvdXJjZSI)',
  150. }],
  151. })
  152. }
  153. }))
  154. const { source } = await bench(files, sessions)
  155. const pending = source.candidates(session, request('re'))
  156. expect(files).toHaveBeenCalledTimes(1)
  157. expect(sessions).toHaveBeenCalledTimes(1)
  158. releaseSessions()
  159. releaseFiles()
  160. await expect(pending).resolves.toEqual([
  161. expect.objectContaining({
  162. name: 'Folder · src/',
  163. description: 'src',
  164. section: 'Files & folders',
  165. }),
  166. expect.objectContaining({
  167. name: 'File · a b.md',
  168. description: 'docs/a b.md',
  169. section: 'Files & folders',
  170. }),
  171. expect.objectContaining({
  172. name: 'Session · Research',
  173. description: 'source · /project · 2023-11-14T22:13:20.000Z',
  174. section: 'Session conversations',
  175. }),
  176. ])
  177. })
  178. it('suppresses sessions for an open quoted path and degrades each failed domain independently', async () => {
  179. const files = vi.fn()
  180. .mockResolvedValueOnce({
  181. ok: true as const,
  182. value: [{ path: 'README.md', kind: 'file' as const }],
  183. })
  184. .mockRejectedValueOnce(new Error('file scan failed'))
  185. const sessions = vi.fn(() => Promise.resolve({
  186. ok: true as const,
  187. value: [{
  188. sessionId: sid('source'),
  189. label: 'Research',
  190. cwd: '/project',
  191. createdAt: 0,
  192. mention: '@[Research](dsh-session:InNvdXJjZSI)',
  193. }],
  194. }))
  195. const { source } = await bench(files, sessions)
  196. const quoted = await source.candidates(session, request('READ', { quoted: true }))
  197. expect(quoted).toEqual([expect.objectContaining({ name: 'File · README.md' })])
  198. expect(source.onPick({
  199. candidate: quoted[0]!,
  200. session,
  201. position: 'inline',
  202. via: 'menu',
  203. span: { start: 0, end: 6, draftRev: 1 },
  204. })).toEqual({
  205. insert: {
  206. source: 'reference',
  207. ref: '@"README.md"',
  208. label: 'README.md',
  209. appearance: 'file',
  210. clipboardText: '@"README.md"',
  211. },
  212. })
  213. expect(sessions).not.toHaveBeenCalled()
  214. await expect(source.candidates(session, request('research'))).resolves.toEqual([
  215. expect.objectContaining({ name: 'Session · Research' }),
  216. ])
  217. })
  218. it('drops a completed result when the query signal was superseded', async () => {
  219. const controller = new AbortController()
  220. const { source } = await bench()
  221. const pending = source.candidates(session, request('', { signal: controller.signal }))
  222. controller.abort()
  223. await expect(pending).resolves.toEqual([])
  224. })
  225. it('treats Remote failures as empty domains and filters paths that cannot be mentioned', async () => {
  226. const files = vi.fn(() => Promise.resolve({
  227. ok: true as const,
  228. value: [{ path: 'bad\nname', kind: 'file' as const }],
  229. }))
  230. const sessions = vi.fn()
  231. .mockRejectedValueOnce(new Error('session lookup failed'))
  232. .mockResolvedValueOnce({
  233. ok: false as const,
  234. error: { code: 'internal', message: 'session lookup failed', details: {} },
  235. })
  236. const { source } = await bench(files, sessions)
  237. await expect(source.candidates(session, request('bad'))).resolves.toEqual([])
  238. files.mockResolvedValueOnce({
  239. ok: false as const,
  240. error: { code: 'internal', message: 'file lookup failed', details: {} },
  241. } as never)
  242. await expect(source.candidates(session, request('bad'))).resolves.toEqual([])
  243. })
  244. it('omits redundant session ids and labels sessions without a cwd', async () => {
  245. const files = vi.fn(() => Promise.resolve({ ok: true as const, value: [] }))
  246. const sessions = vi.fn(() => Promise.resolve({
  247. ok: true as const,
  248. value: [{
  249. sessionId: sid('same'),
  250. label: 'same',
  251. createdAt: 0,
  252. mention: '@[same](dsh-session:InNhbWUi)',
  253. }],
  254. }))
  255. const { source } = await bench(files, sessions)
  256. await expect(source.candidates(session, request('same'))).resolves.toEqual([
  257. expect.objectContaining({
  258. name: 'Session · same',
  259. description: '(no cwd) · 1970-01-01T00:00:00.000Z',
  260. }),
  261. ])
  262. })
  263. })
  264. describe('pick and codec', () => {
  265. const pick = (source: InputTriggerSource, candidate: InputTriggerCandidate) => source.onPick({
  266. candidate,
  267. session,
  268. position: 'inline',
  269. via: 'menu',
  270. span: { start: 0, end: 1, draftRev: 1 },
  271. })
  272. it('inserts files as atomic icon labels while keeping directory completion open', async () => {
  273. const { source } = await bench()
  274. const [directory, file] = await source.candidates(session, request(''))
  275. expect(pick(source, directory!)).toEqual({ text: '@src/', continue: true })
  276. expect(pick(source, file!)).toEqual({
  277. insert: {
  278. source: 'reference',
  279. ref: '@"docs/a b.md"',
  280. label: 'a b.md',
  281. appearance: 'file',
  282. clipboardText: '@"docs/a b.md"',
  283. },
  284. })
  285. const [quotedDirectory] = await source.candidates(session, request('', { quoted: true }))
  286. expect(pick(source, quotedDirectory!)).toEqual({ text: '@"src/', continue: true })
  287. })
  288. it('inserts sessions as atomic chips whose clipboard and model forms are canonical mentions', async () => {
  289. const { source } = await bench()
  290. const candidates = await source.candidates(session, request(''))
  291. const candidate = candidates.find(item => item.name === 'Session · Research')!
  292. const mention = '@[Research](dsh-session:InNvdXJjZSI)'
  293. expect(pick(source, candidate)).toEqual({
  294. insert: {
  295. source: 'reference',
  296. ref: mention,
  297. label: 'Research',
  298. appearance: 'session',
  299. clipboardText: mention,
  300. },
  301. })
  302. expect(source.codec?.clipboardText(mention)).toBe(mention)
  303. await expect(source.codec?.serialize(mention, new AbortController().signal)).resolves.toBe(mention)
  304. })
  305. it('ignores candidates that do not carry a source-owned value', async () => {
  306. const { source } = await bench()
  307. expect(pick(source, { name: 'foreign candidate' })).toBeUndefined()
  308. })
  309. })