clickable-links-gallery.e2e.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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/start', { turn: 1, step: 2 })
  239. session.append('assistant/message', {
  240. stream: [],
  241. turn: 1,
  242. step: 2,
  243. message: createAssistantMessage({
  244. content: text([
  245. '## Link gallery',
  246. '',
  247. `Docs: [style guide](${GUIDE_URL}) and \`${API_URL}\`; see [the release notes][rel], `
  248. + `contact [the maintainer](${MAILTO_URL}), and check the fine print[^1].`,
  249. '',
  250. `Inert contrasts: \`curl ${API_URL}\`, \`javascript:alert(1)\`, and \`pnpm run build\`.`,
  251. '',
  252. 'Wrote `report.html` plus two `style.css` copies; `notes.md` untouched.',
  253. '',
  254. `![Token preview](${imageUrl})`,
  255. '',
  256. '```css',
  257. '--inline-code: #F5F5F5;',
  258. '```',
  259. '',
  260. DONE,
  261. '',
  262. `[rel]: ${RELEASES_URL}`,
  263. '',
  264. '[^1]: Footnote references stay inert superscripts.',
  265. ].join('\n')),
  266. source: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  267. }),
  268. }, { surfaceOp: 'append' })
  269. session.append('step/end', { turn: 1, step: 2 })
  270. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  271. return [
  272. JSON.stringify({
  273. type: 'session',
  274. version: SESSION_FORMAT_VERSION,
  275. id: '{{sessionId}}',
  276. createdAt: 0,
  277. cwd: '{{cwd}}',
  278. isSeeded: false,
  279. delegationDepth: 0,
  280. }),
  281. ...session.snapshotEvents().map(event => JSON.stringify({
  282. ...event,
  283. time: eventTimeOrigin + event.seq * 1_000,
  284. })),
  285. '',
  286. ].join('\n')
  287. }
  288. describe('web e2e: clickable links gallery', () => {
  289. let scaffold: WebScaffold
  290. let browser: Browser
  291. let page: Page
  292. let imageUrl: string
  293. let tripwire: ReturnType<typeof watchConsole>
  294. beforeAll(async () => {
  295. scaffold = await launchWebScaffold({ extraOverlayPath: OVERLAY })
  296. imageUrl = new URL('/favicon.svg', scaffold.baseUrl).toString()
  297. await seedSession(scaffold, galleryFixture(imageUrl), SEED_ID)
  298. browser = await chromium.launch()
  299. page = await newEnglishPage(browser)
  300. tripwire = watchConsole(page)
  301. await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
  302. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  303. }, 120_000)
  304. afterAll(async () => {
  305. await browser?.close()
  306. await scaffold?.close()
  307. })
  308. it.skipIf(MODE === 'record')('renders every clickable link and artifact form of the settled turn', async () => {
  309. onTestFailed(() => saveFailureShot(page, 'web-e2e-clickable-links-gallery'))
  310. const groupRow = page.locator('[role="treeitem"]').first()
  311. await groupRow.waitFor({ timeout: 15_000 })
  312. await groupRow.click()
  313. const sessionRow = page.locator('[role="treeitem"]').nth(1)
  314. await sessionRow.waitFor({ timeout: 10_000 })
  315. await sessionRow.click()
  316. await expect.poll(() => page.getByText(DONE, { exact: true }).count(), { timeout: 15_000 }).toBe(1)
  317. // Markdown prose: plain, reference-style, and mailto links plus the
  318. // inline-code URL are anchors; the URL-with-flags code, the javascript:
  319. // destination, and plain command code stay inert.
  320. const markdown = page.locator('[class*="markdown"]')
  321. await expect.poll(() => markdown.locator(`a[href="${GUIDE_URL}"]`).count(), { timeout: 10_000 }).toBe(1)
  322. expect(await markdown.locator(`a[href="${RELEASES_URL}"]`).count()).toBe(1)
  323. expect(await markdown.locator(`a[href="${MAILTO_URL}"]`).count()).toBe(1)
  324. const inlineCodeLink = markdown.locator(`code a[href="${API_URL}"]`)
  325. expect(await inlineCodeLink.count()).toBe(1)
  326. expect(await inlineCodeLink.getAttribute('target')).toBe('_blank')
  327. expect(await page.getByText(`curl ${API_URL}`, { exact: true }).locator('a').count()).toBe(0)
  328. expect(await page.getByText('javascript:alert(1)', { exact: true }).locator('a').count()).toBe(0)
  329. expect(await markdown.locator(`img[src="${imageUrl}"]`).count()).toBe(1)
  330. // Produced files: one unique-basename mention links; the shared basename
  331. // and the unwritten file stay inert code. Seven produced paths overflow
  332. // the chip row; the failed write joins neither surface.
  333. const mentions = markdown.locator('code button')
  334. expect(await mentions.count()).toBe(1)
  335. expect(await mentions.first().getAttribute('title')).toBe('site/report.html')
  336. expect(await page.getByText('Produced', { exact: true }).count()).toBe(1)
  337. expect(await page.locator('[class*="centerCol"] button[aria-label^="Open "]').count()).toBeGreaterThanOrEqual(5)
  338. expect(await page.locator('button[aria-label="Open c/broken.css"]').count()).toBe(0)
  339. // Tool rows: five writes, the edit, and the read carry the dotted file
  340. // link; the failed write row does not, and neither does str_replace_editor
  341. // — TOOL_VARIANTS has no entry for it, so it falls to the generic row with
  342. // no openable path even though its create still joins the produced chips.
  343. expect(await page.locator('button[class*="fileLink"]').count()).toBe(7)
  344. // Expanded cards. The turn-process group collapses a multi-call turn, so
  345. // it opens first. Rows expand via a right-edge click: the row center can
  346. // land on the nested fileLink button, which would hand the path to the
  347. // Host's opener.
  348. await page.getByRole('button', { name: `${String(CALLS.length)} tool calls` }).click()
  349. for (const row of [
  350. /^Search clickable link styles/,
  351. /^Fetch /,
  352. /^Read docs\/guide\.md/,
  353. /^Edit src\/tokens\.css/,
  354. /^Grep linkColor/,
  355. /Run the lint gate|pnpm run lint/,
  356. ]) {
  357. const toggle = page.getByRole('button', { name: row }).first()
  358. await toggle.waitFor({ timeout: 10_000 })
  359. const box = await toggle.boundingBox()
  360. await toggle.click(box === null ? {} : { position: { x: box.width - 8, y: box.height / 2 } })
  361. }
  362. // Both generic rows (the unclassified str_replace_editor and the unknown
  363. // design_tokens_sync) expand to their IN/OUT surfaces.
  364. const genericRows = page.getByRole('button', { name: /^Tool call/ })
  365. for (let index = 0; index < await genericRows.count(); index += 1) {
  366. const toggle = genericRows.nth(index)
  367. const box = await toggle.boundingBox()
  368. await toggle.click(box === null ? {} : { position: { x: box.width - 8, y: box.height / 2 } })
  369. }
  370. const sourceLink = page.locator(`a[href="${SOURCE_URL}"]`)
  371. await expect.poll(() => sourceLink.count(), { timeout: 10_000 }).toBe(1)
  372. expect(await page.locator('a[href^="ftp:"]').count()).toBe(0)
  373. expect(await page.locator(`a[href="${FETCH_URL}"]`).count()).toBe(1)
  374. expect(await page.locator(`a[href="${GUIDE_URL}"]`).count()).toBe(2)
  375. const snapshot = (await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd))
  376. .split(SEED_ID).join('{{seededId}}')
  377. .split(imageUrl).join('{{imageUrl}}')
  378. await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE)
  379. expect(tripwire.pageErrors).toEqual([])
  380. expect(tripwire.warnings).toEqual([])
  381. await assertFixtureInventory(SNAPSHOT_DIR, ['ui.expected.md'])
  382. // The link language itself — ARIA records none of it, so pin the computed
  383. // styles: link-blue 500-weight text, no underline at rest, dotted underline
  384. // on hover, and a leading currentColor glyph. Light theme, so the link
  385. // alias resolves to deepseek-500.
  386. const LINK_BLUE = 'rgb(65, 118, 230)'
  387. const styleOf = async (target: ReturnType<Page['locator']>, property: string): Promise<string> =>
  388. target.evaluate((el, p) => getComputedStyle(el).getPropertyValue(p), property)
  389. const guideLink = markdown.locator(`a[href="${GUIDE_URL}"]`).first()
  390. const chip = page.locator('button[aria-label="Open site/report.html"]').first()
  391. for (const [name, link] of [
  392. ['markdown anchor', guideLink],
  393. ['file mention', mentions.first()],
  394. ['search source', sourceLink.first()],
  395. ['fetch url', page.locator(`a[href="${FETCH_URL}"]`).first()],
  396. ['produced chip', chip],
  397. ] as const) {
  398. expect.soft(await styleOf(link, 'color'), `${name} color`).toBe(LINK_BLUE)
  399. expect.soft(await styleOf(link, 'font-weight'), `${name} weight`).toBe('500')
  400. expect.soft(await styleOf(link, 'text-decoration-line'), `${name} at rest`).toBe('none')
  401. expect.soft(await link.locator('svg').count(), `${name} glyph`).toBe(1)
  402. }
  403. await guideLink.hover()
  404. expect(await styleOf(guideLink, 'text-decoration-line')).toBe('underline')
  405. expect(await styleOf(guideLink, 'text-decoration-style')).toBe('dotted')
  406. expect(await styleOf(guideLink, 'text-underline-offset')).toBe('3px')
  407. await chip.hover()
  408. expect(await styleOf(chip, 'text-decoration-style')).toBe('dotted')
  409. expect(await styleOf(chip, 'background-color')).toBe('rgba(0, 0, 0, 0)')
  410. // The excluded grey affordance: tool-row file links keep their own color.
  411. expect(await styleOf(page.locator('button[class*="fileLink"]').first(), 'color')).not.toBe(LINK_BLUE)
  412. }, 90_000)
  413. })