Repository navigation
Expand file tree
/
Copy pathtest-navigation-e2e.ts
More file actions
1792 lines (1777 loc) · 78.1 KB
/
Copy pathtest-navigation-e2e.ts
File metadata and controls
1792 lines (1777 loc) · 78.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { mkdir, readFile, writeFile } from 'node:fs/promises'
import { dirname, join } from 'node:path'
import {
type Browser,
type BrowserContext,
chromium,
expect,
type Locator,
type Page,
type Request,
type Video,
webkit,
} from '@playwright/test'
import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import { sleep } from '@sim/utils/helpers'
import { toRecord } from '@sim/utils/object'
const logger = createLogger('DocsNavigationE2E', { logLevel: 'INFO' })
const origin = process.env.DOCS_E2E_BASE_URL
const reportSetting = process.env.DOCS_NAVIGATION_REPORT_PATH
if (!origin || !reportSetting)
throw new Error('DOCS_E2E_BASE_URL and DOCS_NAVIGATION_REPORT_PATH are required')
const reportPath: string = reportSetting
const target = new URL(origin)
if (!['localhost', '127.0.0.1', '[::1]'].includes(target.hostname))
throw new Error('Only a loopback docs server may be tested')
const directory = dirname(reportPath)
const canonicalOrigin = new URL(process.env.NEXT_PUBLIC_DOCS_URL ?? 'https://docs.sim.ai').origin
const engine = process.env.DOCS_NAVIGATION_BROWSER ?? 'chromium'
if (engine !== 'chromium' && engine !== 'webkit')
throw new Error('DOCS_NAVIGATION_BROWSER must be chromium or webkit')
const results: Array<{
name: string
status: 'passed' | 'failed' | 'unavailable'
durationMs: number
error?: string
}> = []
await mkdir(directory, { recursive: true })
async function check(name: string, action: () => Promise<void>, unavailable?: string) {
if (process.env.DOCS_NAVIGATION_FILTER && !name.includes(process.env.DOCS_NAVIGATION_FILTER))
return
logger.info('Running', { name })
const started = performance.now()
if (unavailable) {
results.push({ name, status: 'unavailable', durationMs: 0, error: unavailable })
return
}
try {
await action()
results.push({ name, status: 'passed', durationMs: Math.round(performance.now() - started) })
logger.info('Passed', { name })
} catch (error) {
results.push({
name,
status: 'failed',
durationMs: Math.round(performance.now() - started),
error: getErrorMessage(error),
})
logger.error('Failed', { name, error: getErrorMessage(error) })
}
await writeFile(
reportPath,
`${JSON.stringify({ origin: target.origin, engine, results }, null, 2)}\n`
)
}
async function selectRequestLanguage(page: Page, name: string | RegExp): Promise<Locator> {
const tab = page
.getByRole('tablist', { name: 'Request language', exact: true, includeHidden: true })
.getByRole('tab', { name, exact: true, includeHidden: true })
if (await tab.isVisible()) {
await tab.click()
} else {
await page.getByRole('button', { name: /^Request language:/ }).click()
await page.getByRole('menuitemradio', { name, exact: true }).click()
}
await expect(tab).toHaveAttribute('aria-selected', 'true')
return tab
}
async function open(page: Page, path: string) {
const response = await page.goto(new URL(path, target).href, { waitUntil: 'domcontentloaded' })
expect(response?.ok() || response?.status() === 304).toBe(true)
await expect(page.getByRole('heading', { level: 1 }).first()).toBeVisible()
await page.evaluate(() => document.fonts.ready)
await expect(
page.getByRole('group', { name: 'Color theme' }).last().getByRole('button', { pressed: true })
).toHaveCount(1)
}
async function verifyClientMetadata(page: Page, path: string, title: string) {
const description = (await page.locator('main > div > header > p').textContent())?.trim()
expect(description).toBeTruthy()
await expect(page).toHaveTitle(`${title} | Sim Docs`)
await expect(page.locator('link[rel="canonical"]')).toHaveCount(1)
await expect(page.locator('link[rel="canonical"]')).toHaveAttribute(
'href',
`${canonicalOrigin}${path}`
)
await expect(page.locator('meta[name="description"]')).toHaveCount(1)
await expect(page.locator('meta[name="description"]')).toHaveAttribute(
'content',
description ?? ''
)
await expect(page.locator('link[rel="alternate"][type="text/plain"]')).toHaveAttribute(
'href',
`${canonicalOrigin}/llms.txt`
)
return {
path,
title: await page.title(),
canonical: await page.locator('link[rel="canonical"]').getAttribute('href'),
description,
}
}
async function copyMenu(page: Page) {
const item = page.getByRole('menuitem', {
name: /^(Copy Markdown|Copied|Copy prepared Markdown)$/,
})
if (!(await item.isVisible()))
await page
.getByRole('button', { name: /^(Page actions|Copy page options)$/, exact: true })
.click()
return item
}
async function verifyClipboard(
page: Page,
context: BrowserContext,
path: string,
title: string,
content: string
) {
await context.grantPermissions(['clipboard-read', 'clipboard-write'])
const markdownUrl = new URL(`${path}.md`, target).href
const response = await page.request.get(markdownUrl)
expect(response.ok()).toBe(true)
const markdown = await response.text()
expect(markdown).toContain(`# ${title} (${path})`)
expect(markdown).toContain(content)
await (await copyMenu(page)).click()
await expect(page.getByRole('menuitem', { name: 'Copied', exact: true })).toBeVisible()
await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe(markdown)
for (const failure of [
{ status: 503, body: 'Unavailable' },
{ status: 200, body: ' \n ' },
]) {
await page.route(markdownUrl, (route) => route.fulfill(failure))
await (await copyMenu(page)).click()
await expect(page.getByRole('status').filter({ hasText: 'Could not copy.' })).toBeVisible()
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(markdown)
await expect(page.getByRole('menuitem', { name: 'Copied', exact: true })).toHaveCount(0)
await page.unroute(markdownUrl)
await (await copyMenu(page)).click()
await expect(page.getByRole('menuitem', { name: 'Copied', exact: true })).toBeVisible()
}
await page.keyboard.press('Escape')
}
let browser: Browser | undefined
try {
browser = await (engine === 'webkit' ? webkit : chromium).launch()
const feedbackBrowser = browser
await check('Feedback forwards votes and preserves unchanged retry identity', async () => {
const cert = process.env.DOCS_FEEDBACK_TEST_CERT
const key = process.env.DOCS_FEEDBACK_TEST_KEY
const token = process.env.DOCS_FEEDBACK_WEBHOOK_TOKEN
if (!cert || !key || !token) throw new Error('Feedback HTTPS fixture configuration is required')
const received: Array<{ authorization: string | null; body: Record<string, unknown> }> = []
let accept = false
const intake = Bun.serve({
hostname: '127.0.0.1',
port: 3443,
tls: { cert: await readFile(cert), key: await readFile(key) },
async fetch(request) {
if (received.length >= 8) return new Response(null, { status: 429 })
received.push({
authorization: request.headers.get('authorization'),
body: toRecord(await request.json()),
})
return Response.json(
{ message: accept ? 'Webhook processed' : 'Unavailable' },
{ status: accept ? 200 : 503 }
)
},
})
let context: BrowserContext | undefined
try {
context = await feedbackBrowser.newContext()
const page = await context.newPage()
const started = Date.now()
await open(page, '/introduction')
await page.getByRole('button', { name: 'No, this could be improved', exact: true }).click()
const comment = page.getByLabel('What could be better? (optional)', { exact: true })
await comment.fill(' Explain deployment prerequisites. ')
const send = page.getByRole('button', { name: 'Send feedback', exact: true })
for (let attempt = 0; attempt < 2; attempt++) {
const response = page.waitForResponse(
(response) => new URL(response.url()).pathname === '/api/feedback'
)
await send.click()
expect((await response).status()).toBe(502)
await expect(page.getByRole('main').getByRole('alert')).toContainText(
'Could not send feedback.'
)
await expect(comment).toHaveValue(' Explain deployment prerequisites. ')
await expect(send).toBeEnabled()
}
expect(received).toHaveLength(2)
expect(received[1].body.submission_id).toBe(received[0].body.submission_id)
expect(received[0].body.comment).toBe('Explain deployment prerequisites.')
accept = true
await comment.fill(' Explain deployment permissions. ')
const accepted = page.waitForResponse(
(response) => new URL(response.url()).pathname === '/api/feedback'
)
await send.click()
expect((await accepted).status()).toBe(202)
await expect(
page.getByRole('status').filter({ hasText: 'Thanks for your feedback.' })
).toBeVisible()
expect(received).toHaveLength(3)
expect(received[2].body.submission_id).not.toBe(received[1].body.submission_id)
expect(received[2].body).toMatchObject({
page: '/introduction',
helpful: false,
comment: 'Explain deployment permissions.',
})
await page
.getByRole('navigation', { name: 'Page navigation' })
.getByRole('link', { name: 'Next Getting started' })
.click()
const positive = page.waitForResponse(
(response) => new URL(response.url()).pathname === '/api/feedback'
)
await page.getByRole('button', { name: 'Yes, this was helpful', exact: true }).click()
expect((await positive).status()).toBe(202)
await expect(
page.getByRole('status').filter({ hasText: 'Thanks for your feedback.' })
).toBeVisible()
expect(received).toHaveLength(4)
expect(received[3].body).toMatchObject({
page: '/getting-started',
helpful: true,
comment: '',
})
expect(received[3].body.submission_id).not.toBe(received[2].body.submission_id)
for (const request of received) {
expect(request.authorization).toBe(`Bearer ${token}`)
expect(Object.keys(request.body).sort()).toEqual([
'comment',
'helpful',
'page',
'received_at',
'submission_id',
])
expect(request.body.submission_id).toMatch(/^[0-9a-f-]{36}$/)
expect(typeof request.body.received_at).toBe('string')
const timestamp = Date.parse(String(request.body.received_at))
expect(timestamp).toBeGreaterThanOrEqual(started)
expect(timestamp).toBeLessThanOrEqual(Date.now())
}
} finally {
try {
await context?.close()
} finally {
await intake.stop(true)
}
}
})
const noScript = await browser.newContext({
javaScriptEnabled: false,
viewport: { width: 1440, height: 1000 },
})
try {
for (const scenario of [
{ path: '/getting-started', title: 'Getting started', tabbed: false },
{ path: '/mcp/overview', title: 'Sim MCP', tabbed: true },
{ path: '/api-reference/logs/getLog', title: 'Get log', tabbed: true },
]) {
await check(`JavaScript-disabled reading: ${scenario.path}`, async () => {
const page = await noScript.newPage()
try {
const response = await page.goto(new URL(scenario.path, target).href, {
waitUntil: 'load',
})
expect(response?.ok()).toBe(true)
await expect(
page.getByRole('heading', { level: 1, name: scenario.title, exact: true })
).toBeVisible()
const article = page.locator('main article')
await expect(article).toBeVisible()
expect((await article.innerText()).trim().length).toBeGreaterThan(100)
const panels = page
.getByRole('tabpanel', { includeHidden: true })
.or(page.locator('[id^="response-example-"]'))
const observations = []
for (const panel of await panels.all()) {
observations.push({
id: await panel.getAttribute('id'),
visible: await panel.isVisible(),
contentLength: (await panel.textContent())?.trim().length ?? 0,
})
}
const stem = scenario.path.replaceAll('/', '-')
await writeFile(
join(directory, `no-javascript${stem}.json`),
`${JSON.stringify({ path: scenario.path, javaScriptEnabled: false, panels: observations }, null, 2)}\n`
)
await page.screenshot({ path: join(directory, `no-javascript${stem}.png`) })
if (scenario.tabbed) {
expect(observations.length).toBeGreaterThan(1)
for (const panel of await panels.all()) {
await expect(panel).toBeVisible()
expect((await panel.innerText()).trim().length).toBeGreaterThan(0)
}
} else {
const next = article.getByRole('link', { name: 'Build a research agent', exact: true })
await next.click()
await expect(page).toHaveURL(new URL('/getting-started/research-agent', target).href)
await expect(page.getByRole('heading', { level: 1 }).first()).toBeVisible()
}
const disclosure = page
.locator('main details:not([open])')
.filter({ visible: true })
.first()
if (await disclosure.count()) {
const element = await disclosure.elementHandle()
if (!element) throw new Error('Native reference disclosure disappeared')
await disclosure.locator('summary').first().click()
await expect.poll(() => element.getAttribute('open')).toBe('')
}
} finally {
await page.close()
}
})
}
} finally {
await noScript.close()
}
const prefetchContext = await browser.newContext({
viewport: { width: 390, height: 844 },
reducedMotion: 'reduce',
})
try {
await check(
'In-flight intent prefetch transfers a large reference body only once',
async () => {
const page = await prefetchContext.newPage()
const destination = '/integrations/cloudflare'
const requests: Array<{ request: Request; beforeClick: boolean }> = []
const finished = new Set<Request>()
const transfers: Array<{
url: string
beforeClick: boolean
segment?: string
prefetch?: string
status: number
encodedBytes: number
}> = []
let clicked = false
let inFlightAtClick = false
try {
await open(page, '/integrations/apollo')
await page.getByRole('button', { name: 'Menu', exact: true }).click()
const link = page
.getByRole('navigation', { name: 'Documentation sidebar', exact: true })
.getByRole('link', { name: 'Cloudflare', exact: true })
await link.scrollIntoViewIfNeeded()
const session = await prefetchContext.newCDPSession(page)
await session.send('Network.enable')
await session.send('Network.emulateNetworkConditions', {
offline: false,
latency: 150,
downloadThroughput: 100 * 1024,
uploadThroughput: 100 * 1024,
})
const isDestination = (request: Request) =>
new URL(request.url()).pathname === destination && request.headers().rsc === '1'
page.on('request', (request) => {
if (isDestination(request)) requests.push({ request, beforeClick: !clicked })
})
page.on('requestfinished', (request) => finished.add(request))
const prefetched = page.waitForRequest((request) => {
if (!isDestination(request)) return false
const segment = request.headers()['next-router-segment-prefetch']
return !segment || segment.endsWith('/__PAGE__')
})
await link.focus()
const pending = await prefetched
inFlightAtClick = !finished.has(pending)
expect(inFlightAtClick, 'The regression must navigate during a real body transfer').toBe(
true
)
clicked = true
await link.click()
await expect(
page.getByRole('heading', { level: 1, name: 'Cloudflare', exact: true })
).toBeVisible({ timeout: 15000 })
await expect(page).toHaveURL(new URL(destination, target).href)
await expect(page.locator('main article')).not.toBeEmpty()
for (const { request, beforeClick } of requests) {
const response = await request.response()
if (!response)
throw new Error(`Destination request failed: ${request.failure()?.errorText}`)
const failure = await response.finished()
if (failure) throw failure
const sizes = await request.sizes()
transfers.push({
url: request.url(),
beforeClick,
segment: request.headers()['next-router-segment-prefetch'],
prefetch: request.headers()['next-router-prefetch'],
status: response.status(),
encodedBytes: sizes.responseBodySize,
})
expect(response.ok()).toBe(true)
}
const bodies = transfers.filter((transfer) => transfer.encodedBytes > 64 * 1024)
expect(
bodies,
'Navigation must reuse the large in-flight prefetched response'
).toHaveLength(1)
expect(bodies[0]?.beforeClick, 'The large response must originate from intent').toBe(true)
} finally {
await writeFile(
join(directory, 'in-flight-prefetch.json'),
`${JSON.stringify({ source: '/integrations/apollo', destination, latencyMs: 150, bytesPerSecond: 100 * 1024, inFlightAtClick, transfers }, null, 2)}\n`
)
await page.close()
}
},
engine === 'webkit'
? 'Controlled network throttling uses Chromium CDP; Playwright WebKit cannot exercise this transport regression.'
: undefined
)
} finally {
await prefetchContext.close()
}
const sidebarContext = await browser.newContext({
viewport: { width: 1440, height: 640 },
reducedMotion: 'reduce',
})
try {
await check(
'Sidebar keeps its scroll position when opening Logs and navigating back',
async () => {
const page = await sidebarContext.newPage()
await open(page, '/introduction')
await page
.getByRole('heading', { name: /^Models and integrations/ })
.scrollIntoViewIfNeeded()
expect(await page.evaluate(() => window.scrollY)).toBeGreaterThan(0)
const navigation = page.getByRole('navigation', { name: 'Documentation sidebar' })
const logs = navigation.getByRole('link', { name: 'Logs and debugging', exact: true })
await logs.scrollIntoViewIfNeeded()
const scrollPosition = () =>
navigation.evaluate((element) => element.closest('aside')?.scrollTop ?? 0)
const before = await scrollPosition()
expect(before).toBeGreaterThan(0)
await logs.click()
await expect(page).toHaveURL(new URL('/logs-debugging', target).href)
await expect(logs).toHaveAttribute('aria-current', 'page')
await expect.poll(scrollPosition).toBeCloseTo(before, 0)
await expect(logs).toBeInViewport()
await expect(
page.getByRole('heading', { level: 1, name: 'Logs', exact: true })
).toBeInViewport()
const runLogs = navigation.getByRole('link', { name: 'Run logs', exact: true })
await runLogs.scrollIntoViewIfNeeded()
const nestedBefore = await scrollPosition()
await runLogs.click()
await expect(page).toHaveURL(new URL('/logs-debugging/logging', target).href)
await expect(runLogs).toHaveAttribute('aria-current', 'page')
await expect.poll(scrollPosition).toBeCloseTo(nestedBefore, 0)
await expect(runLogs).toBeInViewport()
await page.goBack()
await expect(logs).toHaveAttribute('aria-current', 'page')
await expect.poll(scrollPosition).toBeCloseTo(nestedBefore, 0)
await page.mouse.move(720, 80)
await page.screenshot({
path: join(directory, 'sidebar-preserved.png'),
animations: 'disabled',
})
}
)
} finally {
await sidebarContext.close()
}
const drawerContext = await browser.newContext({ viewport: { width: 390, height: 640 } })
try {
await check(
'Mobile sidebar keeps its scroll position when reopened after navigation',
async () => {
const page = await drawerContext.newPage()
await open(page, '/introduction')
await page.getByRole('button', { name: 'Menu', exact: true }).click()
const navigation = page.getByRole('navigation', { name: 'Documentation sidebar' })
await navigation.getByRole('button', { name: 'Expand Overview', exact: true }).click()
const logs = navigation.getByRole('link', { name: 'Logs and debugging', exact: true })
await logs.scrollIntoViewIfNeeded()
const scrollPosition = () =>
navigation.evaluate((element) => element.parentElement?.scrollTop ?? 0)
const before = await scrollPosition()
expect(before).toBeGreaterThan(0)
await logs.click()
await expect(page).toHaveURL(new URL('/logs-debugging', target).href)
await expect(page.getByRole('dialog')).toBeHidden()
await page.getByRole('button', { name: 'Menu', exact: true }).click()
await expect(logs).toHaveAttribute('aria-current', 'page')
await expect.poll(scrollPosition).toBeCloseTo(before, 0)
await expect(logs).toBeInViewport()
await page.getByRole('button', { name: 'Close navigation' }).click()
await expect(page.getByRole('button', { name: 'Menu', exact: true })).toBeFocused()
}
)
} finally {
await drawerContext.close()
}
for (const { width, dpr } of [
{ width: 390, dpr: 3 },
{ width: 768, dpr: 2 },
{ width: 1440, dpr: 1 },
]) {
const context = await browser.newContext({
viewport: { width, height: 1000 },
deviceScaleFactor: dpr,
})
try {
for (const scene of [
{
path: '/introduction',
image: 'platform.webp',
background: 'san-francisco',
variant: 'hero',
},
{
path: '/files',
image: 'files-markdown.webp',
background: 'architecture',
variant: 'overview',
},
{
path: '/logs-debugging',
image: 'log-trace.webp',
background: 'canyon',
variant: 'detail',
},
{
path: '/search/ask-questions',
image: 'launch-update-draft.webp',
background: 'architecture',
variant: 'result',
},
]) {
await check(`Screenshot framing: ${scene.variant} at ${width}px DPR${dpr}`, async () => {
const page = await context.newPage()
try {
await open(page, scene.path)
const figure = page
.locator('figure')
.filter({ has: page.locator(`img[src*="${scene.image.replace('.webp', '')}"]`) })
const screenshot = figure.getByRole('img')
await figure.scrollIntoViewIfNeeded()
await expect
.poll(() =>
screenshot.evaluate(
(element) =>
element instanceof HTMLImageElement &&
element.complete &&
element.naturalWidth > 0
)
)
.toBe(true)
const background = figure.locator('img[aria-hidden="true"]')
await expect(background).toHaveCount(1)
await expect
.poll(() =>
background.evaluate(
(element) =>
element instanceof HTMLImageElement &&
element.complete &&
element.naturalWidth > 0
)
)
.toBe(true)
await expect(background).toHaveAttribute(
'src',
new RegExp(`${scene.background}(?:\\.[a-zA-Z0-9_-]+)?\\.webp`)
)
const delivery = await screenshot.evaluate((element) => {
if (!(element instanceof HTMLImageElement)) throw new Error('Screenshot is missing')
const source = new URL(element.currentSrc)
return {
currentSrc: element.currentSrc,
srcset: element.srcset,
sizes: element.sizes,
requestedWidth: Number(source.searchParams.get('w')),
renderedWidth: element.getBoundingClientRect().width,
sourceWidth: Number(element.getAttribute('width')),
dpr: devicePixelRatio,
resources: performance
.getEntriesByName(element.currentSrc)
.map((entry) => entry.toJSON()),
}
})
await writeFile(
join(directory, `image-delivery-${scene.variant}-${width}-dpr${dpr}.json`),
`${JSON.stringify(delivery, null, 2)}\n`
)
expect(delivery.requestedWidth).toBeGreaterThan(0)
expect(delivery.requestedWidth).toBeLessThanOrEqual(
Math.max(delivery.sourceWidth, delivery.renderedWidth * dpr * 2)
)
const geometry = await screenshot.evaluate((element) => {
const backdrop = element.closest('figure')?.querySelector('img[aria-hidden="true"]')
const frame = backdrop?.parentElement?.getBoundingClientRect()
const image = element.getBoundingClientRect()
if (!frame) throw new Error('Screenshot has no background frame')
return {
left: (image.left - frame.left) / frame.width,
right: (frame.right - image.right) / frame.width,
top: (image.top - frame.top) / frame.width,
bottom: (frame.bottom - image.bottom) / frame.width,
aspect: frame.width / frame.height,
heroTop: (image.top - frame.top) / frame.height,
width: image.width / frame.width,
}
})
if (scene.variant === 'hero') {
expect(geometry.aspect).toBeCloseTo(width < 640 ? 2 : 50 / 19, 1)
expect(Math.abs(geometry.left - (width < 640 ? 0.06 : 0.11))).toBeLessThan(0.008)
expect(Math.abs(geometry.width - (width < 640 ? 0.88 : 0.78))).toBeLessThan(0.012)
expect(Math.abs(geometry.heroTop - (width < 640 ? 0.14 : 0.184))).toBeLessThan(0.015)
expect(geometry.bottom).toBeLessThan(0)
} else {
const side = scene.variant === 'overview' ? 0.07 : 0.05
expect(Math.abs(geometry.left - side)).toBeLessThan(0.008)
expect(Math.abs(geometry.right - side)).toBeLessThan(0.008)
expect(
Math.abs(geometry.top - (scene.variant === 'overview' ? 0.06 : 0.05))
).toBeLessThan(0.008)
expect(
Math.abs(geometry.bottom - (scene.variant === 'detail' ? 0.05 : 0))
).toBeLessThan(0.008)
}
await page.mouse.move(width - 5, 5)
await page.screenshot({
path: join(directory, `image-${scene.variant}-${width}.png`),
animations: 'disabled',
})
const trigger = figure.getByRole('button')
await trigger.click()
const viewer = page.getByRole('dialog')
await expect(viewer.getByRole('img')).toBeVisible()
await expect
.poll(() =>
viewer
.getByRole('img')
.evaluate(
(element) =>
element instanceof HTMLImageElement &&
element.complete &&
element.naturalWidth > 0
)
)
.toBe(true)
const expandedImage = await viewer.getByRole('img').evaluate((element) => {
if (!(element instanceof HTMLImageElement)) throw new Error('Viewer image is missing')
const rect = element.getBoundingClientRect()
const style = getComputedStyle(element)
const width =
rect.width -
Number.parseFloat(style.borderLeftWidth) -
Number.parseFloat(style.borderRightWidth)
const height =
rect.height -
Number.parseFloat(style.borderTopWidth) -
Number.parseFloat(style.borderBottomWidth)
return {
ratio: width / height,
naturalRatio: element.naturalWidth / element.naturalHeight,
radius: Number.parseFloat(style.borderTopLeftRadius),
}
})
expect(Math.abs(expandedImage.ratio - expandedImage.naturalRatio)).toBeLessThan(0.01)
expect(expandedImage.radius).toBeGreaterThan(0)
await expect(viewer.locator('img[aria-hidden="true"]')).toHaveAttribute(
'src',
new RegExp(`${scene.background}(?:\\.[a-zA-Z0-9_-]+)?\\.webp`)
)
if (scene.variant === 'hero')
await page.screenshot({
path: join(directory, `expanded-platform-${width}.png`),
animations: 'disabled',
})
await page.keyboard.press('Escape')
await expect(viewer).toHaveCount(0)
await expect(trigger).toBeFocused()
await trigger.press('Enter')
await expect(viewer).toBeVisible()
await page
.locator('.docs-portal[data-state="open"][aria-hidden="true"]')
.click({ position: { x: 1, y: 1 } })
await expect(viewer).toHaveCount(0)
await expect(trigger).toBeFocused()
await trigger.press('Enter')
await expect(viewer).toBeVisible()
await viewer.getByRole('button', { name: 'Close media viewer', exact: true }).click()
await expect(viewer).toHaveCount(0)
await expect(trigger).toBeFocused()
} finally {
await page.close()
}
})
}
for (const kind of ['loop', 'parallel']) {
await check(`Inline ${kind} body opens lightbox at ${width}px`, async () => {
const page = await context.newPage()
try {
await open(page, `/workflows/blocks/${kind}`)
const container = page.locator('.react-flow__node-previewContainer').first()
await expect(container).toBeVisible()
const bounds = await container.boundingBox()
if (!bounds) throw new Error('Container has no visible bounds')
await container.click({ position: { x: bounds.width / 2, y: bounds.height - 8 } })
const viewer = page.getByRole('dialog')
await expect(viewer).toBeVisible()
await page.screenshot({ path: join(directory, `${kind}-body-${width}.png`) })
await page.keyboard.press('Escape')
await expect(viewer).toHaveCount(0)
} finally {
await page.close()
}
})
}
await check(`Workflow lightbox at ${width}px`, async () => {
const page = await context.newPage()
try {
await open(page, '/workflows/data-flow')
const trigger = page.getByRole('button', {
name: 'Inspect workflow: Classify and reply',
exact: true,
})
await trigger.click()
const viewer = page.getByRole('dialog')
await expect(viewer).toBeVisible()
await expect(viewer.locator('.react-flow__node').first()).toBeVisible()
await page.screenshot({ path: join(directory, `workflow-canvas-${width}.png`) })
await page.keyboard.press('Escape')
await expect(viewer).toHaveCount(0)
await expect(trigger).toBeFocused()
await trigger.press('Enter')
await expect(viewer).toBeVisible()
await page
.locator('.docs-portal[data-state="open"][aria-hidden="true"]')
.click({ position: { x: 1, y: 1 } })
await expect(viewer).toHaveCount(0)
await expect(trigger).toBeFocused()
await trigger.press('Enter')
await viewer.getByRole('button', { name: 'Close media viewer', exact: true }).click()
await expect(viewer).toHaveCount(0)
await expect(trigger).toBeFocused()
} finally {
await page.close()
}
})
} finally {
await context.close()
}
}
const scenarios = [
{ path: '/introduction', title: 'Introduction', content: '## Models and integrations' },
{ path: '/getting-started', title: 'Getting started', content: '## Start in Chat' },
{ path: '/files', title: 'Files', content: '## Upload or create a file' },
{ path: '/integrations/apollo', title: 'Apollo', content: '### Apollo People Search' },
{
path: '/api-reference/workflows/listWorkflows',
title: 'List workflows',
content: 'GET /api/v2/workflows',
},
]
for (const viewport of [
{ name: 'desktop', width: 1440, height: 1000 },
{ name: 'mobile', width: 390, height: 844 },
]) {
for (const scenario of scenarios) {
const context = await browser.newContext({ viewport, reducedMotion: 'reduce' })
try {
await check(
`${viewport.name}: navigation${engine === 'chromium' ? ' and complete copy' : ''}${viewport.name === 'desktop' && scenario.path === '/introduction' ? ' and client metadata' : ''} for ${scenario.path}`,
async () => {
const page = await context.newPage()
const errors: string[] = []
const markdownRequests: string[] = []
page.on('pageerror', (error) => errors.push(error.message))
page.on('request', (request) => {
if (/\.(md|mdx)$/.test(new URL(request.url()).pathname))
markdownRequests.push(request.url())
})
await open(page, scenario.path)
const checkMetadata = viewport.name === 'desktop' && scenario.path === '/introduction'
const sourceMetadata = checkMetadata
? await verifyClientMetadata(page, scenario.path, scenario.title)
: undefined
const sourceTimeOrigin = checkMetadata
? await page.evaluate(() => performance.timeOrigin)
: undefined
expect(markdownRequests).toEqual([])
if (scenario.path.startsWith('/api-reference/')) {
const tabs = page
.getByRole('tablist', { name: 'Request language', includeHidden: true })
.getByRole('tab', { includeHidden: true })
expect(await tabs.count()).toBeGreaterThan(1)
for (let index = 0; index < (await tabs.count()); index += 1) {
await selectRequestLanguage(page, (await tabs.nth(index).innerText()).trim())
await expect(tabs.nth(index)).toHaveAttribute('aria-selected', 'true')
const panelId = await tabs.nth(index).getAttribute('aria-controls')
expect(panelId).toBeTruthy()
const panel = page.locator(`[id="${panelId}"]`)
await expect(panel).toBeVisible()
expect((await panel.locator('code').textContent())?.trim()).toBeTruthy()
}
}
if (viewport.name === 'desktop' && engine === 'chromium') {
await verifyClipboard(page, context, scenario.path, scenario.title, scenario.content)
expect(markdownRequests[0]).toBe(new URL(`${scenario.path}.md`, target).href)
}
if (scenario.path === '/introduction') {
if (viewport.name === 'mobile')
await page.getByRole('button', { name: 'Menu', exact: true }).click()
const navigation = page.getByRole('navigation', {
name: 'Documentation sidebar',
exact: true,
})
const branch = navigation.getByRole('button', {
name: /^(Expand |Collapse )?Platform$/,
})
const costs = navigation.getByRole('link', {
name: 'Credits, billing and limits',
exact: true,
})
if (!(await costs.isVisible())) await branch.click()
await expect(costs).toBeVisible()
await branch.press('Enter')
await expect(costs).toBeHidden()
await branch.press('Enter')
await costs.click()
await expect(page).toHaveURL(new URL('/platform/costs', target).href)
await expect(
page.getByRole('heading', {
level: 1,
name: 'Credits, billing and limits',
exact: true,
})
).toBeVisible()
if (checkMetadata) {
const destinationMetadata = await verifyClientMetadata(
page,
'/platform/costs',
'Credits, billing and limits'
)
expect(await page.evaluate(() => performance.timeOrigin)).toBe(sourceTimeOrigin)
expect(destinationMetadata.description).not.toBe(sourceMetadata?.description)
await writeFile(
join(directory, 'metadata-after-client-navigation.json'),
`${JSON.stringify({ source: sourceMetadata, destination: destinationMetadata, sameDocument: true }, null, 2)}\n`
)
}
if (viewport.name === 'mobile') {
await expect(page.getByRole('dialog')).not.toBeVisible()
await page.getByRole('button', { name: 'Menu', exact: true }).click()
}
await expect(costs).toHaveAttribute('aria-current', 'page')
await expect(branch).toHaveAttribute('aria-expanded', 'true')
if (viewport.name === 'mobile')
await page.getByRole('button', { name: 'Close navigation' }).click()
else if (engine === 'chromium')
await verifyClipboard(
page,
context,
'/platform/costs',
'Credits, billing and limits',
'## What a workflow run costs'
)
}
expect(
await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)
).toBe(true)
await page.screenshot({
path: join(directory, `${viewport.name}${scenario.path.replaceAll('/', '-')}.png`),
})
expect(errors).toEqual([])
}
)
} finally {
await context.close()
}
}
}
for (const reveal of ['fragment', 'beforematch'] as const) {
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } })
try {
await check(`Nested response tabs reveal their ancestors through ${reveal}`, async () => {
const page = await context.newPage()
await open(page, '/api-reference/logs/getLog')
const status = page.locator('#response-400')
const media = status.getByRole('tabpanel', { includeHidden: true }).first()
const statuses = page.getByRole('tablist', { name: 'Response status' })
await expect(page.locator('#response-200')).toBeVisible()
await expect(status).toBeHidden()
const mediaId = await media.getAttribute('id')
if (!mediaId) throw new Error('Response media panel has no fragment identifier')
if (reveal === 'fragment')
await page.evaluate((id) => {
window.location.hash = encodeURIComponent(id)
}, mediaId)
else await media.dispatchEvent('beforematch')
await expect(statuses.getByRole('tab', { name: '400', exact: true })).toHaveAttribute(
'aria-selected',
'true'
)
await expect(status).toBeVisible()
await expect(media).toBeVisible()
await expect(page.locator('#response-200')).toBeHidden()
await statuses.getByRole('tab', { name: '200', exact: true }).click()
await expect(page.locator('#response-200')).toBeVisible()
await expect(status).toBeHidden()
await page.screenshot({ path: join(directory, `nested-tabs-${reveal}.png`) })
})
} finally {
await context.close()
}
}
for (const colorScheme of ['light', 'dark'] as const) {
for (const width of [320, 768, 1440]) {
const context = await browser.newContext({ viewport: { width, height: 900 }, colorScheme })
try {
await check(`API example menu: ${colorScheme} at ${width}px`, async () => {
const page = await context.newPage()
await open(page, '/api-reference/workflows/listWorkflows')
const trigger = page.getByRole('button', { name: /^Response example:/ })
await trigger.scrollIntoViewIfNeeded()
const selectedRegion = page
.getByRole('region', { name: 'Response', exact: true })
.filter({ visible: true })
const initialPanel = await selectedRegion.getAttribute('id')
await trigger.focus()
await page.keyboard.press('Enter')
const menu = page.getByRole('menu')
await expect(menu).toBeVisible()
await expect(menu).toHaveAttribute(
'aria-labelledby',
(await trigger.getAttribute('id')) ?? ''
)
await expect(trigger).toHaveAttribute(
'aria-controls',
(await menu.getAttribute('id')) ?? ''
)
await expect(page.getByRole('menuitemradio', { name: /^200/ })).toHaveAttribute(
'aria-checked',
'true'
)
const bounds = await menu.boundingBox()
if (!bounds) throw new Error('API example menu has no bounds')
expect(bounds.x).toBeGreaterThanOrEqual(0)
expect(bounds.x + bounds.width).toBeLessThanOrEqual(width)
expect(bounds.y + bounds.height).toBeLessThanOrEqual(900)
await page.getByRole('menuitemradio', { name: '400', exact: true }).focus()
await page.keyboard.press('Enter')
await expect(menu).toHaveCount(0)
await expect(trigger).toBeFocused()
await expect(trigger).toHaveAccessibleName('Response example: 400')
const selectedPanel = await selectedRegion.getAttribute('id')
if (!initialPanel || !selectedPanel) throw new Error('API examples have no panel IDs')
await expect(page.locator(`[id="${initialPanel}"]`)).toBeHidden()
await expect(page.locator(`[id="${selectedPanel}"]`)).toBeVisible()
await trigger.click()
await expect(
page.getByRole('menuitemradio', { name: '400', exact: true })
).toHaveAttribute('aria-checked', 'true')
await page.screenshot({
path: join(directory, `api-example-menu-${colorScheme}-${width}.png`),
})
await page.keyboard.press('Escape')
await expect(trigger).toBeFocused()
expect(
await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)
).toBe(true)
})
} finally {
await context.close()
}
}
}