browser-plugin.client.spec.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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 { afterEach, beforeEach, 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 { RemoteError } from '@deepseek-ai/dsh-client-test-runtime'
  11. import type {
  12. CandidateRequest, ClientSessionContext, InputTriggerCandidate, InputTriggerSource,
  13. } from '@deepseek-ai/dsh-client-ui-input-trigger/client'
  14. import type { FileReferenceCandidate } from '@deepseek-ai/dsh-file-reference/types'
  15. import type { SessionReferenceMentionCandidate } from '@deepseek-ai/dsh-session-reference/types'
  16. import { apply, inject } from '../src/client/index.ts'
  17. import { apply as nodeApply } from '../src/index.ts'
  18. const sid = (value: string): SessionId => value as SessionId
  19. const session: ClientSessionContext = { sessionId: sid('target') }
  20. /** The target session's own workspace: candidates in it are the `sameWorkspace` rows. */
  21. const HOME = '/Users/dev'
  22. const CREATED_AT = 1_700_000_000_000
  23. /** Three days after every fixture's createdAt, so age copy is one fixed bucket. */
  24. const NOW = CREATED_AT + 3 * 86_400_000
  25. /** The Host session list dates a row; only a session missing from it falls back to createdAt. */
  26. const UPDATED_AT = NOW - 3_600_000
  27. beforeEach(() => {
  28. vi.useFakeTimers({ toFake: ['Date'] })
  29. vi.setSystemTime(NOW)
  30. })
  31. afterEach(() => { vi.useRealTimers() })
  32. type RemoteEnvelope<T> =
  33. | { ok: true; value: T }
  34. | { ok: false; error: { code: string; message: string; details: object } }
  35. type RemoteLookup<T> = (
  36. agentId: SessionId,
  37. query: string,
  38. signal?: AbortSignal,
  39. ) => Promise<RemoteEnvelope<T[]>>
  40. function request(
  41. query: string,
  42. options: { quoted?: boolean; signal?: AbortSignal } = {},
  43. ): CandidateRequest {
  44. return {
  45. query,
  46. quoted: options.quoted ?? false,
  47. position: 'inline',
  48. drilled: false,
  49. signal: options.signal ?? new AbortController().signal,
  50. }
  51. }
  52. async function bench(
  53. files: RemoteLookup<FileReferenceCandidate> = vi.fn(() => Promise.resolve({
  54. ok: true as const,
  55. value: [
  56. { path: 'src', kind: 'directory' as const },
  57. { path: 'docs/a b.md', kind: 'file' as const },
  58. ],
  59. })),
  60. sessions: RemoteLookup<SessionReferenceMentionCandidate> = vi.fn(() => Promise.resolve({
  61. ok: true as const,
  62. value: [{
  63. sessionId: sid('source'),
  64. label: 'Research',
  65. cwd: `${HOME}/project`,
  66. sameWorkspace: false,
  67. createdAt: CREATED_AT,
  68. mention: '@[Research](dsh-session:InNvdXJjZSI)',
  69. }],
  70. })),
  71. listed: Record<string, { updatedAt: number }> = {},
  72. ): Promise<{ ctx: Context; fiber: ReturnType<Context['plugin']>; source: InputTriggerSource }> {
  73. const ctx = new Context()
  74. ctx.provide('sidebarRight', { openResource: vi.fn() })
  75. let source: InputTriggerSource | undefined
  76. ctx.provide('inputTriggers', {
  77. registerSource(candidate: InputTriggerSource) {
  78. source = candidate
  79. return () => { source = undefined }
  80. },
  81. })
  82. class RemoteService extends Service {
  83. readonly $host = { home: HOME, isLoopback: true }
  84. constructor(serviceCtx: Context) {
  85. super(serviceCtx, 'remote')
  86. }
  87. }
  88. new RemoteService(ctx)
  89. ctx.provide('remote.fileReferences', { list: files })
  90. ctx.provide('remote.sessionReferenceResolver', { candidates: sessions })
  91. ctx.provide('locale', new LocaleRuntime(ctx))
  92. ctx.provide('sessions', { list: { getSnapshot: () => ({ byId: listed }) } })
  93. const fiber = ctx.plugin({ inject: [...inject], apply })
  94. await fiber.await()
  95. if (source === undefined) throw new Error('reference source was not registered')
  96. return { ctx, fiber, source }
  97. }
  98. describe('apply', () => {
  99. it('declares its services and releases the @ reference registration on disposal', async () => {
  100. expect(inject).toEqual([
  101. 'inputTriggers', 'locale', 'sessions', 'remote', 'remote.fileReferences',
  102. 'remote.sessionReferenceResolver', 'sidebarRight',
  103. ])
  104. const { fiber } = await bench()
  105. let registered: InputTriggerSource | undefined
  106. const ctx = new Context()
  107. ctx.provide('sidebarRight', { openResource: vi.fn() })
  108. ctx.provide('inputTriggers', {
  109. registerSource(source: InputTriggerSource) {
  110. registered = source
  111. return () => { registered = undefined }
  112. },
  113. })
  114. class RemoteService extends Service {
  115. readonly $host = { home: undefined, isLoopback: false }
  116. constructor(serviceCtx: Context) {
  117. super(serviceCtx, 'remote')
  118. }
  119. }
  120. new RemoteService(ctx)
  121. ctx.provide('remote.fileReferences', { list: () => Promise.resolve({ ok: true, value: [] }) })
  122. ctx.provide('remote.sessionReferenceResolver', { candidates: () => Promise.resolve({ ok: true, value: [] }) })
  123. ctx.provide('locale', new LocaleRuntime(ctx))
  124. ctx.provide('sessions', { list: { getSnapshot: () => ({ byId: {} }) } })
  125. const ownFiber = ctx.plugin({ inject: [...inject], apply })
  126. await ownFiber.await()
  127. expect(registered).toMatchObject({ trigger: '@', name: 'reference', showGroupTitle: false })
  128. await ownFiber.dispose()
  129. expect(registered).toBeUndefined()
  130. await fiber.dispose()
  131. })
  132. it('the node half applies without host-side behavior', () => {
  133. expect(() => { nodeApply() }).not.toThrow()
  134. })
  135. })
  136. describe('candidates', () => {
  137. it('starts both Remote lookups together and renders files before sessions with stable labels', async () => {
  138. let releaseFiles!: () => void
  139. let releaseSessions!: () => void
  140. const files = vi.fn(() => new Promise<{
  141. ok: true
  142. value: { path: string; kind: 'file' | 'directory' }[]
  143. }>((resolve) => {
  144. releaseFiles = () => {
  145. resolve({
  146. ok: true,
  147. value: [
  148. { path: 'src', kind: 'directory' },
  149. { path: 'docs/a b.md', kind: 'file' },
  150. ],
  151. })
  152. }
  153. }))
  154. const sessions = vi.fn(() => new Promise<{
  155. ok: true
  156. value: {
  157. sessionId: SessionId
  158. label: string
  159. cwd: string
  160. sameWorkspace: boolean
  161. createdAt: number
  162. mention: string
  163. }[]
  164. }>((resolve) => {
  165. releaseSessions = () => {
  166. resolve({
  167. ok: true,
  168. value: [{
  169. sessionId: sid('source'),
  170. label: 'Research',
  171. cwd: `${HOME}/project`,
  172. sameWorkspace: false,
  173. createdAt: CREATED_AT,
  174. mention: '@[Research](dsh-session:InNvdXJjZSI)',
  175. }],
  176. })
  177. }
  178. }))
  179. const { source } = await bench(files, sessions, { source: { updatedAt: UPDATED_AT } })
  180. const pending = source.candidates(session, request('re'))
  181. expect(files).toHaveBeenCalledTimes(1)
  182. expect(sessions).toHaveBeenCalledTimes(1)
  183. releaseSessions()
  184. releaseFiles()
  185. await expect(pending).resolves.toEqual([
  186. {
  187. name: 'src/',
  188. icon: 'folder',
  189. section: 'Files & folders',
  190. value: JSON.stringify({ kind: 'file', fileKind: 'directory', label: 'src', mention: '@src/' }),
  191. drill: true,
  192. },
  193. expect.objectContaining({
  194. name: 'a b.md',
  195. description: 'docs',
  196. icon: 'file',
  197. section: 'Files & folders',
  198. }),
  199. expect.objectContaining({
  200. name: 'Research',
  201. description: '~/project · 1h',
  202. icon: 'session',
  203. section: 'Sessions',
  204. }),
  205. ])
  206. })
  207. it('suppresses sessions for an open quoted path and degrades each failed domain independently', async () => {
  208. const files = vi.fn()
  209. .mockResolvedValueOnce({
  210. ok: true as const,
  211. value: [{ path: 'README.md', kind: 'file' as const }],
  212. })
  213. .mockResolvedValueOnce({
  214. ok: false as const,
  215. error: new RemoteError('gateway/internal', 'file scan failed', {}),
  216. })
  217. const sessions = vi.fn(() => Promise.resolve({
  218. ok: true as const,
  219. value: [{
  220. sessionId: sid('source'),
  221. label: 'Research',
  222. cwd: `${HOME}/project`,
  223. sameWorkspace: false,
  224. createdAt: CREATED_AT,
  225. mention: '@[Research](dsh-session:InNvdXJjZSI)',
  226. }],
  227. }))
  228. const { source } = await bench(files, sessions)
  229. const quoted = await source.candidates(session, request('READ', { quoted: true }))
  230. expect(quoted).toEqual([expect.objectContaining({ name: 'README.md', icon: 'file' })])
  231. expect(source.onPick({
  232. candidate: quoted[0]!,
  233. session,
  234. position: 'inline',
  235. via: 'menu',
  236. action: 'pick',
  237. span: { start: 0, end: 6, draftRev: 1 },
  238. })).toEqual({
  239. insert: {
  240. source: 'reference',
  241. ref: '@"README.md"',
  242. label: 'README.md',
  243. appearance: 'file',
  244. clipboardText: '@"README.md"',
  245. },
  246. })
  247. expect(sessions).not.toHaveBeenCalled()
  248. await expect(source.candidates(session, request('research'))).resolves.toEqual([
  249. expect.objectContaining({ name: 'Research', icon: 'session' }),
  250. ])
  251. })
  252. it('drops a completed result when the query signal was superseded', async () => {
  253. const controller = new AbortController()
  254. const { source } = await bench()
  255. const pending = source.candidates(session, request('', { signal: controller.signal }))
  256. controller.abort()
  257. await expect(pending).resolves.toEqual([])
  258. })
  259. it('treats Remote failures as empty domains and filters paths that cannot be mentioned', async () => {
  260. const files = vi.fn(() => Promise.resolve({
  261. ok: true as const,
  262. value: [{ path: 'bad\nname', kind: 'file' as const }],
  263. }))
  264. const sessions = vi.fn(() => Promise.resolve({
  265. ok: false as const,
  266. error: new RemoteError('gateway/internal', 'session lookup failed', {}),
  267. }))
  268. const { source } = await bench(files, sessions)
  269. await expect(source.candidates(session, request('bad'))).resolves.toEqual([])
  270. files.mockResolvedValueOnce({
  271. ok: false as const,
  272. error: new RemoteError('gateway/internal', 'file lookup failed', {}),
  273. } as never)
  274. await expect(source.candidates(session, request('bad'))).resolves.toEqual([])
  275. })
  276. it('labels a session without a cwd and still dates it', async () => {
  277. const files = vi.fn(() => Promise.resolve({ ok: true as const, value: [] }))
  278. const sessions = vi.fn(() => Promise.resolve({
  279. ok: true as const,
  280. value: [{
  281. sessionId: sid('same'),
  282. label: 'same',
  283. sameWorkspace: false,
  284. createdAt: CREATED_AT,
  285. mention: '@[same](dsh-session:InNhbWUi)',
  286. }],
  287. }))
  288. const { source } = await bench(files, sessions)
  289. await expect(source.candidates(session, request('same'))).resolves.toEqual([
  290. expect.objectContaining({
  291. name: 'same',
  292. description: '(no cwd) · 3d',
  293. }),
  294. ])
  295. })
  296. it('falls back to the candidate createdAt for a session the Host list does not carry', async () => {
  297. const files = vi.fn(() => Promise.resolve({ ok: true as const, value: [] }))
  298. const sessions = vi.fn(() => Promise.resolve({
  299. ok: true as const,
  300. value: [{
  301. sessionId: sid('unlisted'),
  302. label: 'Unlisted run',
  303. cwd: `${HOME}/project`,
  304. sameWorkspace: true,
  305. createdAt: CREATED_AT,
  306. mention: '@[Unlisted run](dsh-session:InVubGlzdGVkIg)',
  307. }],
  308. }))
  309. // A row absent from the list has no durable activity time to read.
  310. const { source } = await bench(files, sessions, { other: { updatedAt: UPDATED_AT } })
  311. await expect(source.candidates(session, request('unlisted'))).resolves.toEqual([
  312. expect.objectContaining({ name: 'Unlisted run', description: '3d' }),
  313. ])
  314. })
  315. it('reads a session opened moments ago as the present, not a zero distance', async () => {
  316. const files = vi.fn(() => Promise.resolve({ ok: true as const, value: [] }))
  317. const sessions = vi.fn(() => Promise.resolve({
  318. ok: true as const,
  319. value: [{
  320. sessionId: sid('just-now'),
  321. label: 'Just now',
  322. cwd: `${HOME}/project`,
  323. sameWorkspace: true,
  324. createdAt: NOW - 1_000,
  325. mention: '@[Just now](dsh-session:Imp1c3Qtbm93Ig)',
  326. }],
  327. }))
  328. const { source } = await bench(files, sessions, { 'just-now': { updatedAt: NOW - 1_000 } })
  329. await expect(source.candidates(session, request('just'))).resolves.toEqual([
  330. expect.objectContaining({ name: 'Just now', description: 'now' }),
  331. ])
  332. })
  333. it('dates a session in the current workspace without repeating that workspace', async () => {
  334. const files = vi.fn(() => Promise.resolve({ ok: true as const, value: [] }))
  335. const sessions = vi.fn(() => Promise.resolve({
  336. ok: true as const,
  337. value: [{
  338. sessionId: sid('sibling'),
  339. label: 'Sibling run',
  340. cwd: `${HOME}/project`,
  341. sameWorkspace: true,
  342. createdAt: CREATED_AT,
  343. mention: '@[Sibling run](dsh-session:InNpYmxpbmdyIg)',
  344. }],
  345. }))
  346. const { source } = await bench(files, sessions)
  347. await expect(source.candidates(session, request('sib'))).resolves.toEqual([
  348. expect.objectContaining({ name: 'Sibling run', description: '3d' }),
  349. ])
  350. })
  351. })
  352. describe('directory header', () => {
  353. const drilledRequest = (query: string, quoted = false): CandidateRequest => ({
  354. query,
  355. quoted,
  356. position: 'inline',
  357. drilled: true,
  358. signal: new AbortController().signal,
  359. })
  360. it('publishes no header for a query the user typed', async () => {
  361. const { source } = await bench()
  362. expect(source.header?.(session, { query: 'src/module1/', drilled: false })).toBeUndefined()
  363. })
  364. it('publishes no header until a drilled query names a directory', async () => {
  365. const { source } = await bench()
  366. expect(source.header?.(session, { query: 'src', drilled: true })).toBeUndefined()
  367. })
  368. it('trails the workspace root down to the directory being listed', async () => {
  369. const { source } = await bench()
  370. expect(source.header?.(session, { query: 'src/module1/ind', drilled: true })).toEqual([
  371. { label: 'Workspace', value: JSON.stringify({ kind: 'file', fileKind: 'directory', label: 'Workspace', mention: '@' }) },
  372. { label: 'src', value: JSON.stringify({ kind: 'file', fileKind: 'directory', label: 'src', mention: '@src/' }) },
  373. {
  374. label: 'module1',
  375. value: JSON.stringify({ kind: 'file', fileKind: 'directory', label: 'module1', mention: '@src/module1/' }),
  376. current: true,
  377. },
  378. ])
  379. })
  380. it('keeps an open quote across every crumb of a quoted descent', async () => {
  381. const { source } = await bench()
  382. const crumbs = source.header?.(session, { query: 'my dir/sub/', quoted: true, drilled: true })
  383. expect(crumbs?.map(crumb => JSON.parse(crumb.value) as { mention: string }).map(value => value.mention))
  384. .toEqual(['@"', '@"my dir/', '@"my dir/sub/'])
  385. })
  386. it('publishes no header when a segment cannot be written back as mention text', async () => {
  387. const { source } = await bench()
  388. expect(source.header?.(session, { query: 'ok/we\u0001ird/', drilled: true })).toBeUndefined()
  389. })
  390. it('returns to a crumb through the same drill outcome a folder row uses', async () => {
  391. const { source } = await bench()
  392. const crumbs = source.header?.(session, { query: 'src/module1/', drilled: true })
  393. expect(source.onPick({
  394. candidate: { name: 'src', value: crumbs?.[1]?.value ?? '' },
  395. session,
  396. position: 'inline',
  397. via: 'menu',
  398. action: 'drill',
  399. span: { start: 0, end: 13, draftRev: 1 },
  400. })).toEqual({ text: '@src/', continue: true })
  401. })
  402. it('drops the row location a drilled listing already shows in its header', async () => {
  403. const files = vi.fn(() => Promise.resolve({
  404. ok: true as const,
  405. value: [{ path: 'src/module1/index.html', kind: 'file' as const }],
  406. }))
  407. const sessions = vi.fn(() => Promise.resolve({ ok: true as const, value: [] }))
  408. const { source } = await bench(files, sessions)
  409. await expect(source.candidates(session, drilledRequest('src/module1/'))).resolves.toEqual([
  410. expect.objectContaining({ name: 'index.html', icon: 'file' }),
  411. ])
  412. const [row] = await source.candidates(session, drilledRequest('src/module1/'))
  413. expect(row).not.toHaveProperty('description')
  414. })
  415. })
  416. describe('pick and codec', () => {
  417. const pickAs = (action: 'pick' | 'drill') =>
  418. (source: InputTriggerSource, candidate: InputTriggerCandidate) => source.onPick({
  419. candidate,
  420. session,
  421. position: 'inline',
  422. via: 'menu',
  423. action,
  424. span: { start: 0, end: 1, draftRev: 1 },
  425. })
  426. const pick = pickAs('pick')
  427. const drill = pickAs('drill')
  428. it('settles files and directories as atomic icon labels; drill keeps directory completion open', async () => {
  429. const { source } = await bench()
  430. const [directory, file] = await source.candidates(session, request(''))
  431. expect(directory?.drill).toBe(true)
  432. expect(file?.drill).toBeUndefined()
  433. expect(pick(source, directory!)).toEqual({
  434. insert: {
  435. source: 'reference',
  436. ref: '@src/',
  437. label: 'src/',
  438. appearance: 'folder',
  439. clipboardText: '@src/',
  440. },
  441. })
  442. expect(drill(source, directory!)).toEqual({ text: '@src/', continue: true })
  443. expect(pick(source, file!)).toEqual({
  444. insert: {
  445. source: 'reference',
  446. ref: '@"docs/a b.md"',
  447. label: 'a b.md',
  448. appearance: 'file',
  449. clipboardText: '@"docs/a b.md"',
  450. },
  451. })
  452. const [quotedDirectory] = await source.candidates(session, request('', { quoted: true }))
  453. expect(drill(source, quotedDirectory!)).toEqual({ text: '@"src/', continue: true })
  454. })
  455. it('inserts sessions as atomic chips whose clipboard and model forms are canonical mentions', async () => {
  456. const { source } = await bench()
  457. const candidates = await source.candidates(session, request(''))
  458. const candidate = candidates.find(item => item.name === 'Research')!
  459. const mention = '@[Research](dsh-session:InNvdXJjZSI)'
  460. expect(pick(source, candidate)).toEqual({
  461. insert: {
  462. source: 'reference',
  463. ref: mention,
  464. label: 'Research',
  465. appearance: 'session',
  466. clipboardText: mention,
  467. },
  468. })
  469. expect(source.codec?.clipboardText(mention)).toBe(mention)
  470. await expect(source.codec?.serialize(mention, new AbortController().signal)).resolves.toBe(mention)
  471. })
  472. it('ignores candidates that do not carry a source-owned value', async () => {
  473. const { source } = await bench()
  474. expect(pick(source, { name: 'foreign candidate' })).toBeUndefined()
  475. })
  476. })
  477. describe('reference preview', () => {
  478. it('opens plain and quoted file references without treating folders or sessions as files', async () => {
  479. const { ctx, source, fiber } = await bench()
  480. const openResource = vi.spyOn(ctx.sidebarRight, 'openResource')
  481. expect(source.openReference?.(session, { ref: '@notes/readme.md', appearance: 'file' })).toBe(true)
  482. expect(source.openReference?.(session, { ref: '@"docs/a b.md"', appearance: 'file' })).toBe(true)
  483. expect(openResource).toHaveBeenNthCalledWith(1, 'dsh-resource://file/session/target/notes/readme.md')
  484. expect(openResource).toHaveBeenNthCalledWith(2, 'dsh-resource://file/session/target/docs/a%20b.md')
  485. expect(source.openReference?.(session, { ref: '@docs/', appearance: 'folder' })).toBe(false)
  486. expect(source.openReference?.(session, { ref: '@[Research](dsh-session:abc)', appearance: 'session' })).toBe(false)
  487. expect(openResource).toHaveBeenCalledTimes(2)
  488. await fiber.dispose()
  489. })
  490. })