🧲 fix: Settle Fast Pinned Drops, Defer the Hidden Mobile Header Menu, and Close Untraced E2E Races (#18087)

* 🧪 test: Read the Artifact Scrim's Blur From the Persistent Scrim

"a small blur surface still blurs by four pixels" read the backdrop filter
of `#artifact-viewer [role="status"]`.first() once, with a single evaluate.

The artifact panel's lazy tabs also render a `role="status"` loading
placeholder until their chunk arrives, and the panel re-renders while it
opens. A one-shot read that resolves the wrong status, or a node React has
just replaced, gets the computed style of a detached element: an empty
string instead of `blur(4px)`.

Select the always-mounted refresh scrim, the only status that carries
`aria-hidden`, and assert its filter with `toHaveCSS`, which re-resolves and
retries until the value settles.

Untraced, on two CPUs: 11 of 20 runs failed with `Received: ""` before,
20 of 20 pass after.

* ⚡ perf: Mount the Mobile Header Menu Only Once a Phone Layout Has Shown It

The chat header rendered both of its action surfaces on every load: the
desktop buttons and the mobile overflow menu, hidden with `className="hidden"`
on wide screens. The hidden menu still mounted its whole tree on desktop,
with its bookmark, export, share, temporary-chat and pull-request hooks and
its dialog providers.

Mount the overflow menu only while the drawer viewport is active, and keep
it mounted once it has been shown, so resizing back to desktop does not drop
a dialog opened from it.

Measured with a React DevTools hook counting component renders over a cold
desktop load of a saved conversation (7 warm navigations each, production
build): 1,313 component mounts before and 1,242 after, the overflow trigger
no longer in the DOM, and the median component re-renders over the load
5,835 before and 5,682 after.

`dropped-classes.spec.ts` read the overflow trigger's size on a desktop
viewport, where it was only attached; it now reads it at phone width, where
the trigger is visible.

* 🧲 fix: Settle a Pinned Row's Position on Drop, Not Only on Hover

A pinned row reorders in its `hover` callback, which judges the pointer
against the hovered row's midpoint using the offset react-dnd last recorded.
The HTML5 backend delivers hover once per animation frame, so a release that
lands in the same frame as the move across the midpoint is judged against the
offset from before it: the swap is refused and the drop keeps the old order.
A quick, deliberate drag is discarded.

The drop handler now runs the same placement against the final pointer offset
before returning its result, so `end` commits the order the pointer actually
ended on. Hovering is unchanged.

The new regression holds the hover frame and fires dragover/drop at a point
past the midpoint and at one short of it. On the previous handler the first
case keeps the old order; with this change both cases match the pointer.

In a real browser, with a drag that releases without waiting for a hover
frame: "a pinned chat cannot be dragged through a pinned model" kept the old
order in 4 of 15 untraced runs on the previous handler and 0 of 15 with this
one.

* 🧲 test: Release a Pinned Drag Without Waiting for a Hover Frame

The pinned drag helper waited for an animation frame after each settling
move, so react-dnd had delivered a hover at the final position before the
release. That kept the reorder scenario green while a release landing in the
same frame as its last move was discarded by the app.

The drop handler now settles the final pointer position itself, so that wait
no longer stands between the scenario and a failure; it only hides the
fast-release path. Release straight after the settling moves again, so the
scenario covers it.

Untraced, on two CPUs, with this helper: "a pinned chat cannot be dragged
through a pinned model" failed 4 of 15 runs against the previous drop handler
and passed 15 of 15 with the settled drop; the whole pinned-drag-rules file
passed 30 of 30.

* 🧪 test: Publish the Reaper Fixture's PID Only After It Is Written

Two reaper tests wait for a PID file to exist and then read it. The shell
creates the file when it opens the redirection and writes the PID a moment
later, so a read in between gets an empty file. `Number('')` is 0, and
`isGone(0)` reports true because there is no `/proc/0`: "escalates to
SIGKILL when the tree ignores SIGTERM" and "sweep reaps a group that
outlived a clean root exit" then fail their "still running" assertion.

Write the PID to a temporary file and rename it into place, so the file
appears only with its content. With a 0.3 s pause forced between the
redirection and the write, both tests fail on the old fixture and pass on
this one.

Also kill each spawned process group after every test, so a failing test
does not leave its trap-protected `sleep 30` behind, and read the process
state with `ps` where `/proc` does not exist.

* 🔦 test: Keep a Measured Trace and a Startup Profile When Lighthouse Fails

When the serial-latency audit fails a budget, the uploaded `.lighthouse/`
holds the JSON and HTML reports only. They name the slow metric but not the
main-thread work behind it, so a total-blocking-time failure cannot be traced
to the code that blocked without reproducing it locally.

- Run Lighthouse with `--save-assets`, keeping each run's measured
  `lhr-*-0.trace.json` for Chrome's Performance panel. Its raw DevTools
  network log is deleted; the trace is parsed and every string value has the
  session cookie values redacted, so numeric timings and JSON structure
  survive even for short cookie values. A trace that does not parse (an
  interrupted run) is deleted rather than uploaded raw.
- After a failed audit, navigate once more with the CDP profiler running and
  save `.lighthouse/startup.cpuprofile`, including three seconds after the
  transcript appears so late catalog callbacks are sampled. This runs after
  the measured audits, so it cannot change their numbers, and a profiling
  error never replaces the original failure.

Budgets, runs and the workflow are unchanged; the workflow already uploads
`.lighthouse/`.

* 🔦 test: Keep Lighthouse Traces Only When the Audit Fails

Each saved trace is about 45 MB, so keeping all three on every run turned the
always-uploaded `lighthouse` artifact from about 2 MB into about 137 MB for
runs that pass and need no diagnosis. Delete the traces once the test's last
assertion has passed; a failing run still uploads them with its reports.

* 🧪 test: Read the Streaming Shimmer From the Live Footer

"an in-flight label sweeps, and high contrast holds both stops opaque" read
the stream-elapsed label's styles once through `locator.evaluate`. The label
lives in the streaming footer, which re-renders while the reply streams; when
the node the locator resolved was replaced before the evaluate ran, the read
came from a detached element or failed.

Assert the animation name and background clip with `toHaveCSS`, which
re-resolves and retries, and read the shimmer's dip alpha by querying the
current node inside the evaluate, polling until it settles.

Untraced, on two CPUs: 4 of 20 runs failed with `Received: ""` before,
20 of 20 pass after.

* 🧪 test: Click the Drawer's New Chat Link, Not Whichever One Is Exposed

"returns focus after right-clicking an unopened running menu on a small
screen" opens the mobile drawer and clicks
`getByRole('link', { name: 'New chat', exact: true })`. On a saved chat the
header row also offers a New chat link, and it hides only when the sidebar's
expanded state commits. On mobile that commit is deferred: the drawer starts
sliding first and the state flips a few frames later inside a transition,
which a streaming run keeps pushing back. The drawer's Close button is
already visible during the slide, so the test reaches the click while both
links are exposed and fails with a strict mode violation.

Scope the locator to `#mobile-drawer`, the link the test means.

Untraced, on two CPUs: 20 of 20 runs failed on the previous locator and 20
of 20 pass with this one.

---------

Co-authored-by: Dustin Healy <54083382+dustinhealy@users.noreply.github.com>
This commit is contained in:
Danny Avila 2026-11-12 09:47:46 -05:00 • committed by GitHub
parent 502a5734be
commit cbd4cbb5fb
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
15 changed files with 329 additions and 80 deletions

View file

@ -1,4 +1,4 @@
import { memo, useMemo } from 'react';
import { memo, useMemo, useState, useEffect } from 'react';
import { useRecoilValue } from 'recoil';
import { useParams } from 'react-router-dom';
import { useIsSubmitting } from '@librechat/chat/react';
@ -41,6 +41,10 @@ function Header({
const navVisible = useRecoilValue(store.sidebarExpanded);
const isSubmitting = useIsSubmitting(0);
const isSmallScreen = useDrawerViewport();
const [hasShownMobileMenu, setHasShownMobileMenu] = useState(false);
useEffect(() => {
if (isSmallScreen) setHasShownMobileMenu(true);
}, [isSmallScreen]);
/** The mobile row only offers a new chat when there is one to leave. Read
* from the route rather than the context conversation, which still holds the
@ -141,13 +145,17 @@ function Header({
isSubmitting={isSubmitting}
/>
)}
<HeaderMenu
startupConfig={startupConfig}
trace={trace}
readOnly={readOnly}
pullRequestConversationId={showPullRequest ? routeConversationId : undefined}
className={isSmallScreen ? undefined : 'hidden'}
/>
{/* Avoid mounting a second action tree on desktop startup. Once visited, retain it
so resizing does not discard dialogs opened from the mobile menu. */}
{(isSmallScreen || hasShownMobileMenu) && (
<HeaderMenu
startupConfig={startupConfig}
trace={trace}
readOnly={readOnly}
pullRequestConversationId={showPullRequest ? routeConversationId : undefined}
className={isSmallScreen ? undefined : 'hidden'}
/>
)}
<div className={cn('items-center gap-2', isSmallScreen ? 'hidden' : 'flex')}>
{trace.show && <TraceButton onClick={trace.open} />}
<ExportAndShareMenu

View file

@ -1,6 +1,6 @@
import React from 'react';
import '@testing-library/jest-dom';
import { render, screen } from '@testing-library/react';
import { render, screen, fireEvent } from '@testing-library/react';
import Header from '../Header';
const mockEndpoint = { current: 'agents' };
@ -79,11 +79,36 @@ describe('Header stacking', () => {
backgroundTasks.mockClear();
pullRequestChip.mockClear();
headerMenu.mockClear();
headerMenu.mockImplementation(() => null);
mockEndpoint.current = 'agents';
mockSmallScreen.current = false;
mockConversation.current = codeConversation;
});
test('does not mount the mobile action tree on desktop startup', () => {
render(<Header />);
expect(headerMenu).not.toHaveBeenCalled();
});
test('retains mobile action state when the viewport returns to desktop', () => {
headerMenu.mockImplementation(() => <input aria-label="Menu draft" defaultValue="" />);
const { rerender } = render(<Header />);
expect(screen.queryByRole('textbox', { name: 'Menu draft' })).not.toBeInTheDocument();
mockSmallScreen.current = true;
rerender(<Header readOnly />);
const input = screen.getByRole('textbox', { name: 'Menu draft' });
fireEvent.change(input, { target: { value: 'unsaved dialog state' } });
mockSmallScreen.current = false;
rerender(<Header />);
expect(screen.getByRole('textbox', { name: 'Menu draft' })).toBe(input);
expect(input).toHaveValue('unsaved dialog state');
expect(headerMenu.mock.calls.at(-1)[0]).toMatchObject({ className: 'hidden' });
mockSmallScreen.current = true;
rerender(<Header readOnly />);
expect(screen.getByRole('textbox', { name: 'Menu draft' })).toBe(input);
expect(input).toHaveValue('unsaved dialog state');
});
test('keeps header controls above the z-10 composer approval review', () => {
const { container } = render(<Header />);

View file

@ -3,6 +3,7 @@ import { ChevronDown } from 'lucide-react';
import { useDrag, useDragLayer, useDrop } from 'react-dnd';
import { Skeleton, useMediaQuery, useToastContext, buttonVariants } from '@librechat/client';
import type { TConversation, TEndpointsConfig } from 'librechat-data-provider';
import type { DropTargetMonitor } from 'react-dnd';
import type {
SelectEndpointHandler,
SelectSpecHandler,
@ -108,6 +109,33 @@ const DraggablePinnedRow = ({
}: DraggablePinnedRowProps) => {
const ref = useRef<HTMLDivElement>(null);
const hasHoverPointer = useMediaQuery('(hover: hover)');
const moveAtPointer = (
item: PinnedRowDragItem,
monitor: DropTargetMonitor<PinnedRowDragItem, unknown>,
) => {
/* Record even the dragged row itself: returning to it ends an earlier
* external hover, despite having no effect on the order. */
markPinnedHover();
if (!item.key || item.key === entry.key || !ref.current) {
return;
}
const clientOffset = monitor.getClientOffset();
if (!clientOffset) {
return;
}
const rect = ref.current.getBoundingClientRect();
if (
shouldSwapOnHover({
dragIndex: indexOfKey(item.key),
hoverIndex: indexOfKey(entry.key),
pointerY: clientOffset.y,
hoverTop: rect.top,
hoverBottom: rect.bottom,
})
) {
moveEntry(item.key, entry.key);
}
};
const [{ handlerId }, drop] = useDrop<PinnedRowDragItem, unknown, { handlerId: unknown }>({
/* A row only takes a drag of its own kind, so a pinned chat never shifts a
* pinned agent or model out of the way — not even as a preview. The two
@ -120,36 +148,17 @@ const DraggablePinnedRow = ({
* itself in the drop result instead. Without that name, `end` below saw
* `monitor.didDrop()` and read the release as a filing action, discarding
* the arrangement: every pointer reorder snapped back on release. */
drop: () => PINNED_ROW_DROP_RESULT,
drop: (item, monitor) => {
// Hover runs before React DnD publishes its latest pointer offset, and
// the HTML5 backend batches it on RAF. A quick release may arrive first.
// Drop observes the final offset; settle it before end commits the order.
moveAtPointer(item, monitor);
return PINNED_ROW_DROP_RESULT;
},
collect(monitor) {
return { handlerId: monitor.getHandlerId() };
},
hover(item, monitor) {
/* Recorded before any of the guards below, including the one for hovering
* the dragged row itself. Returning early there would leave an earlier
* external hover standing, and a drag that wandered onto a project and
* came back to its own position would be discarded as a filing action. */
markPinnedHover();
if (!item.key || item.key === entry.key || !ref.current) {
return;
}
const clientOffset = monitor.getClientOffset();
if (!clientOffset) {
return;
}
const rect = ref.current.getBoundingClientRect();
const swap = shouldSwapOnHover({
dragIndex: indexOfKey(item.key),
hoverIndex: indexOfKey(entry.key),
pointerY: clientOffset.y,
hoverTop: rect.top,
hoverBottom: rect.bottom,
});
if (!swap) {
return;
}
moveEntry(item.key, entry.key);
},
hover: moveAtPointer,
});
const [{ isDragging }, drag] = useDrag<PinnedRowDragItem, unknown, { isDragging: boolean }>({

View file

@ -506,6 +506,50 @@ describe('PinnedSection unified list', () => {
expect(mockUpdatePinnedOrder).not.toHaveBeenCalled();
});
it.each([
['crossed', 10, ['Second', 'First']],
['not crossed', 30, ['First', 'Second']],
] as const)(
'settles a fast drop with the midpoint %s before the hover frame',
(_name, dropY, labels) => {
renderSection([pinnedConvo('c1', 'First'), pinnedConvo('c2', 'Second')]);
const [target, source] = screen
.getAllByTestId('pinned-convo')
.map((node) => node.parentElement as HTMLElement);
jest.spyOn(target, 'getBoundingClientRect').mockReturnValue({
top: 0,
bottom: 40,
left: 0,
right: 100,
width: 100,
height: 40,
x: 0,
y: 0,
toJSON: () => ({}),
});
// The HTML5 backend batches hover callbacks on RAF. Keep that callback
// pending so only the accepted drop can settle the final pointer position.
jest.spyOn(window, 'requestAnimationFrame').mockImplementation(() => 0);
const drag = (node: HTMLElement, type: string, clientY: number) =>
fireEvent(node, new MouseEvent(type, { bubbles: true, clientX: 10, clientY }));
drag(source, 'dragstart', 60);
drag(source, 'dragover', 60);
drag(target, 'dragover', dropY);
drag(target, 'drop', dropY);
drag(source, 'dragend', dropY);
expect(itemLabels()).toEqual(labels);
if (dropY < 20) {
expect(mockUpdatePinnedOrder).toHaveBeenCalledWith(
['convo:c2', 'convo:c1'],
expect.anything(),
);
} else {
expect(mockUpdatePinnedOrder).not.toHaveBeenCalled();
}
},
);
/* An arrangement that arrives while the order is reconciling is held and
* written when the fresh order lands. The flush runs on every settle, so it
* has to stay quiet when there is nothing being held: reposting a committed

View file

@ -3,9 +3,49 @@ import { test } from 'node:test';
import { tmpdir } from 'node:os';
import { inspect } from 'node:util';
import assert from 'node:assert/strict';
import { mkdtemp, writeFile, readFile, rm } from 'node:fs/promises';
import { mkdtemp, writeFile, readFile, readdir, rm } from 'node:fs/promises';
import { runLighthouse } from './lighthouse/process.mts';
import { discardLighthouseTraces, sanitizeLighthouseArtifacts } from './lighthouse/artifacts.mts';
test('Lighthouse retains measured trace timings without publishing network logs or cookies', async (t) => {
const directory = await mkdtemp(path.join(tmpdir(), 'lighthouse-artifacts-'));
t.after(() => rm(directory, { recursive: true, force: true }));
const cookies = [
{ name: 'refreshToken', value: 'private-token-"quoted"' },
{ name: 'token_provider', value: 'local' },
{ name: 'short_cookie', value: '1' },
];
const header = cookies.map(({ name, value }) => `${name}=${value}`).join('; ');
await writeFile(path.join(directory, 'lhr-1-0.devtoolslog.json'), JSON.stringify({ header }));
await writeFile(
path.join(directory, 'lhr-1-0.trace.json'),
JSON.stringify({
traceEvents: [{ ts: 1231, dur: 51, args: { token: cookies[0].value, header } }],
}),
);
await writeFile(path.join(directory, 'lhr-1.report.html'), header);
await writeFile(path.join(directory, 'lhr-2-0.trace.json'), '{"partial":"private-token-');
sanitizeLighthouseArtifacts(directory, cookies);
assert.ok(!(await readdir(directory)).some((file) => file.endsWith('.devtoolslog.json')));
assert.ok(!(await readdir(directory)).includes('lhr-2-0.trace.json'));
const trace = await readFile(path.join(directory, 'lhr-1-0.trace.json'), 'utf8');
for (const { value } of cookies) {
assert.ok(!JSON.stringify(JSON.parse(trace).traceEvents[0].args).includes(value));
}
assert.equal(JSON.parse(trace).traceEvents[0].ts, 1231);
assert.equal(JSON.parse(trace).traceEvents[0].dur, 51);
assert.equal(await readFile(path.join(directory, 'lhr-1.report.html'), 'utf8'), '[redacted]');
});
test('a passing audit discards its traces and keeps its reports', async (t) => {
const directory = await mkdtemp(path.join(tmpdir(), 'lighthouse-traces-'));
t.after(() => rm(directory, { recursive: true, force: true }));
await writeFile(path.join(directory, 'lhr-1-0.trace.json'), '{}');
await writeFile(path.join(directory, 'lhr-1.report.json'), '{}');
discardLighthouseTraces(directory);
assert.deepEqual(await readdir(directory), ['lhr-1.report.json']);
});
for (const [failures, diagnostic, stderr] of [
[0, 'NO_NAVSTART', 'Runtime error encountered: Trace failed (NO_NAVSTART)'],

View file

@ -43,13 +43,19 @@ login page, spinner, or empty shell cannot pass.
2. Open a `.lighthouse/lhr-*.report.html` report. The console also prints API request
start/end times. A late request start suggests a browser dependency; a long
request suggests server work or serial database reads.
A failed audit keeps each run's measured `.lighthouse/lhr-*-0.trace.json` for
inspection in Chrome's Performance panel; a passing one discards them. Raw network
logs are removed and cookie values redacted before upload. Failed audits also save `.lighthouse/startup.cpuprofile` from a separate navigation to
identify expensive startup functions, including three seconds after the transcript
appears so later catalog callbacks are sampled. Profiling runs after the measured audits and
does not change their metrics or budgets.
3. Inspect the relevant path before changing the budget:
| Request / symptom | Code to inspect | Performance change this protects |
| ------------------------------------------- | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Config waits for repeated user lookups | `packages/api/src/app/service.ts`, `api/server/middleware/config/app.js` | [#14101](https://github.com/LibreChat-AI/LibreChat/pull/14101) |
| Message authorization and read run serially | `api/server/routes/messages.js`, `packages/api/src/middleware/messageValidation.ts` | [#14101](https://github.com/LibreChat-AI/LibreChat/pull/14101) |
| Messages wait for the file map | `client/src/data-provider/Messages/queries.ts`, `client/src/components/Chat/ChatView.tsx` | [#14188](https://github.com/LibreChat-AI/LibreChat/pull/14188) |
| Request / symptom | Code to inspect | Performance change this protects |
| ------------------------------------------- | ----------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Config waits for repeated user lookups | `packages/api/src/app/service.ts`, `api/server/middleware/config/app.js` | [#14101](https://github.com/LibreChat-AI/LibreChat/pull/14101) |
| Message authorization and read run serially | `api/server/routes/messages.js`, `packages/api/src/middleware/messageValidation.ts` | [#14101](https://github.com/LibreChat-AI/LibreChat/pull/14101) |
| Messages wait for the file map | `client/src/data-provider/Messages/queries.ts`, `client/src/components/Chat/ChatView.tsx` | [#14188](https://github.com/LibreChat-AI/LibreChat/pull/14188) |
| Startup repeats auth user reads | `api/server/controllers/AuthController.js`, `packages/api/src/auth/userDocCache.ts` | [#14187](https://github.com/LibreChat-AI/LibreChat/pull/14187), [#14343](https://github.com/LibreChat-AI/LibreChat/pull/14343), [#14747](https://github.com/LibreChat-AI/LibreChat/pull/14747) |
Reuse already-loaded user/config data. Start independent reads together, but keep

View file

@ -0,0 +1,49 @@
import fs from 'node:fs';
import path from 'node:path';
/** A passing audit needs no traces: at roughly 45 MB a run they only pay off when a budget fails. */
export function discardLighthouseTraces(directory: string): void {
for (const file of fs.existsSync(directory) ? fs.readdirSync(directory) : []) {
if (file.endsWith('.trace.json')) fs.rmSync(path.join(directory, file));
}
}
/** Keep measured traces, but never publish their raw network headers or session cookies. */
export function sanitizeLighthouseArtifacts(
directory: string,
cookies: { name: string; value: string }[],
): void {
const cookieHeader = cookies.map(({ name, value }) => `${name}=${value}`).join('; ');
const values = [...new Set(cookies.map(({ value }) => value).filter(Boolean))].sort(
(a, b) => b.length - a.length,
);
for (const file of fs.existsSync(directory) ? fs.readdirSync(directory) : []) {
const filename = path.join(directory, file);
if (file.endsWith('.devtoolslog.json')) {
fs.rmSync(filename);
continue;
}
if (!/\.(?:report\.(?:json|html)|trace\.json)$/.test(file)) continue;
let content = fs.readFileSync(filename, 'utf8');
if (cookieHeader) content = content.replaceAll(cookieHeader, '[redacted]');
if (file.endsWith('.trace.json')) {
// Walk string values so even short cookie values cannot corrupt numeric
// timestamps, JSON syntax or object keys. Network logs are omitted entirely.
try {
content = JSON.stringify(
JSON.parse(content, (_key, value: unknown) => {
if (typeof value !== 'string') return value;
let redacted = value;
for (const secret of values) redacted = redacted.replaceAll(secret, '[redacted]');
return redacted;
}),
);
} catch {
// An interrupted CLI may leave a partial trace. Never upload it raw.
fs.rmSync(filename);
continue;
}
}
fs.writeFileSync(filename, content);
}
}

View file

@ -5,6 +5,7 @@ import type Result from 'lighthouse/types/lhr/lhr';
import type { Cookie } from '@playwright/test';
import { runLighthouse } from './process.mts';
import { sanitizeLighthouseArtifacts } from './artifacts.mts';
/** Median budgets keyed by Lighthouse audit id. */
export type MedianBudgets = Record<string, number>;
@ -72,6 +73,7 @@ export async function auditPage({
`--extra-headers=${JSON.stringify({ Cookie: cookie })}`,
'--output=json',
'--output=html',
'--save-assets',
];
try {
@ -80,13 +82,7 @@ export async function auditPage({
await runLighthouse({ cli, flags, output, run, runs });
}
} finally {
// Lighthouse embeds extraHeaders in reports; keep disposable session cookies out of artifacts.
for (const file of fs.existsSync(directory) ? fs.readdirSync(directory) : []) {
if (!/\.report\.(json|html)$/.test(file)) continue;
const filename = path.join(directory, file);
const content = fs.readFileSync(filename, 'utf8');
fs.writeFileSync(filename, cookie ? content.replaceAll(cookie, '[redacted]') : content);
}
sanitizeLighthouseArtifacts(directory, cookies);
}
const reports = fs.readdirSync(directory).filter((file) => /^lhr-.*\.report\.json$/.test(file));

View file

@ -1,12 +1,46 @@
import fs from 'node:fs/promises';
import { expect, test } from '@playwright/test';
import type { Page } from '@playwright/test';
import { seedConversations, seedMessages } from '../specs/mock/db';
import { getE2EUser } from '../setup/user';
import { discardLighthouseTraces } from './artifacts.mts';
import { auditPage, lcpElement } from './audit';
const conversationId = '16390000-0000-4000-8000-000000000001';
const title = 'Lighthouse latency audit';
const transcriptMarker = 'Serial database latency transcript';
/** Capture a separate navigation after a failure; profiling never changes the measured audits. */
async function captureStartupProfile(page: Page, url: string) {
const profiler = await page.context().newCDPSession(page);
let started = false;
try {
await profiler.send('Network.enable');
await profiler.send('Network.setCacheDisabled', { cacheDisabled: true });
await profiler.send('Profiler.enable');
await profiler.send('Profiler.start');
started = true;
await page.goto(url);
await expect(
page.locator('.message-render').filter({ hasText: transcriptMarker }),
).toBeVisible();
// Optional catalog responses can arrive after the transcript. Keep a bounded
// post-ready sample so their callbacks are included in this diagnostic only.
await page.waitForTimeout(3_000);
} finally {
try {
if (started) {
const { profile } = await profiler.send('Profiler.stop');
await fs.mkdir('.lighthouse', { recursive: true });
await fs.writeFile('.lighthouse/startup.cpuprofile', JSON.stringify(profile));
}
} finally {
await profiler.detach();
}
}
}
test('serial database latency stays within web-vitals budgets', async ({ page, baseURL }) => {
const email = getE2EUser().email;
await seedConversations(email, [{ conversationId, title, updatedAt: new Date() }]);
@ -30,7 +64,17 @@ test('serial database latency stays within web-vitals budgets', async ({ page, b
await page.goto(url);
await expect(page.locator('.message-render').filter({ hasText: transcriptMarker })).toBeVisible();
const cookies = await page.context().cookies();
const reports = await auditPage({ url, cookies });
let reports: Awaited<ReturnType<typeof auditPage>>;
try {
reports = await auditPage({ url, cookies });
} catch (error) {
try {
await captureStartupProfile(page, url);
} catch {
console.warn('Startup CPU profile unavailable; retaining the original Lighthouse failure.');
}
throw error;
}
expect(reports, 'Lighthouse must produce all three reports').toHaveLength(3);
for (const report of reports) {
expect(report.finalDisplayedUrl, 'Do not measure a login redirect').toBe(url);
@ -39,4 +83,5 @@ test('serial database latency stays within web-vitals budgets', async ({ page, b
'The measured LCP must be the seeded transcript, not the shell or a spinner',
).toContain(transcriptMarker);
}
discardLighthouseTraces('.lighthouse');
});

View file

@ -297,7 +297,10 @@ test.describe('conversation management', () => {
await expect(page.getByRole('button', { name: 'Stop generating' })).toBeVisible();
const conversationUrl = page.url();
await openSidebar(page);
await page.getByRole('link', { name: 'New chat', exact: true }).click();
await page
.locator('#mobile-drawer')
.getByRole('link', { name: 'New chat', exact: true })
.click();
await expect(page).toHaveURL(/\/c\/new$/);
await expect(page.locator('#mobile-drawer')).toHaveCSS('visibility', 'hidden');
await openSidebar(page);

View file

@ -44,17 +44,17 @@ test.describe('classes that survive cn()', () => {
page,
}) => {
test.setTimeout(120_000);
await page.setViewportSize({ width: 390, height: 844 });
await page.goto('/c/new', { timeout: 30000 });
/** The header's overflow trigger is a `Button size="icon"`, whose recipe
* contributes `size-10`, with `size-9` written by the call site. `cn()` has
* to keep the caller's: 1.9.1 knows no `size-*` group, so it keeps both,
* and `.size-10` is emitted after `.size-9` — the button silently renders
* at 40px instead of the 36px the header lays out for. It is `md:hidden`,
* so the assertion reads the computed box, which is defined whether or not
* the viewport shows it. */
* at 40px instead of the 36px the header lays out for. The overflow menu
* mounts on mobile, so exercise its visible viewport. */
const trigger = page.getByTestId('header-overflow-menu');
await expect(trigger).toBeAttached({ timeout: 30000 });
await expect(trigger).toBeVisible({ timeout: 30000 });
await expect(trigger).toHaveClass(/\bsize-9\b/);
await expect(trigger).not.toHaveClass(/\bsize-10\b/);

View file

@ -105,10 +105,6 @@ export async function removePins(pins: SeededPin[]): Promise<void> {
await deleteConversations(pins.map((pin) => pin.conversationId));
}
/** Resolves once the page has run the animation frame after this call. */
const nextAnimationFrame = (page: Page): Promise<void> =>
page.evaluate(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));
/**
* Drags one row onto a point inside another and releases there.
*
@ -157,14 +153,12 @@ export async function dragRowOnto(
* be rendering the previous one; a real hand keeps sending events. These
* repeats are that, bounded.
*
* react-dnd delivers hover once per animation frame, and judges the release
* against the offset the last delivered hover recorded. Every move here can
* land inside a single frame, which leaves the release judged against where
* the pointer was a frame earlier: short of the row's midpoint, and so no
* swap. Each repeat therefore waits for the frame that delivers it. */
* react-dnd delivers hover once per animation frame, so these moves and the
* release can all land inside one frame, before any hover has seen the final
* position. The drop handler settles that position itself; releasing without
* waiting for a frame keeps that fast-release path under test. */
for (let settle = 0; settle < 3; settle += 1) {
await page.mouse.move(endX, endY + settle - 1, { steps: 2 });
await nextAnimationFrame(page);
}
await page.mouse.up();
}

View file

@ -32,7 +32,13 @@ const probe = (page: Page, className: string) =>
const elapsedReading = (page: Page) => messagesView(page).getByTestId('stream-elapsed');
const readSweep = (page: Page) =>
elapsedReading(page).evaluate((element) => {
page.evaluate(() => {
// Streaming can replace the footer between locator resolution and evaluate.
// Resolve the current node and read its styles in the same browser task.
const element = document.querySelector(
'[data-testid="messages-view"] [data-testid="stream-elapsed"]',
);
if (!element) return null;
const style = getComputedStyle(element);
return {
animationName: style.animationName,
@ -81,17 +87,16 @@ test.describe('shared part classes', () => {
expect(run.ok()).toBeTruthy();
await expect(elapsedReading(page)).toBeVisible({ timeout: 15_000 });
const sweep = await readSweep(page);
expect(sweep.animationName).toBe('shimmer');
expect(sweep.backgroundClip).toBe('text');
expect(Number(sweep.dipAlpha)).toBeLessThan(1);
await expect(elapsedReading(page)).toHaveCSS('animation-name', 'shimmer');
await expect(elapsedReading(page)).toHaveCSS('background-clip', 'text');
await expect.poll(async () => Number((await readSweep(page))?.dipAlpha)).toBeLessThan(1);
await page.emulateMedia({ contrast: 'more' });
await expect(page.locator('html.high-contrast')).toHaveCount(1, { timeout: 5_000 });
await expect.poll(async () => (await readSweep(page)).dipAlpha).toBe('1');
await expect.poll(async () => (await readSweep(page))?.dipAlpha).toBe('1');
await page.emulateMedia({ contrast: null });
await page.emulateMedia({ reducedMotion: 'reduce' });
await expect.poll(async () => (await readSweep(page)).animationName).toBe('none');
await expect(elapsedReading(page)).toHaveCSS('animation-name', 'none');
});
});

View file

@ -80,12 +80,12 @@ test.describe('Tailwind v4 rendering', () => {
* sites the upgrade touched: v3's `blur-sm` was 4px, v4's is 8px, and the
* 4px step is now called `blur-xs`. The scrim is always mounted, so its
* filter is readable while it is still transparent. */
const scrim = page.locator('#artifact-viewer [role="status"]').first();
/** The lazy tabs also render a status while loading; only the persistent scrim has aria-hidden. */
const scrim = page.locator('#artifact-viewer [role="status"][aria-hidden]');
await expect(scrim).toBeAttached({ timeout: 30000 });
const { backdropFilter } = await computedStyles(scrim, ['backdropFilter']);
expect(backdropFilter).toBe('blur(4px)');
expect(backdropFilter).not.toBe('blur(8px)');
await expect(scrim).toHaveCSS('backdrop-filter', 'blur(4px)');
await expect(scrim).not.toHaveCSS('backdrop-filter', 'blur(8px)');
} finally {
await deleteMessagesByConversation([conversationId]);
await deleteConversations([conversationId]);

View file

@ -1,18 +1,21 @@
import fs from 'fs';
import os from 'os';
import path from 'path';
import { spawn } from 'node:child_process';
import { spawn, execFileSync } from 'node:child_process';
import type { ChildProcess } from 'node:child_process';
import { createReaper } from './reaper';
let base: string;
let children: ChildProcess[];
function run(command: string): ChildProcess {
return spawn('bash', ['-c', command], {
const child = spawn('bash', ['-c', command], {
detached: true,
stdio: 'ignore',
env: { PATH: process.env.PATH },
});
children.push(child);
return child;
}
function isGone(pid: number): boolean {
@ -21,6 +24,15 @@ function isGone(pid: number): boolean {
} catch {
return true;
}
if (process.platform !== 'linux') {
try {
return execFileSync('ps', ['-o', 'stat=', '-p', String(pid)], { encoding: 'utf8' })
.trim()
.startsWith('Z');
} catch {
return true;
}
}
try {
const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8');
return stat.slice(stat.lastIndexOf(')') + 2, stat.lastIndexOf(')') + 3) === 'Z';
@ -37,10 +49,19 @@ async function waitFor(condition: () => boolean): Promise<void> {
}
beforeEach(async () => {
children = [];
base = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'lc-reaper-'));
});
afterEach(async () => {
for (const child of children) {
if (typeof child.pid !== 'number') continue;
try {
process.kill(-child.pid, 'SIGKILL');
} catch {
// A successful test has already terminated this group.
}
}
await fs.promises.rm(base, { recursive: true, force: true });
});
@ -56,7 +77,11 @@ describe('createReaper', () => {
test('escalates to SIGKILL when the tree ignores SIGTERM', async () => {
const pidFile = path.join(base, 'stubborn.pid');
const child = run(`trap '' TERM; echo $$ > "${pidFile}"; sleep 30`);
// Publish only after the PID is written: file existence alone can expose an
// empty file between shell redirection and echo, which Number('') turns into 0.
const child = run(
`trap '' TERM; echo $$ > "${pidFile}.tmp"; mv "${pidFile}.tmp" "${pidFile}"; sleep 30`,
);
await waitFor(() => fs.existsSync(pidFile));
const rootPid = Number((await fs.promises.readFile(pidFile, 'utf8')).trim());
createReaper(child, 200).reap();
@ -69,7 +94,7 @@ describe('createReaper', () => {
test('sweep reaps a group that outlived a clean root exit', async () => {
const pidFile = path.join(base, 'worker.pid');
const child = run(
`bash -c 'trap "" TERM; echo $$ > "${pidFile}"; sleep 30' >/dev/null 2>&1 & exit 0`,
`bash -c 'trap "" TERM; echo $$ > "${pidFile}.tmp"; mv "${pidFile}.tmp" "${pidFile}"; sleep 30' >/dev/null 2>&1 & exit 0`,
);
const reaper = createReaper(child, 200);
const closed = new Promise<void>((resolve) => child.once('close', () => resolve()));