* 🧬 fix: Collapse Radix Layer Packages to One Copy
Radix coordinates nested layers and focus scopes through module-level state,
so a dialog and a popover inside it cooperate only while they import the same
copy of `react-dismissable-layer` / `react-focus-scope`. This tree had four
and three of them:
dialog -> react-dialog/node_modules/… 1.0.2 (exact pin)
select -> react-select/node_modules/… 1.1.10
menu -> react-menu/node_modules/… 1.1.0
hover -> hoisted 1.0.5
Split that way, a popover never learns the dialog disabled body pointer
events and the dialog's focus trap is never paused, so in-dialog selects and
hover cards are inert and keyboard-dead (#15738). The exact `1.0.2` pin on
`react-dialog` and `react-alert-dialog` came from #11023, which downgraded
them from ^1.1.15 to fix modal tooltip and dropdown regressions — the same
split seen from the other side, when the dialog was the new package and
everything else was old.
Unpinning both and refreshing the other Radix packages inside their existing
carets collapses the tree to one copy of each. No `overrides` entry: the
resolution stands on its own, and pinning transitive versions would only hide
the next split. `radixLayers.spec.ts` reads the lockfile and fails if either
package is ever nested again; `dialogPopoverFocus.spec.tsx` asserts the
behaviour that invariant exists for — a portaled option holding focus inside
a dialog, which fails on the old tree and passes on this one.
Verified with a real install in a worktree: one copy of each resolved from
dialog, select and hover-card alike; `packages/client` 46 suites / 476 tests
and `client` 323 suites / 3201 tests green; both workspaces typecheck.
Needs a manual pass over the app's modals before merge — what #11023 was
guarding cannot be proven by jsdom.
* 🍞 fix: Give Escape Back to the Dialog Under a Toast
Radix routes Escape to the highest dismissable layer only, and `Toast.Root`
registers one — mounted after whatever dialog is already open. Splitting
`react-dismissable-layer` into per-package copies hid this: toasts and dialogs
were never in the same stack. Collapsing them to one copy puts a status toast
above every open dialog, and it eats the Escape meant for the dialog beneath.
Measured in the running app (mock e2e, instrumented): the dialog's own
`onEscapeKeyDown` was never called, the layer above it was
`<li class="toast-root" data-radix-collection-item>`, and a SECOND Escape
closed the dialog. That is `agent-skills.spec.ts:709`, which failed
deterministically here across three attempts.
The frontmost open dialog now takes Escape back while a toast is present,
closing through a hidden `Dialog.Close` so controlled and uncontrolled dialogs
behave alike. Scoped tightly: no toast on screen leaves Radix's arbitration
untouched, and only the frontmost dialog acts, so an inner dialog still closes
alone.
The toast is matched whatever its `data-state`. A toast that has begun closing
keeps its layer registered until the exit animation ends, and that is exactly
the case that failed — the first attempt keyed on `[data-state="open"]` and
missed it, which the instrumentation caught (`FB toast= null allLis= 1`).
`agent-skills.spec.ts` now passes locally on the deduped tree: 4 passed.
Regression test verified to fail with the fix reverted.
* 🚪 fix: Close the MCP Menu With the Dialog It Opened
Ariakit takes Escape for a menu only when the event target is the menu, its
trigger, or `body`:
if (event.key !== "Escape") return;
if (event.defaultPrevented) return;
...
if (isElement(target) && target.tagName === "BODY") return true;
if (contains(dialog, target)) return true;
if (contains(disclosureElement, target)) return true;
return false; // ariakit dialog.tsx:496-517
While the MCP config dialog holds focus none of those is true, so the Escape
that closes the dialog leaves the menu open behind it — and `disabled={isOpen}`
on the trigger then makes it unclickable. The reader is stranded with a menu
they cannot reach and a button they cannot press; `mcp-oauth-readiness` times
out clicking it, three tests over.
Keyed on the dialog CLOSING, not opening. The first attempt closed the menu as
the dialog opened and broke a fourth test that reads the server rows from the
still-mounted menu underneath (`unmountOnHide` deletes them):
`element(s) not found`. Closing on the way back out leaves that untouched.
Local mock e2e on the deduped tree: `mcp-oauth-readiness` 5 passed (was 2/5),
`agent-skills` + `mcp` 5 passed, `client` 3204 tests green, typecheck clean.
* 🛡️ fix: Keep the Escape Fallback Inside Its Lane
Codex found three, all real.
**P1 — the fallback overruled the guards it should obey.** Any Escape while a
toast was up clicked the dialog's close button, including when a select inside
the dialog owned that Escape (WCAG 2.1.1) or when another layer had already
answered it. A reader closing a listbox would have lost the whole dialog and
anything unsaved in it. It now bails on `event.defaultPrevented` and on the
same popup conditions the Radix-provided handler honours — extracted into one
`escapeBelongsToPopup` helper both call, so they cannot drift apart.
**P2 — the frontmost check read inline z-index only.** `ImagePreview` is a raw
`DialogPrimitive.Content` carrying `z-[250]` as a CLASS, so it scored zero and
the My Files dialog underneath was mistaken for the frontmost — Escape in the
preview would have closed it too. Ranking now reads the resolved
`getComputedStyle().zIndex`.
**P2 — the published contract did not carry the singleton.** `@librechat/client`
still admitted `react-toast@1.1.5` and `react-popover@1.0.7`, which depend on
the older dismissable-layer/focus-scope line, so a consumer could reassemble
the very split this PR removes. Radix minimums raised to the versions the
lockfile resolves; the tree still holds exactly one copy of each.
Three regression tests, each verified to fail against the pre-fix component.
`packages/client` 484 tests, `client` 3204 tests, both typecheck clean, local
mock e2e `agent-skills` + `mcp-oauth-readiness` 9 passed.
* 🎚️ fix: Let the Consumer and the Alert Dialog Have Their Say
Two more from codex, both real.
The fallback never ran the dialog's own `onEscapeKeyDown`. Radix calls that
only for the highest layer, which the toast is — so a dialog whose consumer
cancels Escape (`event.preventDefault()`) closed anyway, taking whatever was
in it. The fallback now invokes the supplied handler and honours the
cancellation, exactly as the Radix path does.
The frontmost ranking looked only for `role="dialog"`. `OGDialogContent` is
also used as an alert dialog — the shared-link delete confirmation
(`SharedLinkButton.tsx:426`) — so its content was never found, `frontmost`
stayed null, and the fallback declined to act: that confirmation still needed
two Escapes. Alert dialogs are ranked too.
Two more regression tests, both verified to fail against the previous version.
`packages/client` 486 tests, `client` 3204 tests, typecheck and static checks
clean.
Social providers that do not return a profile picture cause sign-in to
fail when a non-local file strategy is configured. `handleExistingUser`
and `createSocialUser` pass the incoming `avatarUrl` straight to
`resizeAvatar`, which throws "Invalid input type. Expected URL, Buffer,
or File." on null. `socialLogin` catches that error and forwards it to
the Passport callback, so authentication fails instead of the avatar
simply being skipped.
Apple is affected by definition: `appleStrategy.js` sets
`avatarUrl: null` with the comment "Apple does not provide an avatar
URL". Any Google or OIDC account without a picture reaches the same path.
Guard the three call sites so that a missing avatar skips avatar
processing and leaves the rest of the sign-in flow untouched.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* 🎯 fix: Keep Scroll-to-Bottom Clear of Composer Panels
The `ask_user_question` popover and the tool-approval review float up from
the composer (`bottom-28`, measured from the composer's bottom) while the
scroll-to-bottom control floats up from the thread's edge (20px above the
composer's top), so the two meet on the panel's footer whenever the composer
is taller than 92px — it is 96px empty. Each panel now registers itself as
an open composer overlay for exactly as long as it renders, and the control
stands down while any is open. The in-flight steer stack keeps its existing
lift: it publishes its height and stays short enough for that to read well.
The overlap also exposed a stagger that was there all along: the control sat
flush with the column edge at 40px, while every composer control is 36px on
the `theme-control` tokens and Send is inset `mr-2`. It now shares Send's
inset and geometry, so the two read as one rail rather than two edges.
`ScrollButton` moves out of `MessagesView` into its own module so the gate
can be exercised against a stubbed IntersectionObserver.
* 🎯 refactor: Keep the Scroll Control on the Shared Button and Host Surface
Codex round 1. The control goes back on the shared `Button`, which gains the
composer row's geometry as `size="icon-theme"` (`size-theme-control p-0`)
and `shape="round"` (`rounded-theme-control-round`) instead of a feature-
local class list. The overlay count and its registration hook move out of
the global store into `Chat/Input/overlay.ts`, since only chat panels write
it and only the chat thread reads it. The extracted `ScrollButton` and
`ScrollToBottom` no longer read `showScrollButton` / `maximizeChatSpace`
from the app store: `MessagesView` takes both from the host's `ChatSurface`
and passes them down, and the subagent activity host does the same for the
column width.
`dev` is red on `Tests: @librechat/client`. The comment I added in #15738
cites the pull request that pinned `react-dialog` as `(#11023)`, and the
shared-component guardrail's `/#[0-9a-f]{3,8}\b/i` reads five hex-range
digits as a color. Every branch built on dev inherits the failure.
Fixed on both sides: the comment cites the number without the `#`, and the
pattern now matches only CSS-legal hex lengths (3, 4, 6, 8), so no issue
reference can trip it again. The guardrail keeps its teeth — the same test
now asserts it still matches `#fff`, `#ff0000` and `#aabbccdd`, and leaves
"closes #15738" alone.
Also relaxes one assertion in `popoverLayering.spec.tsx`: it pinned the
ABSENCE of an inline `pointer-events` on a hover card outside any dialog,
which is Radix's to set, not the hook's. Whether a sibling select's
`disableOutsidePointerEvents` reaches that card depends on whether the two
share a copy of `react-dismissable-layer` — a packaging fact that changes
under #15742. The test now asserts only what the hook itself contributes.
* 🕰️ fix: Settle Parts the Response Has Moved Past
Two live treatments outlived what they were reporting on: a reasoning block
kept shimmering with its thought peek scrolling, and a question group kept
reading "Asking 1 question", both long after the response moved on.
**Reasoning.** Activity phases split one response into several bodies, and
`PartWithContext` handed `Part` the per-body `isLastPart` as `isLast` — while
`showCursor` was correctly the body-level `isLast` AND'd with it. So every
settled phase's trailing part claimed to be the live one, and `Reasoning`
shimmers on `isSubmitting && isLast`. Both props now carry the same verdict:
the part holds the message's cursor. Grouped and parallel-lane paths already
AND'd the two, so only the phase path changes; `ToolCallGroup`'s own `isLast`
gets the same treatment for consistency.
**Questions.** `ask_user_question` writes no output onto its `tool_call` part
until the turn finalizes, so `allCompleted` stayed false and the header held
the present tense for the rest of the turn. Position cannot settle this one:
a LIVE pause appends its interactive card AFTER the group, so the group is
not the message's last part exactly while the question is open — the three
label tests that failed when I tried it that way are what caught it. The
answer itself is the signal, read through the same locally-recorded fallback
the durable record card uses, because the streaming handler's message copy
can overwrite the optimistic output stamp mid-stream.
Both regression tests were verified to fail with their fix reverted.
* 🫥 fix: Settle the Group Glyph With Its Label
The header's glyph and stacked icons pulsed on their own
`!allCompleted && isSubmitting`, so an answered question group would read
"Asked 1 question" while still pulsing beside it. Label, glyph and icon
animation now read one `isGroupLive` verdict — they are a single control.
Found by auditing the rest of the class rather than stopping at the two
reported symptoms. The other live treatments in message content are gated on
a per-part signal that does settle: `Summary` on its own `summarizing` flag,
the interim skill cards on `hasRealContent`, `SubagentCall` on its progress
status, and every tool card on `resolveToolCallPhase`, whose whole-message
`isSubmitting` fallback only applies where no `runStepStatus` was emitted.
* 🪟 fix: Lift Portaled Popovers Over the Dialog They Belong To
`Select`, `Combobox` and `HoverCard` portal their content to the body and
carry the shadcn default layer — `z-40` / `z-50`. `OGDialogContent` sits at
140 over an opaque overlay at 130, so inside a dialog those popovers open
*behind* both: invisible and unclickable, while the dialog around them keeps
taking clicks. Reported for the Run Code tool settings, whose two environment
selects and help hovers moved into that dialog in #15722.
`usePopoverZIndex()` already solves this for `DropdownMenu`, `DropdownPopup`,
`Tooltip` and `ControlCombobox`. These three could not simply adopt it: four
consumers raise `HoverCardContent` to `z-[999]` by class to clear the legacy
`Dialog`, and an unconditional inline z-index would silently outrank them. So
`useNestedPopoverZIndex()` returns the layered value only inside a dialog and
`undefined` outside it, leaving the CSS layer — and every override of it —
exactly as it was.
The regression test asserts the popover's own inline z-index against the
dialog's own constant, and pins the unchanged behaviour outside a dialog.
Verified failing with the fix removed. `Combobox` carries the identical
one-line change without a case of its own: no dialog hosts one today, and
driving Radix Select's open state through jsdom hangs the suite.
* 🖱️ fix: Restore Pointer Events on In-Dialog Popovers
Codex was right on both counts, and they share one cause: the app carries
THREE copies of `@radix-ui/react-dismissable-layer` (and two of
`react-focus-scope`), because `react-dialog` is pinned at 1.0.2 (#11023)
while `react-select` and `react-hover-card` resolve to their own newer ones.
Radix coordinates nested layers through module-level state, so layers from
different copies never see each other: the dialog parks
`pointer-events: none` on the body and the popover from another copy is never
granted the `auto` that Radix would otherwise give it.
Measured in jsdom, dialog open, popover open:
as installed body none / card "" → inert
deduped body none / card auto → interactive
`useNestedPopoverZIndex` becomes `useNestedPopoverStyle`, carrying
`pointer-events: auto` alongside the layered z-index — the same trade
`DropdownPopup` already makes for Ariakit menus. Clicking a portaled option
does not dismiss the dialog: React portals bubble through the React tree, so
the dialog's own "pointer down inside" check still sees it (asserted).
A select gets `auto` from its own copy either way, since it disables outside
pointer events for its own stack; the hover card is the one that was inert.
Focus is the half this cannot reach: the dialog's focus trap lives in yet
another copy's scope stack, so a nested popover's scope never pauses it and
keyboard selection is still lost. Deduping the packages fixes that too —
verified by re-running the same probe with both copies mapped to one — but
that means unpinning `react-dialog`, which is what #11023 pinned to fix modal
tooltip and dropdown regressions. Left for a follow-up that can be validated
in a browser.
The code approval selector was the only chat control built on the shadcn
`DropdownMenu` primitives — a borderless ghost button and default radio
dots beside a row of bordered composer pills, with per-item text styled
by hand.
- Rebuild the control on the composer's own menu language (Ariakit menu +
`TooltipAnchor`), matching `MCPSelect`: a pill trigger with a rotating
chevron, and a `bg-presentation` popover whose options carry an icon,
a description and a check on the selected row, as the model and MCP
menus already do.
- Extract the pill appearance into `composerControlClasses()` beside
`composerSurfaceClasses()` in `@librechat/client`, and consume it from
`CheckboxButton` and `MCPSelect`, which each carried their own copy of
the same border/radius/height/elevation decision.
- Replace the raised hand with a pair that reads as one question — a
document with a question mark for "ask", a document with a pen for
"accept edits" — leaving the shield to the pending review button that
sits in the same row.
Roles, keyboard behaviour and the stored `codeApprovalMode` are
unchanged: the trigger keeps its `code-approval-mode` test id and
`aria-expanded`, and the options stay `menuitemradio`.
The retry navigation reserves its width in the message footer whether or not
hover has revealed it, so a response with siblings rendered the elapsed reading
indented past the column the streaming dot had just vacated. Rendering the
reading ahead of the navigation in all three row renderers puts it back on that
column start, in the streaming footer and in the flat thread alike.
* feat: Enable Full Access for BYOM Coding 🛫
* test: Preserve endpoint policy under Full Access
* fix: Gate Full Access on expected root agent metadata
* 🗜️ feat: Manual Context Compaction as a Summarize-Only Turn
Adds a user-triggered "Compact context" action that summarizes the active
branch on demand. The compaction is an ordinary agent turn: the client
submits it through the normal chat pipeline with `compact: true`, the
controller hangs it off the branch's leaf instead of creating a user
message, and the agent client runs the graph summarize-only (the SDK's new
`summarizeOnly` input), so the summary streams into the response
placeholder under the leaf exactly like the automatic detour's and is
persisted as the boundary every later turn starts from.
Nothing new is needed for job registration, billing, abort, persistence,
or the usage snapshot: the run emits the same summary step and post-summary
context snapshot the automatic path already emits, and the response message
carries the summary part plus the `summaryUsedTokens` baseline the gauge
reads. The controller validates the request (existing conversation, a real
leaf, summarization enabled, no edit/regenerate/continue combination) and
answers 409 when the leaf is already a bare summary.
Client-side the submission borrows the regenerate shape — no new user
bubble, the placeholder parents onto the leaf — while the wire payload
drops `isRegenerate` so the server never treats it as a regenerated user
turn. The action sits in the context-usage popover, gated by the same
`summarization.enabled` switch as the automatic detour.
* 🗜️ fix: Localize a Compaction That Cannot Run
A compaction the graph could not attempt (summarization disabled, the
instructions already exceeding the budget, or an explicit recency window
covering the whole conversation) rejects with the SDK's
`ManualSummarizationSkippedError`, which rendered as the generic admin
error. It now maps to a typed `compaction_skipped` payload with the reason,
and a run that ends with neither a summary nor a recorded error fails as
`compaction_failed`; the Error component localizes both. A run that already
recorded why it stopped keeps that error part instead of failing twice.
* 🗜️ fix: Anchor a Compaction on the Leaf Everywhere It Is Read
Review round 1.
- The client sent the leaf's parent as `parentMessageId`, which the
controller treats as the anchor, so the summary would have skipped the
latest reply and landed as its sibling. The leaf's own id is now both the
placeholder's parent and the server-side anchor.
- A compaction has no user message of its own, and every consumer of the
job's user-message slot now knows it: the error path parents its row on
the loaded anchor and never upserts the leaf, and the job records the
regenerate shape so a reconnecting client rebuilds the turn under the
leaf instead of recreating it as a user message.
- The controller no longer reads the anchor before the branch is loaded;
`BaseClient` validates it against the history it loads anyway and
answers 404 for a missing leaf or a typed `nothing_to_summarize` for a
finished compaction. That predicate is shared through the data provider
and ignores a summary still streaming or one that failed, so an
interrupted compaction can be retried.
- A compaction never consumes files staged in the composer, the action is
shown only when the server advertises `compactionEnabled`, and the
in-flight marker is feature-local Jotai state rather than a read of the
Recoil submission store.
* 🗜️ fix: Keep a Compaction Turn to Its Summary
Review round 2, plus the class it belongs to. A compaction submits no user
turn, so nothing that keys off one may run: the memory pass no longer runs
over the history (it would have spent a model call and could repeat memory
writes), and skill primes are no longer injected into the transcript the
run is about to summarize.
The client's in-flight marker is also reconciled on mount: a compaction
that finished while the view was away left the marker set, and the next
ordinary turn in that conversation would have shown as compacting.
* 🧹 chore: Sort Imports in the Compaction Hook Spec
* 🔧 chore: Update @librechat/agents dependency to version 3.8.1 in package-lock.json and package.json files
* 🕓 style: Move the Queued-Message Hint Into a Hover Tooltip on the Clock Icon
"Sends when this response finishes" rendered as a caption row under the
queued chips for as long as a run was pending, costing composer height
for a single reassurance. The clock icon of each queued row now carries
that sentence as a hover tooltip and as its accessible name, and the
caption row is gone. Nothing else about the row changes: warning states
keep their triangle, and the hint disappears with the run as before.
* ⌨️ fix: Give the Queued-Hint Clock an Explicit Tab Stop and Focus Ring
The tooltip anchor was already focusable through Ariakit's Focusable
default, and opens on focus-visible, but nothing said so and no ring
showed where focus was. Make the tab stop explicit, add the same
focus-visible ring the row's buttons use, and prove the keyboard path
with a test. The hover test now allows for Ariakit's show timer on a
loaded CI shard, which is what failed the first run. Codex round 1 (P2)
on #15706.
* 🧪 test: Move the Pointer Between Coordinates Before Expecting the Queued Hint Tooltip
Ariakit's hover detector treats a pointer as moving only when consecutive
mousemove events differ in screen coordinates; its NODE_ENV=test shortcut
does not apply under the CI runner's NODE_ENV, which is why the hover test
passed locally and failed in the shard. Two moves at distinct coordinates
make the test environment-independent; the keyboard test was already
deterministic.
#15691 paired every read of `AgentCapabilities.execute_code` / `file_search`
with its role grant, and skipped `execute_code` from the resend-file priming
when `RUN_CODE` was denied. It left the `file_search` half: the grant was not
available inside `initializeAgent`, so a role denied `FILE_SEARCH` still had
its prior-turn search files re-hydrated on every resend.
Priming is not free. The files are fetched, `updateFilesUsage` bumps their
counters, and `primeResources` builds `tool_resources.file_search` — all for
a tool the loader is about to drop. A deployment with the capability off paid
the same cost.
`InitializeAgentParams.fileSearchAvailable` carries the capability AND the
grant, resolved from the same single `resolveToolRoleGrants` read that already
answers `codeEnvAvailable`, so pairing the second flag costs no extra role
lookup. Every initializer that resolves grants forwards it: the chat path and
its handoff, added-convo and discovery hand-offs, both API routes, and the
OpenAI-compatible embedder route. Absent leaves priming unconditional, so an
embedder that resolves no grant keeps its current behavior.
The loop that selected the resend tool resources becomes
`resolveResendToolResources`, which makes both halves of the gate testable
rather than reachable only through a full agent initialization.
The memory agent is untouched: it passes no `conversationId`, so it never
reaches this priming.
Co-authored-by: Claude <noreply@anthropic.com>
* fix: enforce FILE_SEARCH role permission server-side
The FILE_SEARCH role permission is stored, served by GET /api/roles/:name and
settable through the admin API, but nothing ever checks it.
PermissionTypes.FILE_SEARCH occurs zero times under api/server; the three
occurrences in @librechat/api are all in the interface-to-role sync, which
writes the permission rather than checking it.
Measured on v0.8.8-rc1 and confirmed unchanged in rc2: a user whose role has
FILE_SEARCH.USE = false can still upload a document with
tool_resource=file_search and gets 200 with "embedded": true. The same user
calling execute_code correctly gets 403.
Two gates, both mirroring toolAccessPermType in ~/server/controllers/tools.js:
* Upload (api/server/routes/files/files.js): a tool-resource-to-permission map
checked before any branching, so it also covers the assistants path. Returns
403 with the same log line as the RUN_CODE gate. execute_code is included
because it had the same hole: the tool CALL was gated, the upload was not.
* Tool loading (api/app/clients/tools/util/handleTools.js): checked outside the
lazy loader so a denied user never gets the tool equipped, rather than one
that fails when called. Fails closed if the permission check itself throws.
All four required imports were already present in that file, next to an
existing FILE_CITATIONS check.
Both changes live in /api (JavaScript) rather than /packages/api (TypeScript)
as CLAUDE.md prefers for new backend code: each mirrors an existing pattern in
exactly these files, and a second permission gate in another language and
package would be harder to keep in step with the first.
Tests: api/app/clients/tools/util/handleTools.fileSearchPermission.test.js
covers permit, deny, the log line, and the fail-closed path.
* fixup! fix: enforce FILE_SEARCH role permission server-side
* 🔐 fix: Gate `file_search` and `execute_code` on Role Permissions
The `FILE_SEARCH` gate added in the previous commit lives in
`handleTools.loadTools`, which `loadAgentTools` only reaches when
`definitionsOnly` is false. That default is false on the chat path
(`Endpoints/agents/initialize.js`) but true on the responses and
OpenAI-compatible controllers, so on those paths a denied user still got
the tool definition advertised to the model and their files primed by
`primeSearchFiles`, and the call failed later in `loadToolsForExecution` —
the "gets one that fails when called" outcome the gate set out to avoid.
Move the decision to the capability filters that both loaders already run,
mirroring how `canUseMCP` resolves the `MCP_SERVERS` permission ahead of the
synchronous filter. `AgentCapabilities` stays the instance-wide deployment
switch; the role grant is a second condition a tool has to clear. Because
`hasFileSearch`/`hasExecuteCode` derive from the filtered list, priming is
skipped for a denied user too.
`RUN_CODE` had the same hole: `toolAccessPermType` in
`~/server/controllers/tools.js` gates only `POST /tools/:toolId/call`, not
the agent run, so a role without `RUN_CODE.USE` could still execute code
through an agent. Both tools go through the same map.
Checks use `checkAccessWithRequestCache` and run only for tools whose
capability is already enabled, so a run costs at most one role read. A check
that throws denies the tool.
Also formats the test file added in the previous commit, which Prettier
rejects as-is.
* 🔐 fix: Close the Remaining `RUN_CODE` and `FILE_SEARCH` Bypasses
Codex review of the previous commit found four ways past the gates. All four
share a cause: the permission map was copied per call site, so every boundary
that was not copied into stayed open.
Moves the maps and the check into `packages/api/src/tools/rolePermissions.ts`,
per CLAUDE.md ("all new backend code must be TypeScript in `/packages/api`",
"keep `/api` changes to the absolute minimum"), and points the four `/api`
boundaries at it.
- `handleTools.loadTools` now gates every tool in `toolRolePermissions`, not
just `file_search`. It is the shared boundary the Assistants required-action
flow crosses via `processRequiredActions`, which never passes the agent
capability filter — so a legacy Assistant with a raw function named
`execute_code` ran arbitrary code for a role denied `RUN_CODE`.
- The check is now request-cached (`checkAccessWithRequestCache`). The previous
`checkAccess` call omitted `req`, so the agent path resolved the same grant
twice and issued a second serial `getRoleByName` during chat startup, against
the rule in AGENTS.md.
- `codeExecutionEnabled` is gated by the role result at all three loaders, not
only the `execute_code` entry in the filtered list. It drives tool
classification and the programmatic bash tool, so an agent pairing
`execute_code` with an MCP `code_execution` tool still advertised and
instantiated `run_tools_with_bash` for a denied role.
- The upload map covers `EToolResources.code_interpreter`, which the Assistants
builder posts instead of `execute_code`, and native `code_interpreter` /
`file_search` tools are dropped when an assistant is created or updated.
Those run inside the provider and reach neither loader, so configuration time
is the only place they can be gated.
Renames `handleTools.fileSearchPermission.test.js` to
`handleTools.rolePermissions.test.js` — it now covers both tools.
* 🔐 fix: Gate the Image Upload Route and the v1 Assistant Writers
Second Codex round found the same shape again: boundaries the map had not been
wired into. Adds two shared helpers next to the maps in
`packages/api/src/tools/rolePermissions.ts` so a new upload handler or assistant
writer gets the check by calling one function.
- `/files/images` accepts `tool_resource` and routes agent uploads to
`processAgentFileUpload` on its own. The Code Files UI sends images there, so
every image was a way around the upload boundary for a role denied
`RUN_CODE`. Both upload routes now call
`checkToolResourceUploadPermission`.
- That helper passes `req`, so the role read joins the request cache. The
previous `checkAccess` call omitted it, and an allowed Assistants upload goes
on to `processFileUpload` → `addResourceFileId` → `updateAssistant`, whose own
check does pass `req` — two serial lookups per upload, against AGENTS.md.
- `/assistants/v1` is still mounted and its `createAssistant` / `patchAssistant`
write native tools straight to the provider. Both now filter through
`resolveAssistantToolPermissions`, which v2 also uses in place of its local
copy.
Run-time enforcement for native assistant tools is deliberately not here: it
means overriding `body.tools` at `createRun` in both chat controllers, which
changes run semantics, and is better argued on its own.
* 🔐 fix: Gate Legacy `retrieval` and the Code-Environment File Tools
Third Codex round, same shape twice more.
- The v1 assistant builder submits `{ type: 'retrieval' }` where v2 submits
`file_search` (`AssistantPanel.tsx:203`). Only the v2 spelling was mapped, so
`resolveAssistantToolPermissions` treated legacy retrieval as ungated and both
v1 writers preserved it for a role denied `FILE_SEARCH`. Both spellings now
answer to the same grant.
- `codeEnvAvailable` in the agent initializer was capability-only, and
`initializeAgent` rebuilds `bash_tool`, `read_file` and the workspace file
tools from it — after the tool loader has already dropped `execute_code` for a
denied role. The bash gate stops command execution, but those handlers still
read, search, create and edit files in an attached code environment. The flag
now carries the role grant, and short-circuits before the role read when the
deployment has the capability off.
* 🔐 fix: Resolve Tool Grants Once Per Request and Pair Every Capability Gate
Four review rounds found thirteen issues, all one class: a boundary the
permission check had not been copied into. Rounds 2 and 3 each found gaps
created by the previous round's fix, and a manual sweep of tool constructors
and upload routes still missed the `codeEnvAvailable` family entirely — because
the thing worth enumerating is not "paths that reach a tool" but "reads of the
capability".
There are 28 such reads. This replaces per-site permission checks with one
resolution per request, pairs every read that is a gate, and pins the list so a
new one cannot be added silently.
- `resolveToolRoleGrants` resolves `RUN_CODE` and `FILE_SEARCH` together and
memoizes on the request. Both perf findings disappear by construction: gates
share one role read instead of each issuing its own.
- Newly paired gates: `codeEnvAvailable` in the OpenAI-compatible, Responses and
memory-agent initializers (`initializeAgent` rebuilds `bash_tool`, `read_file`
and the workspace file tools from it, and hands their handlers the code
environment); the capability checks in agent upload processing and in
agent-management upload purposes; and the library chat-completion service,
behind an optional `getRoleByName` dependency so embedders are not broken.
- The v1 Knowledge upload posts `assistant_id` with no `tool_resource`, so there
is no resource to authorize. It now reads the assistant's own native tools and
requires their grants, instead of treating a missing resource as unrestricted.
- The startup role read moved off the critical path into the existing
`Promise.all`, and the direct tool-call check passes `req` so the shared
loader gate reuses its result rather than repeating the lookup.
- `toolCapabilityGates.spec.js` pins every file that reads either capability
with a count and a reason. A new read fails the suite until it is classified,
so the next boundary announces itself instead of waiting for a reviewer.
* 🔐 fix: Abort Assistant Writes on Role-Lookup Failure, Authorize Legacy Uploads First
Round 5 found no missed boundary — the inventory held. All three findings are
about how the gates behave.
- Failing closed is right where a denial blocks the operation, and wrong where a
denial instead filters a payload the caller persists. A transient role-store
outage during an assistant create or patch was silently stripping
`code_interpreter` / `file_search` / `retrieval` and saving the result, turning
a momentary failure into permanent config loss. `checkToolRolePermission`
gains `throwOnError`, and `resolveAssistantToolPermissions` uses it: every one
of its callers either persists the filtered list or rejects the request, so a
lookup failure has to propagate.
- The legacy-assistant upload gate ran after `sanitizedUploadFn` had already
pushed the file to the provider, so a denied role left an untracked remote file
and got a 500 for what is a 403. Moved to the route, next to the tool-resource
gate, before any bytes are sent.
- `resendFiles` hydration derived its resource set from unfiltered `agent.tools`,
so a denied role still paid the thread walk and code-file reads for a tool
about to be dropped. The `execute_code` half now keys off
`effectiveCodeEnvAvailable`, which already carries the grant.
The `file_search` half of that last one needs the grant threaded into
`initializeAgent`, which is plumbing in the most delicate file here for a latency
win on an already-correct path — deliberately left for a follow-up.
* 🧪 fix: Declare `resolveToolRoleGrants` in the Upload Spec's Module Stub
`Tests: api (shard 2/3)` failed on `a0b38c3`: `process.spec.js` stubs
`@librechat/api` wholesale, so the `resolveToolRoleGrants` call added to the
upload gate resolved to undefined and threw. Five failures in
`processAgentFileUpload`, plus one cascading `processFileURL` assertion from the
same suite.
The gate was verified through its own spec and the routes above it, but not
through the spec of the file it lives in — `process.spec.js` was never run
locally. Every spec belonging to a file this PR touches now has been, and the
mongodb-backed ones that still cannot run here were checked statically for the
same stub shape: all but `process.integration.spec.js` spread `requireActual`,
and that one never reaches these paths.
* ⚡ fix: Skip the Role Lookup When Code Execution Is Disabled
The browser initializer already guards this; the OpenAI-compatible and Responses
controllers did not, so every request on those endpoints issued a role read whose
result the capability short-circuit then discarded. Both now start the lookup
only when the deployment has `execute_code` enabled, matching the third.
* ⚡ fix: Drop Three Redundant Reads on the Gated Paths
- The memory initializer resolved grants unconditionally, so a deployment
without `execute_code` paid a role read for a flag that could only be false.
Guarded like the three chat initializers.
- Agent-management upload purposes resolved grants before `checkCapability`, so
a purpose the deployment has switched off paid a role read on the way to being
rejected. Capability first, then the grant.
- The legacy-assistant preflight builds an OpenAI client to read the assistant's
tools, and `processFileUpload` then built a second one — re-reading the user's
key expiry and values. The preflight now hands its client on, and processing
builds one only when it wasn't given one.
---------
Co-authored-by: Paul <200737214+SSIG-IT@users.noreply.github.com>
S3 and CloudFront records have carried `storageKey` since #12987, yet six
readers still handed `file.filepath` to `getDownloadStream` and re-derived
the key by parsing a presigned or CDN URL, while four others had grown
their own `storageKey || filepath` expression. One resolver now serves all
ten: `resolveDownloadPath` returns the recorded key when present and the
path otherwise, so records without a key (local, Firebase, Azure, code
output) behave exactly as before, and the share route keeps its local-only
query-string strip on top.
`resolveStoredS3Key` reuses the same `StoredFileRef` type. Covered by unit
cases for the resolver and an S3 case proving a record with a key streams
correctly even when its stored URL no longer parses.
Closes#15693
The DocumentDB compatibility guard flagged Mongoose per-document save-condition bag reads and writes (document.$where) in tenantIsolation.ts as the unsupported $where operator, leaving dev red on Tests: data-schemas. The guard now judges a dotted $where only where the syntax is unambiguous: a call in any form, or code assigned through any operator or wrapper, is an offense; a read or a non-literal assignment is not claimed, with filter.$where = predicate stated as the one declared limit and the method sweep and live cluster run as its backstop. Every other way of writing the operator remains an offense. unwrapExpression also peels angle-bracket assertions, closing a gap in pipeline-update detection.
* 🔤 fix: Decode percent-encoded S3 keys so non-ASCII filenames are readable
extractKeyFromS3Url returns `URL.pathname` as the S3 object key without
decoding it. The AWS SDK percent-encodes the Key again when it signs the
request, so a file stored under `Ársreikningur.pdf` is fetched as
`%C3%81rsreikningur.pdf` and every read fails with NoSuchKey. ASCII keys are
byte-identical either way, which is why this only appears for non-English
filenames.
Decode keys derived from a URL path in all three branches (path-style
endpoint, bucket-in-path, virtual-hosted). A key passed in raw — not a URL —
still returns untouched, and a malformed escape sequence falls back to the
raw value with a warning rather than throwing.
* 🔗 fix: Percent-encode CloudFront URL keys so both URL forms agree
buildCloudFrontUrl interpolated the raw S3 key into the URL while SDK-generated
S3 URLs carry an encoded one, so the two forms of `file.filepath` disagreed
about what a `%` means. `assertS3FileName` permits `%`, so a key containing the
literal text `report%20final.pdf` produced a CloudFront URL indistinguishable
from one for a key containing a space — and decoding on extraction would then
target the wrong object on read, re-sign, and delete.
Encoding each path segment here (separators stay literal) makes both producers
consistent, which is what lets extractKeyFromS3Url decode unconditionally.
* style: sort imports in cloudfront/crud.ts (pre-existing drift)
The changed-file import-sort gate flags this file; the drift predates this PR
(the untouched upstream version fails the same check). Kept as its own commit
so it does not obscure the fix.
* 🔏 fix: Encode the CloudFront Invalidation Path Like the Viewer URL
`buildCloudFrontUrl` now percent-encodes each key segment, so the cached
viewer path for a key with a literal `%` or a non-ASCII character is the
encoded form. `deleteFileFromCloudFront` still handed the raw key to
`CreateInvalidationCommand`, so the invalidation no longer matched the
cached object and deleted content stayed served until the entry expired.
Both producers now share one `encodeKeyPath` helper.
Also asserts that `getS3FileStream` sends the decoded key to
`GetObjectCommand`, which is the call that actually failed with
`NoSuchKey`, rather than only checking the extractor.
Co-authored-by: dinershtein <228485+dinershtein@users.noreply.github.com>
---------
Co-authored-by: Danny Avila <danny@librechat.ai>
Co-authored-by: dinershtein <228485+dinershtein@users.noreply.github.com>
* 🎯 fix: Land a Steer Applied Before the First Run Step on the Live Placeholder
An interrupt (steer + preempt) sent before the model has produced a token
is applied server-side at content index 0 and stamped with the response
id the server pre-allocated at job creation. The pane, however, still
renders the in-flight response under the `${userMessageId}_` placeholder
until the FIRST run step renames it, so the exact-id lookup missed, the
bounded next-frame retry ran out silently, and the interrupt vanished
from the live view until a refresh — while the spinner kept going.
`findResponseMessageIndex` now accepts the pane's OWN placeholder
identities as an explicit fallback (never a positional guess, per the
regenerate rule) and both the steer and activity-label resolvers
delegate to it. `useResumableSSE` passes the submission's placeholder id
and the padded user-message id, read at call time so the `created`
reassignment is honored. The rename copies placeholder content forward,
so the part rides into the renamed row.
* 🧭 fix: Carry an Early Steer Through the Rename for Regenerates and Edited Resubmissions
A regenerate seeds the renamed response from `submission.initialResponse`
rather than the store tail, and an edited resubmission seeds from that
object's content, so a steer landed on the placeholder only in the store
was dropped by the first run step's rename. `syncSubmissionPlaceholder`
keeps the submission the step handler receives in step with the
placeholder this pane mutated.
The steer also claims the server-local index space that run steps and
labels already shift past the retained edit prefix; it now shifts the
same way through one shared `editPrefixLength()` instead of landing
inside the kept content. Codex round 1 (P2) on #15692.
`@lhci/cli@0.15.1` pins `lighthouse` to an exact `12.6.1`, so the Lighthouse
lane could never move off a release whose `puppeteer-core` still depends on
`extract-zip` — an advisory with no patched version. That pin, not Lighthouse
itself, was holding 8 of the repository's 16 `npm audit` findings open.
LHCI was only ever a subprocess wrapper here: `audit.ts` shelled out to
`@lhci/cli/src/cli.js` for `collect` and `assert`, and LHCI's own node runner
shells out to `lighthouse/cli/index.js` in turn. Call that CLI directly, run
the three navigations in a loop, and assert the median budgets in TypeScript
next to the assertions `load.spec.ts` already makes.
- `npm audit`: 16 findings (7 high, 1 moderate, 8 low) -> 6 low. The remainder
is the pre-existing `elliptic` chain under `vite-plugin-node-polyfills`,
which has no fixed version and is unrelated to this lane.
- Lighthouse 13 removed `largest-contentful-paint-element` and moved the LCP
node into `lcp-breakdown-insight`. Reading it through a `lcpElement` helper
keeps the "the transcript must be the LCP element" guard working and makes
the next rename fail loudly in one place.
- Reports move to `.lighthouse/` as `lhr-N.report.{json,html}`; cookie
redaction, the API timing table and the desktop/provided-throttling settings
are unchanged. Budgets are now printed as a table immediately before they are
asserted, so the workflow's 80-line failure comment always contains them.
- `CHROME_PATH` and `LIGHTHOUSE_CHROME_FLAGS` are documented: chrome-launcher
prefers the Windows Chrome under WSL, whose debugging port Linux cannot
reach.
* 🔒 fix: Assert the Tenant When Saving a Persisted Document
`doc.save()` on an already-persisted document issues `update` filtered on
`_id` alone. The tenant-isolation plugin stamps `tenantId` onto the payload
but never asserts it in the predicate, so the write is scoped only by
provenance — safe in the normal flow, since you can only fetch a document
your tenant can see, but unguarded when the `_id` comes from an unscoped
source: `runAsSystem`, a cached id, or a client-supplied id.
Found by the driver probe added in the previous commit, which is also what
proves the fix: its characterization test flips from asserting the predicate
is absent to asserting it is present.
`$where` is Mongoose's documented public hook for this — "additional
properties to attach to the query when calling `save()` and `isNew` is
false" — and its own sharding plugin uses it to attach a shard key the same
way. It is absent from the TypeScript types, hence the cast.
## Why this cannot break existing writes
- `isNew` documents return early; all three `transaction.ts` saves and the
`pluginAuth.ts` save construct their document, so they are untouched.
- A document that never carried a `tenantId` yields no predicate, so
pre-tenancy rows and the global `Role` collection still save.
- With no tenant context — every single-tenant deployment — the scope is
unscoped and no predicate is ever added.
- The remaining two call sites fetch and save inside the same request
context, so the carried tenant matches by construction. `session.ts`
reaches `save()` via `createSession`, which passes an `isNew` document.
- A mismatch fails loudly with `DocumentNotFoundError` rather than silently
no-op'ing, and optimistic concurrency, array writes and subdocument writes
were each verified to still work alongside it.
80 suites / 2793 tests green.
* 🧭 fix: Reset Tenant Save Predicates Across Scopes
* 🛡️ fix: Close Persisted Tenant Save Bypasses
* fix: dismiss menus when composer focus changes
* 🎯 fix: Keep Composer Focus Off Clicked Controls So Menus Can Close
Ariakit records document.activeElement at open time as a menu's disclosure.
The composer surface focused the textarea on every bubbled click, including
the click that opened the Tools or attach menu, so the textarea became the
disclosure and the menu ignored every later textarea interaction. The Tools
menu went from modal to non-modal in #14979 (v0.8.8-rc2), which removed the
backdrop that had been closing it anyway.
Hoists the interactive-target selector, adds label to it, documents the
mechanism at the guard, and gives the composer surface a stable test id so
the empty-space focus test no longer depends on a utility class. Adds a test
that opens a menu and proves a textarea click closes it.
Closes#15624
* 🎯 fix: Restore Textarea Focus After Send, Steer and Stop Controls
The interactive-target guard also skipped the bubbled click that used to
return focus to the textarea after a mouse click on send. The send button
is then disabled or swapped for the stop control, leaving focus on body.
Route that refocus through a shared helper called from the form submit,
the during-run consume callbacks, and the stop button, keeping the
touchscreen exception. Adds a test that a mouse click on send leaves the
textarea focused; it fails without the submit refocus.
* 🎯 refactor: Exempt Only Focus-Owning Targets From the Composer Refocus
The blanket 'button' exemption inverted the surface's long-standing
behavior for every control, so each control that relied on the bubbled
refocus (send, stop, steer, badge toggles) became its own regression.
State the rule the other way round: the surface refocuses the textarea
after any click except on a target that owns focus itself (links, form
fields, labels) or opens or belongs to a popup (aria-haspopup disclosures
and menu/listbox/dialog content, which React bubbles through portals).
Matches that contain the surface itself are ignored so a host dialog can
never disable the refocus. Drops the explicit refocus calls, which plain
buttons no longer need.
* 🎯 fix: Restore Textarea Focus From Popup Actions That Consume the Composer
The during-run alternate actions live in an Ariakit hovercard, which is
portaled dialog content and therefore exempt from the surface's bubbled
refocus. Choosing Steer or Queue there consumed the text and unmounted
both the button and the hovercard, leaving focus on body. Actions that
consume the composer from inside a popup now restore focus themselves
through a shared consume callback. Adds a ChatForm test that opens the
real hovercard with screen-coordinate mouse travel, chooses Queue, and
asserts the textarea is focused; it fails without the refocus.
* 🧪 test: Expect Escape to Return Focus to the Quote Pill
The quotes e2e asserted that Escape on the selections popover focused
the textarea. That held only through the bug this branch fixes: Enter on
the pill fired a click that bubbled to the composer surface, the textarea
took focus mid-open and was recorded as the popover's disclosure, and
Ariakit then 'restored' focus to it on hide. With the surface no longer
stealing focus from a popup disclosure, the pill is the disclosure and
Escape returns focus to it, as PendingQuoteChips documents. The guard
against focus landing on body is unchanged.
* 🎯 fix: Restore Focus When Removing a Quote From the Selections Popup
The remove buttons in the selections popup are popup content, so the
surface no longer refocuses the textarea for them, and the clicked
button unmounts with its row. Removing the second-to-last quote also
unmounts the popup and its pill, so Ariakit has nothing to restore focus
to and it fell to body. The chip now restores focus itself: to the
textarea when the popup collapses, otherwise to the popup so keyboard
users stay inside it. Adds tests for both, plus one proving the primary
during-run submit still refocuses through the surface (the hovercard
anchor carries no popup attributes, so it bubbles like any button).
* ♿ fix: Keep Quote Removal Focus Guarded and on a Visible Control
Route the chip's collapse refocus through the composer's guarded helper
so a tap on a touchscreen does not raise the keyboard, and after removing
one of several quotes focus the remove button now at the same row (or
the last one) once React has re-rendered the list, instead of the
outline-less popup container. Tests pin both; each fails without its fix.
* test: make quote popup focus checks deterministic
---------
Co-authored-by: Jackson Riding <99007683+jacksonriding@users.noreply.github.com>
* 🪪 feat: Configurable Langfuse Trace User Identity and Metadata
* 🪪 fix: Prefer createRun's conversationId and warn once on an unset userIdField
* 🪪 fix: Validate Langfuse trace field names at the point of use
* 🧹 chore: Sort identity imports
* 🪪 fix: Source the trace model label from the initializer, not a prompt-affecting option
* 🧪 fix: Build the trace context without a prototype so partial client contexts resume
* 📦 chore: Bump `@librechat/agents` to v3.8.0 for the Langfuse trace userId override