browser-plugin.spec.ts 11 KB

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