clickable-links-gallery.e2e.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. // Web e2e gallery: every clickable link and artifact form the chat renders,
  2. // in one settled keyless turn — the regression anchor for unifying link
  3. // styles. One fixture turn produces:
  4. // - prose: Markdown link, reference-style link, mailto link, inline-code URL,
  5. // produced-file mention, plus inert contrasts (ambiguous basename, unwritten
  6. // file, command code, URL-with-flags code, javascript: destination,
  7. // footnote superscript, remote image, fenced code block with its copy chrome)
  8. // - artifacts: seven produced files (chips overflow into the "+N" remainder
  9. // and the show-in-folder affordance) with a failed write excluded
  10. // - tool rows: write/edit/str_replace_editor/read file links, a failure row
  11. // without one, and — expanded — the web-search source links (one non-http
  12. // source stays inert) and answer link, the web-fetch URL, the read card's
  13. // inert path label and fold toggle, the diff card's inert path header, the
  14. // grep card's fold-only file headers, a failing bash card's exit status, and
  15. // a generic tool card's IN/OUT surfaces.
  16. // Image thumbnails and subagent rows stay out: the first needs real attachment
  17. // bytes (image-display.expected.e2e.ts owns that route) and the second needs a
  18. // child session (subagent-conversation owns it).
  19. import { fileURLToPath } from 'node:url'
  20. import type { Browser, Page } from 'playwright'
  21. import { chromium } from 'playwright'
  22. import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
  23. import { ToolCallId, createAssistantMessage, createToolResultMessage, createUserMessage } from '@deepseek-ai/dsh-llm'
  24. import { SESSION_FORMAT_VERSION, Session, SessionId } from '@deepseek-ai/dsh-session'
  25. import type { JsonValue } from '@deepseek-ai/dsh-util-values'
  26. import type {} from '@deepseek-ai/dsh-session-title'
  27. import {
  28. assertFixtureInventory,
  29. captureStableAria,
  30. compareOrRefreshGolden,
  31. launchWebScaffold,
  32. seedSession,
  33. watchConsole,
  34. webSnapshotMode,
  35. type WebScaffold,
  36. } from './scaffold.ts'
  37. import { newEnglishPage, saveFailureShot } from './support.ts'
  38. const SNAPSHOT_DIR = fileURLToPath(new URL('./expected/clickable-links-gallery', import.meta.url))
  39. const UI_EXPECTED = fileURLToPath(new URL('./expected/clickable-links-gallery/ui.expected.md', import.meta.url))
  40. // The golden holds the show-in-folder affordance; pin the native-opener
  41. // capability so headless Linux CI and desktop developer hosts expose the same
  42. // UI branch (same pin as produced-files.e2e.ts, whose overlay this shares).
  43. const OVERLAY = fileURLToPath(new URL('./produced-files.overlay.yml', import.meta.url))
  44. const MODE = webSnapshotMode()
  45. const SEED_ID = 'clickable-links-gallery-web-e2e'
  46. const DONE = 'LINK_GALLERY_DONE'
  47. // Seeded events and browser time share a day independently of host timezones.
  48. const GALLERY_TIME = Date.UTC(2026, 0, 15, 12)
  49. const GUIDE_URL = 'https://docs.example.test/guide'
  50. const API_URL = 'https://docs.example.test/api'
  51. const RELEASES_URL = 'https://docs.example.test/releases'
  52. const MAILTO_URL = 'mailto:owner@example.test'
  53. const SOURCE_URL = 'https://docs.example.test/links'
  54. const INERT_SOURCE_URL = 'ftp://mirror.example.test/spec'
  55. const FETCH_URL = 'https://docs.example.test/tokens'
  56. /** One-part text content for a built message. */
  57. function text(value: string): { type: 'text'; text: string }[] {
  58. return [{ type: 'text', text: value }]
  59. }
  60. /** A settled root tool call: its call event arguments plus result content/meta. */
  61. interface GalleryCall {
  62. name: string
  63. args: Record<string, unknown>
  64. result: string
  65. meta?: JsonValue
  66. isError?: true
  67. }
  68. /** The five successful writes; docs/press.md and src/tokens.css join via other tools. */
  69. const WRITES = ['site/report.html', 'a/style.css', 'b/style.css', 'site/index.html', 'site/app.js']
  70. /** The gallery turn's tool calls, in surface order. */
  71. const CALLS: GalleryCall[] = [
  72. ...WRITES.map(path => ({
  73. name: 'write',
  74. args: { file_path: path, content: `content of ${path}\n` },
  75. result: `Created ${path}`,
  76. })),
  77. {
  78. name: 'edit',
  79. args: {
  80. file_path: 'src/tokens.css',
  81. old_string: '--inline-code: #EBEEF2;',
  82. new_string: '--inline-code: #F5F5F5;',
  83. },
  84. result: 'Edited src/tokens.css',
  85. meta: {
  86. diffs: [{
  87. path: 'src/tokens.css',
  88. oldText: '--inline-code: #EBEEF2;\n',
  89. newText: '--inline-code: #F5F5F5;\n',
  90. }],
  91. },
  92. },
  93. {
  94. name: 'str_replace_editor',
  95. args: { command: 'create', path: 'docs/press.md', file_text: '# Press kit\n' },
  96. result: 'Created docs/press.md',
  97. meta: { diffs: [{ path: 'docs/press.md', oldText: null, newText: '# Press kit\n' }] },
  98. },
  99. {
  100. name: 'write',
  101. args: { file_path: 'c/broken.css', content: 'nope\n' },
  102. result: 'permission denied: c/broken.css',
  103. isError: true,
  104. },
  105. {
  106. name: 'read',
  107. args: { file_path: 'docs/guide.md' },
  108. // The read card validates the model-facing envelope, not just the meta:
  109. // without <path>/<type>/<content> the row falls back to the generic card.
  110. result: [
  111. '<path>docs/guide.md</path>',
  112. '<type>file</type>',
  113. '<content>',
  114. ...Array.from({ length: 12 }, (_, index) =>
  115. index === 0 ? '# Link style guide' : `guide line ${String(index + 1)}`),
  116. '</content>',
  117. ].join('\n'),
  118. meta: {
  119. path: 'docs/guide.md',
  120. offset: 1,
  121. lines: Array.from({ length: 12 }, (_, index) => ({
  122. number: index + 1,
  123. text: index === 0 ? '# Link style guide' : `guide line ${String(index + 1)}`,
  124. })),
  125. totalLines: 12,
  126. },
  127. },
  128. {
  129. name: 'grep',
  130. args: { pattern: 'linkColor' },
  131. result: 'nine matches across three files',
  132. meta: {
  133. shape: 'matches',
  134. files: ['a/style.css', 'b/style.css', 'src/tokens.css'].map(path => ({
  135. path,
  136. matches: [3, 7, 11].map(lineNumber => ({ lineNumber, line: ' color: var(--linkColor);' })),
  137. })),
  138. truncated: false,
  139. total: 9,
  140. },
  141. },
  142. {
  143. name: 'glob',
  144. args: { pattern: '**/*.css' },
  145. result: 'a/style.css\nb/style.css\nsrc/tokens.css',
  146. meta: { shape: 'paths', paths: ['a/style.css', 'b/style.css', 'src/tokens.css'], truncated: false, total: 3 },
  147. },
  148. {
  149. name: 'bash',
  150. args: { command: 'ls site', description: 'List the built site' },
  151. result: 'report.html\nindex.html\napp.js\n',
  152. },
  153. {
  154. name: 'bash',
  155. args: { command: 'pnpm run lint', description: 'Run the lint gate', workdir: 'site' },
  156. result: 'style.css: unexpected hex literal\n[exit code: 1]',
  157. },
  158. {
  159. name: 'web_search',
  160. args: { queries: ['clickable link styles', 'produced files ui'] },
  161. result: 'Two sources found.',
  162. meta: {
  163. truncated: false,
  164. answer: `Unify links per [the guide](${GUIDE_URL}).`,
  165. sources: [
  166. { url: SOURCE_URL, title: 'Link styles reference', snippet: 'One cursor token, one focus ring.' },
  167. { url: INERT_SOURCE_URL, title: 'Mirror spec (non-http)', snippet: 'A non-http source renders inert.' },
  168. ],
  169. },
  170. },
  171. {
  172. name: 'web_fetch',
  173. args: { url: FETCH_URL },
  174. result: 'Design token reference page.',
  175. meta: { url: FETCH_URL, statusCode: 200, truncated: false },
  176. },
  177. {
  178. name: 'design_tokens_sync',
  179. args: { source: 'design-platform.css', dryRun: false },
  180. result: '{"synced":true,"tokens":12}',
  181. },
  182. ]
  183. /**
  184. * Build the settled gallery turn: every call above plus a link-dense closing prose.
  185. * @param imageUrl - scaffold-hosted image the prose embeds (kept same-origin so
  186. * the tripwire stays clean; the varying origin is tokenized in the golden).
  187. */
  188. function galleryFixture(imageUrl: string): string {
  189. const session = Session.create(SessionId('clickable-links-gallery-source'))
  190. session.append('turn/start', { turn: 1 })
  191. const user = session.append('user/message', createUserMessage({
  192. content: text('Assemble the link gallery: write the report and styles, inspect the sources, and summarize.'),
  193. source: { kind: 'user' },
  194. }), { surfaceOp: 'append' })
  195. session.append('session/title', {
  196. title: 'Clickable links gallery',
  197. messageSeqs: [user.seq],
  198. source: { kind: 'fallback' },
  199. })
  200. session.append('step/start', { turn: 1, step: 1 })
  201. const calls = CALLS.map((call, index) => ({
  202. ...call,
  203. callId: ToolCallId(`gallery-${String(index)}`),
  204. argsJson: JSON.stringify(call.args),
  205. }))
  206. session.append('assistant/message', {
  207. stream: [],
  208. turn: 1,
  209. step: 1,
  210. message: createAssistantMessage({
  211. content: calls.map(call => ({
  212. type: 'tool-call' as const,
  213. id: call.callId,
  214. name: call.name,
  215. arguments: call.argsJson,
  216. })),
  217. source: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  218. }),
  219. }, { surfaceOp: 'append' })
  220. for (const call of calls) {
  221. const source = session.append('tool/call', {
  222. turn: 1,
  223. step: 1,
  224. callId: call.callId,
  225. name: call.name,
  226. arguments: call.argsJson,
  227. })
  228. session.append('tool/result', {
  229. turn: 1,
  230. step: 1,
  231. message: createToolResultMessage({
  232. callId: call.callId,
  233. content: text(call.result),
  234. isError: call.isError === true,
  235. }),
  236. ...(call.meta === undefined ? {} : { meta: call.meta }),
  237. }, { surfaceOp: 'append', sourceEventSeqs: [source.seq] })
  238. }
  239. session.append('step/end', { turn: 1, step: 1 })
  240. session.append('step/start', { turn: 1, step: 2 })
  241. session.append('assistant/message', {
  242. stream: [],
  243. turn: 1,
  244. step: 2,
  245. message: createAssistantMessage({
  246. content: text([
  247. '## Link gallery',
  248. '',
  249. `Docs: [style guide](${GUIDE_URL}) and \`${API_URL}\`; see [the release notes][rel], `
  250. + `contact [the maintainer](${MAILTO_URL}), and check the fine print[^1].`,
  251. '',
  252. `Inert contrasts: \`curl ${API_URL}\`, \`javascript:alert(1)\`, and \`pnpm run build\`.`,
  253. '',
  254. 'Wrote `report.html` plus two `style.css` copies; `notes.md` untouched.',
  255. '',
  256. `![Token preview](${imageUrl})`,
  257. '',
  258. '```css',
  259. '--inline-code: #F5F5F5;',
  260. '```',
  261. '',
  262. DONE,
  263. '',
  264. `[rel]: ${RELEASES_URL}`,
  265. '',
  266. '[^1]: Footnote references stay inert superscripts.',
  267. ].join('\n')),
  268. source: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  269. }),
  270. }, { surfaceOp: 'append' })
  271. session.append('step/end', { turn: 1, step: 2 })
  272. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  273. return [
  274. JSON.stringify({
  275. type: 'session',
  276. version: SESSION_FORMAT_VERSION,
  277. id: '{{sessionId}}',
  278. createdAt: 0,
  279. cwd: '{{cwd}}',
  280. isSeeded: false,
  281. delegationDepth: 0,
  282. }),
  283. ...session.snapshotEvents().map(event => JSON.stringify({
  284. ...event,
  285. time: GALLERY_TIME + event.seq * 1_000,
  286. })),
  287. '',
  288. ].join('\n')
  289. }
  290. describe('web e2e: clickable links gallery', () => {
  291. let scaffold: WebScaffold
  292. let browser: Browser
  293. let page: Page
  294. let imageUrl: string
  295. let tripwire: ReturnType<typeof watchConsole>
  296. beforeAll(async () => {
  297. scaffold = await launchWebScaffold({ extraOverlayPath: OVERLAY })
  298. imageUrl = new URL('/favicon.svg', scaffold.baseUrl).toString()
  299. await seedSession(scaffold, galleryFixture(imageUrl), SEED_ID, undefined, { createdAt: GALLERY_TIME })
  300. browser = await chromium.launch()
  301. page = await newEnglishPage(browser)
  302. await page.clock.setFixedTime(GALLERY_TIME + 60_000)
  303. tripwire = watchConsole(page)
  304. await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
  305. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  306. }, 120_000)
  307. afterAll(async () => {
  308. await browser?.close()
  309. await scaffold?.close()
  310. })
  311. it.skipIf(MODE === 'record')('renders every clickable link and artifact form of the settled turn', async () => {
  312. onTestFailed(() => saveFailureShot(page, 'web-e2e-clickable-links-gallery'))
  313. const groupRow = page.locator('[role="treeitem"]').first()
  314. await groupRow.waitFor({ timeout: 15_000 })
  315. await groupRow.click()
  316. const sessionRow = page.locator('[role="treeitem"]').nth(1)
  317. await sessionRow.waitFor({ timeout: 10_000 })
  318. await sessionRow.click()
  319. await expect.poll(() => page.getByText(DONE, { exact: true }).count(), { timeout: 15_000 }).toBe(1)
  320. // Markdown prose: plain, reference-style, and mailto links plus the
  321. // inline-code URL are anchors; the URL-with-flags code, the javascript:
  322. // destination, and plain command code stay inert.
  323. const markdown = page.locator('[class*="markdown"]')
  324. await expect.poll(() => markdown.locator(`a[href="${GUIDE_URL}"]`).count(), { timeout: 10_000 }).toBe(1)
  325. expect(await markdown.locator(`a[href="${RELEASES_URL}"]`).count()).toBe(1)
  326. expect(await markdown.locator(`a[href="${MAILTO_URL}"]`).count()).toBe(1)
  327. const inlineCodeLink = markdown.locator(`code a[href="${API_URL}"]`)
  328. expect(await inlineCodeLink.count()).toBe(1)
  329. expect(await inlineCodeLink.getAttribute('target')).toBe('_blank')
  330. expect(await page.getByText(`curl ${API_URL}`, { exact: true }).locator('a').count()).toBe(0)
  331. expect(await page.getByText('javascript:alert(1)', { exact: true }).locator('a').count()).toBe(0)
  332. expect(await markdown.locator(`img[src="${imageUrl}"]`).count()).toBe(1)
  333. // Produced files: one unique-basename mention links; the shared basename
  334. // and the unwritten file stay inert code. Seven produced paths overflow
  335. // the chip row; the failed write joins neither surface.
  336. const mentions = markdown.locator('code button')
  337. expect(await mentions.count()).toBe(1)
  338. expect(await mentions.first().getAttribute('title')).toBe('site/report.html')
  339. expect(await page.getByText('Files changed', { exact: true }).count()).toBe(1)
  340. expect(await page.locator('[class*="centerCol"] button[aria-label^="Open "]').count()).toBeGreaterThanOrEqual(5)
  341. expect(await page.locator('button[aria-label="Open c/broken.css"]').count()).toBe(0)
  342. // Tool rows: five writes, the edit, and the read carry the dotted file
  343. // link; the failed write row does not, and neither does str_replace_editor
  344. // — TOOL_VARIANTS has no entry for it, so it falls to the generic row with
  345. // no openable path even though its create still joins the produced chips.
  346. expect(await page.locator('button[class*="fileLink"]').count()).toBe(7)
  347. // Expanded cards. The turn-process group collapses a multi-call turn, so
  348. // it opens first. Rows expand via a right-edge click: the row center can
  349. // land on the nested fileLink button, which would hand the path to the
  350. // Host's opener.
  351. await page.getByRole('button', { name: `${String(CALLS.length)} tool calls` }).click()
  352. for (const row of [
  353. /^Search clickable link styles/,
  354. /^Fetch /,
  355. /^Read docs\/guide\.md/,
  356. /^Edit src\/tokens\.css/,
  357. /^Grep linkColor/,
  358. /Run the lint gate|pnpm run lint/,
  359. ]) {
  360. const toggle = page.getByRole('button', { name: row }).first()
  361. await toggle.waitFor({ timeout: 10_000 })
  362. const box = await toggle.boundingBox()
  363. await toggle.click(box === null ? {} : { position: { x: box.width - 8, y: box.height / 2 } })
  364. }
  365. // Both generic rows (the unclassified str_replace_editor and the unknown
  366. // design_tokens_sync) expand to their IN/OUT surfaces.
  367. const genericRows = page.getByRole('button', { name: /^Tool call/ })
  368. for (let index = 0; index < await genericRows.count(); index += 1) {
  369. const toggle = genericRows.nth(index)
  370. const box = await toggle.boundingBox()
  371. await toggle.click(box === null ? {} : { position: { x: box.width - 8, y: box.height / 2 } })
  372. }
  373. const sourceLink = page.locator(`a[href="${SOURCE_URL}"]`)
  374. await expect.poll(() => sourceLink.count(), { timeout: 10_000 }).toBe(1)
  375. expect(await page.locator('a[href^="ftp:"]').count()).toBe(0)
  376. expect(await page.locator(`a[href="${FETCH_URL}"]`).count()).toBe(1)
  377. expect(await page.locator(`a[href="${GUIDE_URL}"]`).count()).toBe(2)
  378. const snapshot = (await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd))
  379. .split(SEED_ID).join('{{seededId}}')
  380. .split(imageUrl).join('{{imageUrl}}')
  381. await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE)
  382. expect(tripwire.pageErrors).toEqual([])
  383. expect(tripwire.warnings).toEqual([])
  384. await assertFixtureInventory(SNAPSHOT_DIR, ['ui.expected.md'])
  385. // The link language itself — ARIA records none of it, so pin the computed
  386. // styles: link-blue 500-weight text, no underline at rest, dotted underline
  387. // on hover, and a leading currentColor glyph. Light theme, so the link
  388. // alias resolves to deepseek-500.
  389. const LINK_BLUE = 'rgb(65, 118, 230)'
  390. const styleOf = async (target: ReturnType<Page['locator']>, property: string): Promise<string> =>
  391. target.evaluate((el, p) => getComputedStyle(el).getPropertyValue(p), property)
  392. const guideLink = markdown.locator(`a[href="${GUIDE_URL}"]`).first()
  393. const chip = page.locator('button[aria-label="Open site/report.html"]').first()
  394. for (const [name, link] of [
  395. ['markdown anchor', guideLink],
  396. ['file mention', mentions.first()],
  397. ['search source', sourceLink.first()],
  398. ['fetch url', page.locator(`a[href="${FETCH_URL}"]`).first()],
  399. ['produced chip', chip],
  400. ] as const) {
  401. expect.soft(await styleOf(link, 'color'), `${name} color`).toBe(LINK_BLUE)
  402. expect.soft(await styleOf(link, 'font-weight'), `${name} weight`).toBe('500')
  403. expect.soft(await styleOf(link, 'text-decoration-line'), `${name} at rest`).toBe('none')
  404. expect.soft(await link.locator('svg').count(), `${name} glyph`).toBe(1)
  405. }
  406. await guideLink.hover()
  407. expect(await styleOf(guideLink, 'text-decoration-line')).toBe('underline')
  408. expect(await styleOf(guideLink, 'text-decoration-style')).toBe('dotted')
  409. expect(await styleOf(guideLink, 'text-underline-offset')).toBe('3px')
  410. await chip.hover()
  411. expect(await styleOf(chip, 'text-decoration-style')).toBe('dotted')
  412. expect(await styleOf(chip, 'background-color')).toBe('rgba(0, 0, 0, 0)')
  413. // The excluded grey affordance: tool-row file links keep their own color.
  414. expect(await styleOf(page.locator('button[class*="fileLink"]').first(), 'color')).not.toBe(LINK_BLUE)
  415. }, 90_000)
  416. })