browser-plugin.client.spec.ts 18 KB

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