Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 111 additions & 0 deletions .github/fixtures/pelican-question-e2e/navigation.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import assert from 'node:assert/strict'
import { EventEmitter } from 'node:events'
import test from 'node:test'
import { createPageNavigation } from '../../scripts/pelican-complete-rounds.mjs'

class Page extends EventEmitter {
calls = []
// A document lifecycle state alone is not an in-flight request barrier.
async waitForLoadState() {}
async goto(url, options) { this.calls.push({ url, options }) }
async reload(options) { this.calls.push({ reload: true, options }) }
}
const nextTask = () => new Promise(resolve => setImmediate(resolve))

for (const action of ['goto', 'reload']) {
test(`${action}: drains auth/settings and subsequent requests before unloading`, async () => {
const page = new Page()
const navigation = createPageNavigation(page)
const auth = {}, settings = {}, followup = {}
page.emit('request', auth)
page.emit('request', settings)
const done = action === 'goto' ? navigation.goto('http://app:8080/admin/accounts') : navigation.reload()
await nextTask()
assert.equal(page.calls.length, 0, 'navigation must wait for outstanding bootstrap requests')
page.emit('requestfinished', auth)
page.emit('request', followup)
page.emit('requestfinished', settings)
await nextTask()
assert.equal(page.calls.length, 0, 'a request added during drain must also complete')
page.emit('requestfinished', followup)
await done
assert.equal(page.calls.length, 1)
assert.equal(page.calls[0].options.waitUntil, 'load')
})
}

test('failed requests still reach the strict error guard without filtering', async () => {
const page = new Page()
const failures = []
page.on('requestfailed', request => failures.push(request))
const navigation = createPageNavigation(page)
const failed = { reason: 'net::ERR_ABORTED' }
page.emit('request', failed)
const done = navigation.settle()
page.emit('requestfailed', failed)
await done
assert.deepEqual(failures, [failed])
assert.throws(() => assert.equal(failures.length, 0, 'no failed browser requests'))
})

test('navigation waits for destination requests before returning', async () => {
const page = new Page()
const navigation = createPageNavigation(page)
const pending = {}
page.goto = async (url, options) => { page.calls.push({ url, options }); page.emit('request', pending) }
let returned = false
const done = navigation.goto('http://app:8080/admin/accounts').then(() => { returned = true })
await nextTask()
assert.equal(returned, false)
page.emit('requestfinished', pending)
await done
assert.equal(returned, true)
})

test('srcdoc preview detachment cannot strand navigation on a stale networkidle lifecycle', async () => {
const page = new Page()
page.waitForLoadState = async state => {
assert.equal(state, 'load', 'use document readiness plus tracked request completion, not the stranded networkidle flag')
}
const navigation = createPageNavigation(page)
await navigation.goto('http://app:8080/admin/pelican-tests')
assert.equal(page.calls.length, 1)
assert.equal(page.calls[0].options.waitUntil, 'load')
})

test('an unfinished request still fails at the unchanged twenty-second deadline', async t => {
t.mock.timers.enable({ apis: ['setTimeout', 'Date'], now: 0 })
const page = new Page()
const navigation = createPageNavigation(page)
page.emit('request', {})
let failed = false
const done = assert.rejects(navigation.settle(), /browser requests did not finish before navigation/)
.then(() => { failed = true })
await Promise.resolve()
t.mock.timers.tick(19_999)
await Promise.resolve()
assert.equal(failed, false)
t.mock.timers.tick(1)
await done
assert.equal(failed, true)
assert.equal(page.calls.length, 0)
})

test('document readiness consumes the same deadline rather than granting another twenty seconds', async t => {
t.mock.timers.enable({ apis: ['setTimeout', 'Date'], now: 0 })
const page = new Page()
page.waitForLoadState = () => new Promise(resolve => setTimeout(resolve, 15_000))
const navigation = createPageNavigation(page)
page.emit('request', {})
let failed = false
const done = assert.rejects(navigation.settle(), /browser requests did not finish before navigation/)
.then(() => { failed = true })
t.mock.timers.tick(15_000)
await Promise.resolve()
t.mock.timers.tick(4_999)
await Promise.resolve()
assert.equal(failed, false)
t.mock.timers.tick(1)
await done
assert.equal(failed, true)
})
38 changes: 38 additions & 0 deletions .github/scripts/free-fast-cost-evidence.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#!/usr/bin/env python3
"""Reject setup failures, skips and absent tests in remote Go evidence."""
import json
import re
import sys
from pathlib import Path

mode, filename, *required = sys.argv[1:]
raw = Path(filename).read_text()
assert not re.search(r'build failed|undefined:|panic:|panic_recovered|fatal error:|runtime error:|WARNING: DATA RACE|no tests to run', raw, re.I), 'setup, panic, race or missing-tests failure'
events = [json.loads(line) for line in raw.splitlines() if line.startswith('{')]
assert events, 'no Go JSON events'
assert not any(e.get('Action') == 'skip' for e in events), 'skipped tests'
for name in required:
selected = [e for e in events if e.get('Test') == name]
assert selected, f'missing test {name}'
action = 'fail' if mode == 'red' else 'pass'
assert any(e.get('Action') == action for e in selected), f'{name}: expected {action}'
if mode == 'red':
output = ''.join(e.get('Output', '') for e in events
if e.get('Test') == name or e.get('Test', '').startswith(name + '/'))
marker = ('Standard cache prices must be persisted from the resolved quote' if name.endswith('CachePrices')
else 'restricted admin must expose the immutable customer Standard quote' if name.endswith('ScopedAdmin')
else 'user/admin DTO must expose the immutable customer Standard quote' if name.endswith('DTO')
else 'stored usage must retain the customer Standard quote' if name.endswith('Persistence')
else 'Free Fast must persist the Standard customer cost snapshot')
assert marker in output, f'{name}: missing target business assertion'
if mode == 'red':
assert any(marker in raw for marker in [
'Free Fast must persist the Standard customer cost snapshot',
'user/admin DTO must expose the immutable customer Standard quote',
'restricted admin must expose the immutable customer Standard quote',
'Standard cache prices must be persisted from the resolved quote',
'stored usage must retain the customer Standard quote',
]), 'RED did not reach a target business assertion'
else:
assert not any(e.get('Action') == 'fail' for e in events), 'GREEN has failures'
print(f'{mode}: verified {len(required)} required tests; no setup errors, panic, race or skips')
149 changes: 149 additions & 0 deletions .github/scripts/free-fast-customer-cost-browser.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
// Real shared UsageTable + real styles/locales, with synthetic data only.
import assert from 'node:assert/strict'
import { execFile } from 'node:child_process'
import { promisify } from 'node:util'
const exec = promisify(execFile)
import { createRequire } from 'node:module'
import { createHash } from 'node:crypto'
import fs from 'node:fs/promises'
import path from 'node:path'
import { pathToFileURL } from 'node:url'

const root = process.cwd()
const frontend = path.join(root, 'frontend')
const output = process.env.FREE_FAST_SCREENSHOT_DIR
assert.ok(output, 'FREE_FAST_SCREENSHOT_DIR must point outside the source tree')
const base = '0e8e97aa23afd8e88a61ea64a84a8fb84f1bfdc6'
const head = (await exec('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' })).stdout.trim()
const req = createRequire(path.join(frontend, 'package.json'))
const { createServer } = req('vite')
const vue = req('@vitejs/plugin-vue').default
const browserReq = createRequire(path.join(process.env.PLAYWRIGHT_ROOT, 'package.json'))
const { chromium } = browserReq('playwright')
await fs.mkdir(output, { recursive: true })
const before = path.join(output, 'before-source')
await fs.mkdir(before, { recursive: true })
// Export the complete baseline source, including transitive non-frontend assets.
const archive = path.join(output, 'baseline-source.tar')
await exec('git', ['archive', '--output=' + archive, base])
await exec('tar', ['-xf', archive, '-C', before])
await fs.symlink(path.join(frontend, 'node_modules'), path.join(before, 'frontend/node_modules')).catch(e => { if (e.code !== 'EEXIST') throw e })
const fixtureFile = 'src/components/admin/usage/__tests__/fixtures/freeFastCustomerCost.ts'
const fixture = await fs.readFile(path.join(frontend, fixtureFile), 'utf8')
const manifest = { complete: false, base, head, fixtureSha256: createHash('sha256').update(fixture).digest('hex'), harnessSha256: createHash('sha256').update(await fs.readFile(new URL(import.meta.url))).digest('hex'), synthetic: true, source: 'real Vue shared UsageTable, real DataTable, popover/dialog, locales and style.css', screenshots: [], errors: [], requests: [] }
const browser = await chromium.launch({ headless: true, args: ['--no-sandbox'] })
try {
for (const revision of ['before', 'after']) {
const source = revision === 'before' ? path.join(before, 'frontend') : frontend
const component = await fs.readFile(path.join(source, 'src/components/admin/usage/UsageTable.vue'))
const componentHash = createHash('sha256').update(component).digest('hex')
const html = `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"></head><body><div id="app"></div><script type="module">
import {createApp,h} from 'vue';import {createPinia} from 'pinia';
import UsageTable from '/src/components/admin/usage/UsageTable.vue';
import {i18n,loadLocaleMessages} from '/src/i18n/index.ts';
import {freeFastCachePriceFixture,freeFastMixedCachePriceFixture} from 'fixture:cost';
import '/src/style.css';
const params=new URLSearchParams(location.search),lang=params.get('lang'),admin=params.get('role')==='admin';
await loadLocaleMessages(lang);i18n.global.locale.value=lang;
const fixture=params.get('fixture')==='mixed'?freeFastMixedCachePriceFixture:freeFastCachePriceFixture;
const data=[{...fixture,created_at:'2026-01-01T00:00:00Z',duration_ms:1000,first_token_ms:100,request_type:'stream',cache_ttl_overridden:false,long_context_billing_applied:false}];
const columns=[{key:'model',label:i18n.global.t('usage.model')},{key:'cost',label:i18n.global.t('usage.costDetails')}];
createApp({render:()=>h('main',{class:'p-4 mx-auto max-w-4xl'},[h(UsageTable,{data,columns,showAccountBilling:admin,cacheRateAudience:admin?'admin':'user',enableTimingDetails:false})])}).use(createPinia()).use(i18n).mount('#app');
</script></body></html>`
const tailwindConfig = (await import(pathToFileURL(path.join(source, 'tailwind.config.js')).href)).default
process.chdir(source)
const server = await createServer({ root: source, configFile: false, envFile: false,
cacheDir: path.join(output, 'vite-cache-' + revision),
define: { __INTLIFY_JIT_COMPILATION__: true },
css: { postcss: { plugins: [
req('tailwindcss')({ ...tailwindConfig, content: [path.join(source, 'index.html'), path.join(source, 'src/**/*.{vue,js,ts,jsx,tsx}')] }),
req('autoprefixer')(),
] } },
plugins: [vue(), { name: 'synthetic-cost-page',
resolveId(id) { if (id === 'fixture:cost') return '\0fixture:cost' },
load(id) { if (id === '\0fixture:cost') return fixture },
configureServer(vite) {
vite.middlewares.use((request, response, next) => {
if (request.url?.split('?')[0] !== '/') return next()
response.setHeader('Content-Type', 'text/html')
void vite.transformIndexHtml('/', html).then(text => response.end(text))
})
} }],
resolve: { alias: { '@': path.join(source, 'src'), 'vue-i18n': 'vue-i18n/dist/vue-i18n.runtime.esm-bundler.js' } },
server: { host: '127.0.0.1', port: 4189, strictPort: true, fs: { allow: [source, frontend] } },
optimizeDeps: { entries: [], include: ['vue', 'pinia', 'vue-i18n', 'axios'] },
})
await server.listen()
try {
for (const fixtureName of ['exact', 'mixed']) for (const locale of ['en', 'zh']) for (const role of ['user', 'admin']) for (const size of ['desktop', 'mobile']) {
const viewport = size === 'mobile' ? { width: 390, height: 844 } : { width: 1280, height: 900 }
const context = await browser.newContext({ viewport, colorScheme: 'light', timezoneId: 'UTC', locale: locale === 'zh' ? 'zh-CN' : 'en-US' })
await context.route('**/*', async route => {
const url = new URL(route.request().url())
if (url.origin !== 'http://127.0.0.1:4189') throw new Error('Unexpected external request: ' + url.origin)
if (url.pathname.startsWith('/api/')) {
manifest.requests.push(url.pathname)
return route.fulfill({ json: { code: 0, data: {} } })
}
return route.continue()
})
const page = await context.newPage()
page.on('pageerror', error => manifest.errors.push(error.message))
await page.goto(`http://127.0.0.1:4189/?lang=${locale}&role=${role}&fixture=${fixtureName}`, { waitUntil: 'networkidle' })
const button = page.getByRole('button', { name: locale === 'zh' ? '费用明细' : 'Cost Breakdown', exact: true })
// Use the actual accessible label even when a locale changes its translation.
const costButton = await button.count() ? button : page.locator('button[aria-expanded]').filter({ has: page.locator('.text-green-600') })
await costButton.click()
const panel = page.locator(size === 'mobile' ? '[role="dialog"]' : '[role="tooltip"]')
await panel.waitFor({ state: 'visible' })
// Capture the settled dialog, not a partially transparent enter frame.
await panel.evaluate(async element => {
await Promise.all(element.getAnimations({ subtree: true })
.filter(animation => animation.effect?.getComputedTiming().iterations !== Infinity)
.map(animation => animation.finished))
})
const text = await panel.innerText()
assert.ok(text.includes(revision === 'after' ? '$10.0000' : '$20.0000'), text)
assert.ok(text.includes(revision === 'after' ? '$50.0000' : '$100.0000'), text)
const amounts = fixtureName === 'exact'
? (revision === 'after' ? ['0.08345000', '0.00680000', '0.01496250', '0.03746900', '0.14268150'] : ['0.16690000', '0.01360000', '0.01496250', '0.07493800', '0.27040050'])
: (revision === 'after' ? ['0.08345000', '0.00680000', '0.00046250', '0.00001700', '0.09072950'] : ['0.16690000', '0.01360000', '0.00046250', '0.00003400', '0.18099650'])
for (const value of amounts) assert.ok(text.includes('$' + value), text)
assert.ok(text.includes(fixtureName === 'exact' ? '$0.07134075' : '$0.04536475'), text)
if (revision === 'after') {
assert.ok((await panel.getByTestId('cache-unit-read').innerText()).includes('$1.0000'))
assert.ok((await panel.getByTestId('cache-unit-write_30m').innerText()).includes('$12.5000'))
if (fixtureName === 'mixed') assert.ok((await panel.getByTestId('cache-unit-write_12h').innerText()).includes('$25.0000'))
assert.ok(text.includes(locale === 'zh' ? '缓存读取单价' : 'Cache read price'), text)
assert.ok(text.includes(locale === 'zh' ? '缓存写入单价(30m)' : 'Cache write price (30m)'), text)
}
assert.ok(text.includes('Fast'), text)
assert.ok(!/Free Fast|Fast 加速免费|按 Standard 计费/.test(text), text)
const bounds = await panel.boundingBox()
assert.ok(bounds && bounds.x >= 0 && bounds.x + bounds.width <= viewport.width + 1 && bounds.y >= 0 && bounds.y + bounds.height <= viewport.height + 1, JSON.stringify(bounds))
const contentBounds = await panel.locator('.bg-gray-900').boundingBox()
assert.ok(contentBounds && contentBounds.x >= 0 && contentBounds.y >= 0 && contentBounds.x + contentBounds.width <= viewport.width + 1 && contentBounds.y + contentBounds.height <= viewport.height + 1, JSON.stringify(contentBounds))
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth))
const computedStyle = await panel.locator('.bg-gray-900').evaluate(element => {
const css = getComputedStyle(element)
return { background: css.backgroundColor, fontSize: css.fontSize, padding: css.paddingLeft, border: css.borderTopWidth }
})
assert.equal(computedStyle.background, 'rgb(17, 24, 39)', JSON.stringify(computedStyle))
assert.equal(computedStyle.fontSize, '12px')
assert.equal(computedStyle.padding, '12px')
assert.equal(computedStyle.border, '1px')
const name = `${fixtureName}-${revision}-${locale}-${role}-${size}.png`
await page.screenshot({ path: path.join(output, name), fullPage: true, animations: 'disabled' })
const digest = createHash('sha256').update(await fs.readFile(path.join(output, name))).digest('hex')
manifest.screenshots.push({ file: name, sha256: digest, componentSha256: componentHash, fixtureName, revision, locale, role, viewport, bounds, contentBounds, computedStyle, text })
await context.close()
}
} finally { await server.close(); process.chdir(root) }
}
assert.deepEqual(manifest.errors, [])
assert.equal(manifest.screenshots.length, 32)
manifest.complete = true
} finally {
await browser.close()
await fs.writeFile(path.join(output, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n')
}
Loading
Loading