diff --git a/client/src/components/Chat/Header.tsx b/client/src/components/Chat/Header.tsx index c4202f7ae7..69484fdd39 100644 --- a/client/src/components/Chat/Header.tsx +++ b/client/src/components/Chat/Header.tsx @@ -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} /> )} - + {/* 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) && ( + + )}
{trace.show && } { 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(
); + expect(headerMenu).not.toHaveBeenCalled(); + }); + + test('retains mobile action state when the viewport returns to desktop', () => { + headerMenu.mockImplementation(() => ); + const { rerender } = render(
); + expect(screen.queryByRole('textbox', { name: 'Menu draft' })).not.toBeInTheDocument(); + mockSmallScreen.current = true; + rerender(
); + const input = screen.getByRole('textbox', { name: 'Menu draft' }); + fireEvent.change(input, { target: { value: 'unsaved dialog state' } }); + mockSmallScreen.current = false; + rerender(
); + 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(
); + 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(
); diff --git a/client/src/components/Conversations/PinnedSection.tsx b/client/src/components/Conversations/PinnedSection.tsx index 0059f46876..688de3f462 100644 --- a/client/src/components/Conversations/PinnedSection.tsx +++ b/client/src/components/Conversations/PinnedSection.tsx @@ -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(null); const hasHoverPointer = useMediaQuery('(hover: hover)'); + const moveAtPointer = ( + item: PinnedRowDragItem, + monitor: DropTargetMonitor, + ) => { + /* 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({ /* 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({ diff --git a/client/src/components/Conversations/__tests__/PinnedSection.spec.tsx b/client/src/components/Conversations/__tests__/PinnedSection.spec.tsx index 5cb58fcdf0..99cb1b3b07 100644 --- a/client/src/components/Conversations/__tests__/PinnedSection.spec.tsx +++ b/client/src/components/Conversations/__tests__/PinnedSection.spec.tsx @@ -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 diff --git a/e2e/lighthouse.test.mts b/e2e/lighthouse.test.mts index 8c4f55a3fc..cdcfacbb5a 100644 --- a/e2e/lighthouse.test.mts +++ b/e2e/lighthouse.test.mts @@ -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)'], diff --git a/e2e/lighthouse/README.md b/e2e/lighthouse/README.md index fdab176251..01667341b7 100644 --- a/e2e/lighthouse/README.md +++ b/e2e/lighthouse/README.md @@ -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 diff --git a/e2e/lighthouse/artifacts.mts b/e2e/lighthouse/artifacts.mts new file mode 100644 index 0000000000..0745316e10 --- /dev/null +++ b/e2e/lighthouse/artifacts.mts @@ -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); + } +} diff --git a/e2e/lighthouse/audit.ts b/e2e/lighthouse/audit.ts index 28f6b3cbff..4fd27ab5e8 100644 --- a/e2e/lighthouse/audit.ts +++ b/e2e/lighthouse/audit.ts @@ -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; @@ -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)); diff --git a/e2e/lighthouse/load.spec.ts b/e2e/lighthouse/load.spec.ts index bb11fd57a1..b03b8d4a2b 100644 --- a/e2e/lighthouse/load.spec.ts +++ b/e2e/lighthouse/load.spec.ts @@ -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>; + 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'); }); diff --git a/e2e/specs/mock/conversation-management.spec.ts b/e2e/specs/mock/conversation-management.spec.ts index 48aabc8446..dc27111996 100644 --- a/e2e/specs/mock/conversation-management.spec.ts +++ b/e2e/specs/mock/conversation-management.spec.ts @@ -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); diff --git a/e2e/specs/mock/scenarios/dropped-classes.spec.ts b/e2e/specs/mock/scenarios/dropped-classes.spec.ts index dfc2a89d1e..b6cb634c26 100644 --- a/e2e/specs/mock/scenarios/dropped-classes.spec.ts +++ b/e2e/specs/mock/scenarios/dropped-classes.spec.ts @@ -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/); diff --git a/e2e/specs/mock/scenarios/pinned.helpers.ts b/e2e/specs/mock/scenarios/pinned.helpers.ts index 1c351732a1..2d981d13dd 100644 --- a/e2e/specs/mock/scenarios/pinned.helpers.ts +++ b/e2e/specs/mock/scenarios/pinned.helpers.ts @@ -105,10 +105,6 @@ export async function removePins(pins: SeededPin[]): Promise { await deleteConversations(pins.map((pin) => pin.conversationId)); } -/** Resolves once the page has run the animation frame after this call. */ -const nextAnimationFrame = (page: Page): Promise => - page.evaluate(() => new Promise((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(); } diff --git a/e2e/specs/mock/scenarios/shared-part-classes.spec.ts b/e2e/specs/mock/scenarios/shared-part-classes.spec.ts index df256cab58..eccca90c47 100644 --- a/e2e/specs/mock/scenarios/shared-part-classes.spec.ts +++ b/e2e/specs/mock/scenarios/shared-part-classes.spec.ts @@ -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'); }); }); diff --git a/e2e/specs/mock/scenarios/v4-rendering.spec.ts b/e2e/specs/mock/scenarios/v4-rendering.spec.ts index 7631e64c04..4b1f8b7205 100644 --- a/e2e/specs/mock/scenarios/v4-rendering.spec.ts +++ b/e2e/specs/mock/scenarios/v4-rendering.spec.ts @@ -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]); diff --git a/packages/api/src/agents/hooks/reaper.spec.ts b/packages/api/src/agents/hooks/reaper.spec.ts index 8898795884..c678848522 100644 --- a/packages/api/src/agents/hooks/reaper.spec.ts +++ b/packages/api/src/agents/hooks/reaper.spec.ts @@ -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 { } 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((resolve) => child.once('close', () => resolve()));