clickable-links-gallery.e2e.ts 18 KB

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