browser-plugin.client.spec.ts 18 KB

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