Commit graph

1651 commits

Author SHA1 Message Date
Dustin Healy
cdc3339a78
🪬 fix: Fence Agent Checkpoint Ownership and Cleanup Recovery (#15680)
* 🔒 fix: Isolate Checkpoint Cleanup by Generation Ownership

* 🔒 fix: Harden Checkpoint Cleanup Ownership

* 🔒 fix: Retain Checkpoint Cleanup Evidence

* 🔒 fix: Persist checkpoint cleanup receipts

* 🔒 fix: Bound checkpoint cleanup receipt lifecycle

* fix: Bind checkpoint cleanup to durable ownership and deletion intent

* fix: Bind event actor checkpoint storage to authenticated owners

* fix: Resolve exact actor checkpoint ownership before lifecycle cleanup

* fix: Preserve actor storage compatibility with durable ownership and prune work

* fix: Defer checkpoint erasure until conversation deletion commits

* fix: Reclaim orphan actor ownership and batch deletion lookups

* fix: bind actor checkpoint ownership to payload rows

* fix: isolate actor readers and await account persistence

* fix: gate owned suspensions and drain complete account state

* fix: unify checkpoint deletion lifecycle and storage authority

* fix: Replay checkpoint deletion from durable owner state

* fix: retain checkpoint cleanup identity before topology loss

* fix: complete checkpoint catalog capture and retirement lifecycle
2026-09-07 22:04:59 -04:00
Danny Avila
6f05678bfc
🧐 feat: Restore Interactive Tool Approval Review (#15717)
* 🧐 feat: Review Pending Tool Actions in the Composer (#15714)

* feat: add interactive approval review to the composer

* fix: Harden interactive approval boundaries

* fix: Bound every approval display label

* test: exercise composer approval review in BYOM acceptance

* fix: reveal all directional approval controls

* fix: canonicalize code approval targets across replicas

* style: sort resumable approval test imports

* test: Exercise Coexisting Approval Surfaces

* Revert "🧐 feat: Review Pending Tool Actions in the Composer (#15714)"

This reverts commit 5f79ded9553405b697e837e1976a70accbfc3fc3.

* Reapply "🧐 feat: Review Pending Tool Actions in the Composer (#15714)"

This reverts commit 52c7d9c7453da0168338bcf79494927f561a92a0.

* chore: bump agents sdk to v3.8.2
2026-09-07 22:02:56 -04:00
Danny Avila
3e2a6f333b
🪗 feat: Compact Context in a Summarize-Only Turn (#15690)
* 🗜️ 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
2026-09-07 21:51:54 -04:00
Danny Avila
f1bd85498e
🪫 fix: Recharge Direct OpenID MCP Bearer Sessions (#15704)
* fix: recover direct OpenID MCP bearer sessions

* fix: harden direct bearer recovery lifecycle

* fix: close direct bearer lifecycle races

* test: align direct bearer checks with current dev

* fix: unify direct bearer recovery budget

* fix: infer direct bearer recovery from placeholder

* fix: preserve bearer precedence and recovery budget

* fix: propagate bearer recovery across joiners

* fix: preserve direct bearer fallback without session provider

* fix: close direct bearer recovery race windows

* chore: sort bearer recovery test imports

* fix: align bearer recovery with OAuth cleanup lifecycle

* fix: fence request-scoped MCP creation during config mutations

* fix: retain suspended MCP catalog authentication outcomes

* fix: cancel MCP bearer recovery and reuse refreshed credentials

* fix: close MCP bearer recovery lifecycle boundaries

* fix: preserve ordered catalog authentication rejection

* fix: isolate bearer recovery across request and transport boundaries

* fix: preserve shared recovery ownership and credential precedence

* fix: wait for recovery borrowers and validated OpenID publication

* fix: observe the validated browser publication flight

* fix: cancel abandoned OpenID publication followers

* fix: fence refresh grant admission after lease acquisition
2026-09-07 21:05:26 -04:00
Danny Avila
8fa59637c8
🧱 fix: Close MCP OAuth Teardown Races (#15716)
Some checks are pending
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Codegraph E2E Votes / vote (full suite) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Client build recovery regression (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
Sync Locize Translations & Create Translation PR / Sync Translation Keys with Locize (push) Waiting to run
Sync Locize Translations & Create Translation PR / Create Translation PR on Version Published (push) Blocked by required conditions
* fix: fence concurrent MCP OAuth teardown

* fix: hold MCP refresh teardown fences

* fix: suppress OAuth fallback during teardown

* fix: retire MCP connections before OAuth cleanup

* fix: annotate refresh teardown tenant scope

* fix: fence OAuth teardown across replicas

* test: provide OAuth teardown leases in controller mocks

* fix: fail safely around OAuth teardown leases

* fix: complete OAuth lease lifecycle handling

* fix: preserve OAuth single-flight admission
2026-09-07 18:11:37 -04:00
Danny Avila
601ed07870
🫧 fix: Retire Cancelled MCP OAuth State (#15702)
* fix: Clean Up MCP OAuth Teardown State

* fix: Harden OAuth Teardown Boundaries

* fix: harden MCP OAuth teardown races

* fix: avoid flow cache dependency cycle

* fix: bind OAuth teardown to credential generations

* test: cover active OAuth server fixtures

* style: sort OAuth cleanup imports

* fix: discard mismatched OAuth token snapshots

* fix: fence OAuth teardown across callback races

* test: align OAuth callback fixtures with server fencing

* test: complete OAuth callback server fixtures

* fix: version OAuth flow settlement

* fix: fence OAuth teardown snapshots

* test: align OAuth teardown fixtures

* test: complete OAuth snapshot fixtures

* fix: snapshot OAuth deletion lifecycle

* test: bind OAuth revocation snapshots

* test: assert per-record OAuth fence

* fix: harden MCP OAuth teardown consistency

* test: expect snapshotted OAuth readers
2026-09-07 15:43:02 -04:00
Danny Avila
4b3a6eaf0e
🪧 feat: Surface Conversation Code Approval Modes (#15703)
* feat: Add conversation code approval modes

* refactor: Reuse shared code approval types

* fix: Scope approval selector to stateful agents

* fix: harden code approval state propagation

* fix: fail closed during approval discovery

* test: cover approval mode acceptance

* test: use visible approval mode label

* test: drive approval menu by keyboard

* test: expose accept edits in BYOM acceptance

* fix: read approval mode atomically on send

* fix: align code modes with endpoint policy

* fix: initialize code limiters at startup
2026-09-07 12:24:29 -04:00
Danny Avila
e370ce4b21
🎒 fix: Bound Agent Attachment Context (#15694)
Some checks are pending
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Codegraph E2E Votes / vote (full suite) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Client build recovery regression (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
2026-09-07 08:16:34 -04:00
Danny Avila
dd5829ed77
🏰 fix: Enforce Platform Grants for Code Workers (#15700)
* fix: Require Platform Grants for Code Workers

* fix: Separate Platform Scope From Tenant Identity
2026-09-07 08:13:47 -04:00
Danny Avila
911b6324d8
🧲 fix: Coalesce and Bound Code Environment Status Polls (#15701)
* fix: Bound Code Environment Status Polling

* refactor: Move Code Limiters Into API Package

* fix: enforce status polling boundaries
2026-09-07 08:13:25 -04:00
Danny Avila
29971f188a
🧺 fix: Skip Priming Denied File Search Resources (#15699)
#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>
2026-09-07 07:56:23 -04:00
Danny Avila
a3fc3b9dbf
🚧 fix: Gate File Search and Run Code by Role (#15691)
* 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>
2026-09-07 07:03:22 -04:00
Danny Avila
58de77619e
🗝️ refactor: Prefer the Recorded Storage Key for Every Download Stream (#15695)
Some checks are pending
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Codegraph E2E Votes / vote (full suite) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Client build recovery regression (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
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
2026-09-07 01:28:35 -04:00
Dustin Healy
037cbf530d
🧺 fix: Contain Conversation Import and Upload Failures (#15681)
* 🛡️ fix: Harden Conversation Imports and Upload Handling

* 🩹 fix: Address Import Hardening Review Findings

* 🩹 fix: Map Clone Size Validation Errors

* 🩹 fix: Chunk Import Cleanup Queries
2026-09-06 22:42:46 -04:00
Danny Avila
0b9dc209b0
🧫 fix: Verify Early Stream Recovery (#15676)
* feat: harden early buffer recovery observability

* fix: fence recovery to emitted frontier

* fix: close recovery observability races

* fix: require atomic recovery capabilities

* fix: fail incomplete recovery attachments closed

* fix: preserve legacy store contract

* fix: correlate failed overflow persistence

* fix: break recovery type dependency cycle

* fix: reconcile distributed recovery lifecycle

* fix: preserve content snapshot contract

* fix: harden cross-replica recovery lifecycle

* fix: lease recovery subscriber state

* fix: close recovery lifecycle edge cases

* fix: close recovery validation races

* test: align subscriber lease cleanup

* fix: harden subscriber lease lifecycle

* fix: finalize subscriber lease handoffs

* fix: reconcile recovery error replacements

* fix: preserve durable recovery frontier

* test: expect durable frontier gaps

* fix: scope durable snapshot protocol

* fix: trust durable terminal recovery payloads

* fix: close overflow recovery rollout races

* test: bound overflow race fixture memory

* fix: bound overflow marker refresh

* test: reduce recovery fixture memory

* fix: fence overflow recovery admission

* fix: close overflow recovery admission races

* fix: scope overflow admission fencing

* fix: preserve owner replay after remote admission

* test: await pre-admission append fencing

* test: reflect pre-admission durability
2026-09-06 22:28:17 -04:00
aeyeopsdev
e504128e8d
🫙 fix: Surface Document Extraction Failures (#15651)
Co-authored-by: aeyeopsdev <275853971+aeyeopsdev@users.noreply.github.com>
2026-09-06 19:09:49 -04:00
aeyeopsdev
88116f7710
🫠 fix: Surface Bedrock Content Filter Refusals (#15647)
Some checks are pending
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Codegraph E2E Votes / vote (full suite) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Client build recovery regression (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
Sync Locize Translations & Create Translation PR / Sync Translation Keys with Locize (push) Waiting to run
Sync Locize Translations & Create Translation PR / Create Translation PR on Version Published (push) Blocked by required conditions
* fix: surface Bedrock content-filtered responses

* refactor: extract model refusal metadata

* test: preserve refusal helper in agent callback mock

---------

Co-authored-by: aeyeopsdev <275853971+aeyeopsdev@users.noreply.github.com>
Co-authored-by: Danny Avila <danny@librechat.ai>
2026-09-06 17:39:02 -04:00
Danny Avila
b181ef0232
🪬 feat: Configure Langfuse Trace User Identity and Metadata (#15667)
* 🪪 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
2026-09-06 17:30:23 -04:00
Danny Avila
8a85df9715
📜 feat: Add Skills Discovery and Authoring to the Management API (#15642)
* feat: expose skill discovery and authoring through management API

* fix: declare public skill management schema and handler types

* fix: preserve skill permissions and shared management error semantics

* fix: validate skill file paths before writing storage

* test: isolate execution limiter routes from skills management

* fix: align skills discovery access and file upload protections

* fix: authorize skills operations before sync and upload admission

* perf: overlap independent skills authorization reads

* style: sort skills management imports
2026-09-06 17:26:26 -04:00
aeyeopsdev
a827f35a69
🛤️ fix: Align File Search Citation Paths (#15650)
* fix: keep file search anchors aligned with citation passages

* refactor: centralize file citation selection

* test: wire citation helpers into API mocks

---------

Co-authored-by: aeyeopsdev <275853971+aeyeopsdev@users.noreply.github.com>
Co-authored-by: Danny Avila <danny@librechat.ai>
2026-09-06 17:25:47 -04:00
Danny Avila
3f9285355d
🏠 fix: Route Standalone File Writes to BYOM Workers (#15675) 2026-09-06 17:24:21 -04:00
aeyeopsdev
87097e2113
🎟️ fix: Preserve OpenID Logout Token Hints (#15653)
Co-authored-by: aeyeopsdev <275853971+aeyeopsdev@users.noreply.github.com>
2026-09-06 17:23:58 -04:00
Danny Avila
ebf70826b5
📫 fix: Surface Sandbox Artifact Delivery Failures (#15671)
* fix: Surface sandbox artifact delivery failures

* chore: Sort artifact delivery import
2026-09-06 15:31:19 -04:00
Danny Avila
f1a21764f3
🧺 fix: Discard Stale Session Tokens at OpenID Login (#15668)
With `OPENID_REUSE_TOKENS=true`, `sendOpenIDAuthResponse` compares the
incoming token set against `req.session.openidTokens`. Passport runs with
`session: false`, so the Express session is never regenerated at login and a
token set from an earlier authentication survives there. Its refresh token
differs from the one the IdP just issued, which the advanced-session check
reads as "a concurrent refresh already advanced the session": the fresh IdP
tokens are discarded and the stale set is republished. When that stale
access token has already expired, the completed flight's TTL clamps to 1ms
and the publication assertion fails with "OpenID refresh result is no longer
available for publication", which fails every login for as long as the stale
session lives.

The advanced-session comparison exists for refresh races and has no business
at a fresh authorization-code login. The login controller now asks the
publication service to discard whatever the session holds, and the service
does so after its own session reload so the store cannot resurrect the
stale set. Refresh callers are unchanged.

Fixes #15648
2026-09-06 15:07:08 -04:00
Marco Beretta
c9d208ad3b
🧰 feat: Unify Tool Activity, Reasoning, Search, and Agent Workflows (#14546)
* feat: Group Reasoning with Tool Calls and Polish Activity UI

- Treat reasoning (Thoughts) as transparent to tool grouping so interleaved
  thoughts fold into the tool group instead of splitting it
- Group a lone tool call that has reasoning (e.g. a skill) so it gets the
  same collapsible chrome as multi-tool groups
- Count only real tool calls for the group header; add a reasoning indicator
  and a singular 'Used 1 tool' label
- Rework the in-group Thoughts panel: tool-row sizing, rounded content,
  header copy button, and a floating collapse/copy bar
- Round the floating thinking-bar buttons
- Refine the agent handoff row and instructions panel with consistent
  spacing and a copy affordance

* feat: Move subagent runs to an artifacts-style side panel and polish reasoning UI

- Replace the subagent dialog with a right-side panel that shares the
  artifacts slot (currentSubagentRunId + subagentPanelVisibility atoms,
  a subagentRunsState registry, and a useOpenRightPanel cross-clear so the
  two panels are mutually exclusive)
- Rebuild the inline subagent card to be tool-consistent, preview a single
  live/result line, and open the panel (auto-focusing on stream arrival)
- Relocate the originating prompt to a collapsed, smoothly-animated
  disclosure under the panel header
- Gate the Thoughts copy button to expanded state and move the floating
  bar to a scroll-out reveal, matching the code-block pattern
- Fix the reasoning expand/collapse jump by animating the trailing gap
  inside the grid track instead of an expand-only margin

* fix(client): handle singular grouped tool labels

* refactor(client): unify tool row disclosure styling in a shared module

Extract the hover-reveal chevron and expanded panel spacing into
disclosure.ts and align every tool activity row on the same layout:
h-5 header, my-1 rhythm, full-width click target, and a 200ms chevron
rotation. Rows rendered through ProgressText now stretch across the
message column (the absolute content layer was shrink-wrapping to the
text), and the copy buttons in thinking and output panels anchor to
the row instead of the panel corner.

* fix(client): friendly labels and correct arg parsing for native tools

Map skill, read_file, create_file, edit_file, set_memory, and
delete_memory to localized display names so summaries stop showing raw
tool ids, and give the memory tools the Brain icon the Memories panel
already uses. read_file and skill rows parse the arg the backend
schemas actually emit (path, with file_path as a legacy fallback;
skillName) and fall back to a generic noun instead of rendering an
empty name in their labels.

* feat(client): outcome-based tool group summaries

Group headers now describe the activity performed: homogeneous search
groups read "Searched the web" or "Searched web and files", mixed
groups read "Ran N actions" with per-label repeat counts (Create File
x2) and a failure tally in the detail line. Generic tool rows resolve
their label through getToolDisplayLabel, the OAuth trust warning moved
into a shared ToolAuthWarning that a group renders once instead of per
call, and the group body is a flex column so row margins stop
collapsing unevenly between rows.

* feat(client): render file edits as a structured diff view

Replace the highlighted-text diff in file authoring output with a
line-based renderer: red and green tinted rows with +/- gutters,
old/new line numbers when hunk headers carry them, and diff noise
stripped (file headers, streamed old_text/new_text markers, bare @@
separators become dividers). The code window header shows the file
name with +N/-N change stats next to Copy Code, and file authoring
rows adopt the path-first arg parsing and shared panel spacing.

* refactor(client): align memory updates with the standard tool row

Rebuild MemoryArtifacts on the shared disclosure row (useExpandCollapse
grid animation, hover-reveal chevron, h-5 header) in place of its
bespoke ResizeObserver height animation, and simplify the expanded
panel: section headings dropped in favor of bold memory keys, a single
p-3 inset instead of double padding, and the now-unused heading
translation keys removed.

* fix(client): gate retrieval expansion on renderable results

The row offered an expand affordance whenever raw output existed even
when no sources parsed, opening an empty panel. Expansion now keys off
parsed results, which also covers attachment-only sources that arrive
without text output, and collapses if results disappear.

* style(client): soften the message nav hover tooltip

Rounder corners and the light border weight to match the rest of the
floating surfaces.

* fix(client): compact single-number gutter in diff view

The dual old/new gutters left one column blank on every add or delete
row, reading as a stray number floating far from its marker. Each row
now shows the one relevant line number (old for removals, new
otherwise) right beside the +/- marker, and the scroll container is
vertical-only since lines wrap.

* feat(client): dedicated card for memory tool calls

set_memory and delete_memory rendered through the generic tool card,
reading "Ran Save Memory" with raw parameter chips like an unknown MCP
tool. A new MemoryCall part gives them first-class rows: "Saved
memory" / "Deleted memory" with the key as a quiet subtitle, the
Brain icon, and an expanded panel that mirrors the memory attachment
display (bold uppercase key over the stored value, or a deletion note),
with error output shown inline when a write fails.

* style(client): gap between the web search row and its source list

The expanded source panel sat flush against the 22px favicon stack,
which overflows the 20px row. The panel now opens with a 6px top
margin while the row keeps the shared my-1 rhythm.

* feat(client): richer web search source list

The panel only showed favicon, title, and domain while the search
artifact carries much more. Source rows now include the result snippet
(clamped to two lines) and date under the domain, and a Serper answer
box renders as a lead card above the list with its title and snippet.
Streaming behavior is unchanged; the answer box is attachment-only
since it never carries citation anchors.

* refactor(client): move web search answer box into a details hover card

The inline answer card read as assistant prose sitting inside the
source list. The panel is back to sources only; an Info trigger at the
right edge of the row (hover-revealed like the chevron, focus-openable
for keyboard) opens a hover card with the search query, the source
count, and the provider answer box when present. WebSearch now
receives the tool call args to surface the query.

* feat(client): image, shopping, and place verticals in web search results

Serper vertical results were parsed into the artifact and dropped.
The expanded panel now renders them when present: an image strip of
rounded thumbnails at true aspect ratios (sized from thumbnail
dimensions, no layout shift), a shopping card carousel with product
image, title, price and store, delivery note, and star rating, and a
place list with name, category, address, and rating. All link out,
use semantic lists with localized labels, and cap item counts.
Expansion now keys off any renderable content, so a verticals-only
search still opens.

* style(client): help cursor on the retrieval relevance badge

The badge sits inside a clickable row, so it inherited the pointer
cursor while only offering an explanatory tooltip.

* style(client): strip link underlines in web search verticals

The image and shopping anchors sit inside the markdown prose scope, so
every label rendered with the blue link underline.

* feat(client): surface search verticals outside tool disclosures

Image, shopping, and place results were only visible after expanding
the web search row, and disappeared entirely inside a collapsed tool
group. The strips moved into a shared verticals module that renders
in two spots following the attachment pattern: always below the row
for an ungrouped search, and hoisted below the group (visible while
collapsed) for grouped calls, where the row suppresses its own copy
via hideAttachments. The disclosure panel is back to sources only.

* feat(client): platform-native map links on place results

Place rows were the only vertical without a destination. Each row now
links out to the user's native maps app: Apple devices (detected via
the existing isMacPlatform check) get maps.apple.com with the query
and coordinates, everything else gets a Google Maps search link. Both
are keyless https links that degrade to a web map, so a misdetected
platform still lands somewhere useful. Rows pick up the same hover
treatment as the other linked results.

* fix(client): pin the bash copy button while the command scrolls

The button lived inside the scroll container with sticky/float
positioning, so horizontal scrolling dragged it through the command
text. It now sits absolutely in a non-scrolling wrapper around the
scroller and stays in the corner on both axes.

* feat(client): add view-transition morph helper for composer surfaces

Wrap a state update in startViewTransition (with a synchronous flush) so
elements sharing a view-transition-name animate their position, size and
shape between two states instead of swapping.

The composer band gets its own named, opaque snapshot group stacked above
the morphing element: without it a surface travelling between the thread
and the composer paints over the input and bleeds through the strip below
it. Falls back to a plain update where the API is unavailable and for
reduced-motion users.

* style(client): rebuild the ask question surfaces on shared option rows

The popover and the chat card rendered the same question two different
ways: numbered rows in one, wrapped chip buttons in the other, and the
panel was painted with hardcoded white/gray instead of theme tokens.

Both surfaces now render one AskOptions list, so numbering, check badges,
rounding and hover states match wherever a question appears. The card
groups its prompt with the description, styles the answer box like the
composer, and gains a Skip button beside Submit so declining does not
require the popover. While the popover holds the question the card keeps
a hidden copy of itself in the thread, reserving the exact space the card
will need so nothing reflows when the question moves back.

* refactor(client): make one control move a question between chat and composer

The popover carried both a chevron and a close button. Both left the
question pending and both moved it into the chat, so their only real
difference was invisible: the chevron kept the composer wired up as the
answer box while the close button released it. Two icons for one visible
outcome, with the meaning hidden in a placeholder change somewhere else.

Collapsing now does both jobs at once. Moving a question to the chat hands
the composer back for normal messages, and the card's chevron re-arms it,
so the popover's visibility and the composer's role can never disagree.
Escape maps to the same path and the dismissed-ids state is gone. Both
chevrons get a tooltip and a matching label, since no glyph conveys this.

Also fixes two behaviours found along the way: the card's Skip was a
silent no-op once the question left the popover, because it routed through
a helper gated on answer mode instead of the live pause, and clicking a
multi-select row moved the keyboard highlight, leaving a row painted as
selected after it was unchecked.

* style(client): fix changed-file lint formatting

* style(client): align tool call import order

* fix(client): render handoff instructions as readable context

* test: stabilize full test suite

* test(e2e): align assertions with action groups

* fix: preserve tool run and answer state

* fix: sync subagent and answer handoffs

* fix(client): keep summary parts stable through failed summarize rounds

Failed summarize completions spliced the in-flight summary part out of the
content array, remounting every later index-keyed part (collapsing whatever
the user had expanded mid-stream) and breaking the content-position ==
step-index invariant that streaming writes rely on. Finalize the part in
place instead and scope completion to the owning step's slot so
back-to-back rounds cannot clobber a newer in-flight part.

* fix(api): disable summarization below a viable context budget

A tiny user-set maxContextTokens re-triggers summarization on every graph
step (the summary allocation rounds to nothing and history still
overflows), burning dozens of LLM calls until the recursion limit aborts
the run with an opaque LangGraph error. Fall back to plain pruning under a
1024-token floor so the run either fits or fails fast with the actionable
empty_messages breakdown.

* feat(client): render context budget errors with readable copy

empty_messages and final_context_overflow are structured errors thrown by
the agents SDK, but they were missing from the typed-error dispatch table
and surfaced as raw JSON inside the generic failure text. Map both to
localized copy: empty_messages keeps its token budget breakdown in a
details block, final_context_overflow interpolates the projected and
available token counts.

* Fix ask answer handoff and OAuth warnings

* fix(client): address Codex review findings

* fix(client): address Codex review findings on tool group and summary UI

Replace the raw green/red diff palette in DiffView and CodeWindowHeader with
the existing status-success/status-error semantic roles, so a customized or
versioned theme moves the diff colors with it.

Compose the shared Button primitive in the ask option rows instead of
recreating hover, focus-visible and disabled appearance locally, and swap the
raw text-white on the checked badge for text-on-status.

Prefer a THINK part's generated reasoning_label in the grouped rendering path,
matching the standalone Reasoning path, with the generic Thinking/Thoughts text
only as a fallback.

Derive grouped tool completion and failure from the run step's terminal status
through the shared resolveToolCallPhase helper, so a step the run closed as
failed with empty or benign output no longer reads as running and then reports
success while the card beside it shows a failure.

Carry an explicit failed flag on a summarize round that ended in error, so the
partial deltas already streamed into the slot are no longer presented under the
"Conversation summarized" label.

Also drop seven orphaned English locale keys this branch left unused, which
were failing the unused-i18n static check.

* fix(client): address second round of Codex review findings

Reuse the shared Button primitive for the three question move controls (the
chat card's chevron and both popover chevrons), which each repeated the same
hover, focus-ring, color and rounding recipe locally. Only the icon geometry
stays local.

Drop provider image results that carry neither thumbnailUrl nor imageUrl.
Both are optional in the ImageResult contract, and an unusable entry still
made images.length nonzero, so the card rendered an anchor and img with
undefined destinations instead of omitting the result.

Gate the memory deletion confirmation on a completed phase. The panel opens as
soon as the key streams in and the phase can still settle as cancelled, so
"Memory deleted" was claiming a removal that never happened while the header
correctly read Cancelled.

Key pending answer drafts by action id instead of a single shared slot. With
Save drafts disabled, editing a collapsed question in one conversation and
then editing another paused conversation's question overwrote the only slot,
and the action-scoped reader then showed the first card an empty box with its
unsent answer unrecoverable. Entries are dropped once answered.

* fix(client): address third round of Codex review findings

Reuse the shared CopyButton for the handoff instruction copy control, which
recreated hover, focus-ring, opacity, rounding and copied-state appearance
locally. The icon crossfade and tooltip now come from the shared primitive and
only the reveal-on-hover behavior stays local.

Keep unlabeled commentary out of collapsing tool groups. An unlabeled group
auto-collapses once complete, so folding commentary in hid the assistant's
prose behind a generic action header. The flush now splits the block at
commentary and groups each surrounding run on its own, restoring the shape the
previous fallback had while keeping reasoning folded in.

Drop shopping results without a link and places with nothing to name, for the
same reason the image results are filtered: every provider field is optional,
and an unusable entry still made the array nonempty, so the card rendered an
anchor with no destination that looked actionable but could not be opened.

* fix(client): address fourth round of Codex review findings

Move the disclosure chevron appearance into @librechat/client as
disclosureChevronVariants, owning the hover/focus reveal, the motion and the
open rotation. The four tool, search, memory and reasoning surfaces now pass
their expanded state and keep only icon geometry local, so a change to the
shared behavior reaches all of them. Panel spacing stays feature-local, being
genuine layout.

Require a navigation target on image results, not just an image source: a
thumbnail-only entry passed the previous guard and then rendered a styled
anchor with an undefined href, looking actionable but opening nothing.

Exclude closed run steps from the pending-auth predicate. ToolCall already
hides the sign-in button on a terminal status, so a persisted OAuth call whose
progress never reached 1 left the group showing a trust warning with no
authentication action behind it.

Copy handoff instructions through copy-to-clipboard, as the sibling
message-content controls do. navigator.clipboard is undefined on a non-secure
origin, where dereferencing it threw before the rejection handler could run and
the button silently did nothing.

* fix(client): address fifth round of Codex review findings

Compose the shared Button through HoverCardTrigger's asChild for the web search
details trigger, which recreated rounding, hover colors, focus ring and motion
locally. This also replaces Radix's default anchor with a real button. Only the
hover-card reveal and the icon geometry stay local.

Copy compact reasoning through copy-to-clipboard for the same reason as the
handoff control: navigator.clipboard is undefined on a non-secure origin, where
dereferencing it threw before anything was copied.

Document the streaming-peek fade as a narrowly scoped custom-CSS exception. It
is a mask-image stencil rather than paint, so only its alpha channel is read
and no theme role could meaningfully restyle it.

* fix(client): address sixth round of Codex review findings

Recognize the batched-edit separator pair for every edit in a diff preview.
formatEditPreview writes a `--- old_text N` / `+++ new_text N` pair before each
edit's `@@`, but the parser gated on `inHunk`, which is never reset, so only
the first pair was skipped and every later one was counted as a deletion plus
an addition and rendered as a marker row. Matched by name instead, which leaves
content lines that merely begin with `-` or `+` alone.

Compose the shared Button for the popover's type-below hint, suppressing only
the fill the way Summary's quiet text buttons already do, so the focus ring and
disabled handling come from the shared recipe.

Render an answer box that carries only snippetHighlighted. It is independently
optional from snippet, and the details card opens for any answer box, so such a
result previously showed a heading with an empty body.

* fix(client): match synthetic edit headers only in separator position

Matching the marker names alone was wrong: deleting a real `-- old_text`
comment line, as SQL and Lua use, is prefixed to exactly `--- old_text`, so the
previous guard discarded a genuine changed line from both the preview and the
statistics. The pair is now skipped only in separator position, adjacent and
immediately followed by a hunk header, which no run of genuine content
satisfies. Covered by a test asserting such a pair inside a hunk survives as
content.

Also drops the em dashes from the comments added over this review pass.

* fix(client): address eighth round of Codex review findings

Compose the shared Button for the compact reasoning disclosure, keeping only
the row geometry local so the focus ring and disabled handling come from the
shared recipe.

Lazy-mount the compact reasoning body with useLazyCollapseBody, as the
standalone panel already does. Collapsed is the default whenever thoughts are
hidden, and a streaming THINK part re-renders on every delta, so the full text
was being mounted and laid out behind an invisible panel.

Classify grouped memory failures with isMemoryFailureOutput. Those tools report
failure in prose that generic isError parsing does not recognize, so a
persisted call with no terminal status showed a failed card inside a group
reporting success with no failure count.

Announce the diff statistics to assistive technology. The +/- glyphs carry
their meaning through color and sign, so aria-hidden left screen-reader users
without the change summary; the counts are now also exposed as localized
screen-reader text.

* fix: persist failed summaries and stop double-rendering memory mutations

Stamp the failed marker on the aggregated summary part server-side, mirroring
how ON_RUN_STEP_CLOSED already stamps runStepStatus. The SDK aggregator ignores
a complete event that carries no summary, so an errored round's partial deltas
were saved unmarked and a reload re-rendered the truncated text under
"Conversation summarized".

Skip memory attachments that carry a toolCallId in the message-level
MemoryArtifacts decoration. Those calls already render inline as a MemoryCall
card with the same key, value and outcome, so one mutation appeared twice.
Attachments with no originating call keep the decoration as their only surface.

Keep a reasoning-bearing group expanded when Open Thinking Dropdowns by Default
is on. The folded-in THINK part only renders inside the group body, which is
not even mounted while collapsed, so the preference had no visible effect until
the action group was opened by hand.

Give same-named place results unique keys. Several branches of one chain share
a name and often carry no identifier, so rows whose address, rating and map
target all differ collided on one React key.

* fix: adopt the shared code surface and count background task failures

Register surface-code in the versioned theme registry and use it for the diff
preview. The token, its light and dark CSS values and its Tailwind mapping were
already in place and already consumed by CodeBar, CodeBlock and ResultSwitcher;
only the three theme interfaces, the two bundled themes and DiffView were
missing. DiffView no longer coordinates two unrelated surface roles through a
dark: override, and a custom theme can restyle the code surface centrally.

Include background-task failures in grouped outcomes. A backgrounded bash or
code task reports its verdict through a background_task_status attachment
rather than its output, and its dispatch step keeps a benign handle and usually
closes as completed, so the group reported no failed action beside a card
showing failure. Group metadata now derives that signal with the same helpers
the child card uses, correlated per part so a handoff response repeating a
provider tool-call id across agents still routes correctly.

Require a title on shopping results. A link-only card had no accessible name
and no visible identity: the anchor carried no label, its image is decorative
and the title span rendered empty.

* fix(client): compose shared buttons for two disclosures and seed re-enabled ask drafts

Compose the shared Button for the memory-artifacts and web-search disclosure
rows, keeping only their geometry local. The web-search row keeps its instant
hover by suppressing the recipe's color transition, since the chevron beside it
reveals without a fade and the existing test pins that.

Seed the ask-specific draft when Save drafts is re-enabled. An answer captured
while saving was off has no persisted ask draft for autosave to restore, so
expanding opened an empty composer and the next collapse read that empty value
back over the in-memory answer.

* fix(client): surface cancelled actions and protect the released composer

Track cancellation separately from failure in grouped tool metadata and name it
in the group header. A stopped step is settled and not an error, so the group
auto-collapsed under a success-sounding header with the only cancellation
notice hidden inside the panel it had just closed.

Preserve an ordinary unsent message across an ask handoff. With Save drafts
off, collapsing a question releases the composer; typing there and then moving
the question back overwrote that text with the answer and lost it. The released
text is now stashed per pending action and handed back on the next collapse.

Skip the named view transition for batched questions. Only the single-question
surfaces declare view-transition-name: ask-question, so wrapping a batch
handoff gave the browser nothing to pair and it cross-faded the whole root
instead of morphing the question.

* fix(client): restore the released composer text after answering

Submitting an answer from the expanded card never goes through collapse, so the
ordinary unsent message stashed when the question was moved back was never
handed over and its entry leaked. The resume success path now restores it in
place of the reset when one is stashed, and drops the entry either way. Read
through a ref because the callback settles long after the render that armed it.

* fix(client): stop stacking search snapshots and fix three identity defects

Upsert re-emitted web-search attachments instead of appending them. The search
helper rewrites and re-emits the entire payload after every highlight update,
keeping the same type, toolCallId and turn, and those attachments carry no
file_id so the existing upsert never saw them. Each snapshot was appended, so
collectSearchVerticals concatenated one copy of every image, product and place
per update. Keyed by type, tool call and turn, replacing wholesale since the
incoming payload is complete.

Preserve MCP identity in the tool-call label. function_name has already had the
MCP delimiter and server stripped, so re-parsing it classified an MCP function
sharing a built-in's name as that native tool and both showed and announced an
unrelated label.

Qualify grouped tool identity by agent. Provider tool-call ids repeat across
agents in a handoff transcript, and a lone tool with reasoning now groups too,
so two sibling groups shared one React key and one expansion override.

Compose the shared Button for the handoff disclosure, keeping only its geometry
local.

* refactor(client): build edit previews structurally instead of round-tripping diff text

The args preview was formatted into unified-diff text purely so parseUnifiedDiff
could read it back, and the separators that round trip needed between batched
edits are byte-identical to a real changed line: deleting a source line
`-- old_text` prefixes to exactly `--- old_text`. Neither the marker names nor
their position could tell the two apart, so the parser either inflated the
statistics or dropped a genuine edit.

buildEditPreviewDiff now constructs the preview's lines from the structured
edits, so edit boundaries are structural and no separator is ever emitted.
parseUnifiedDiff is back to parsing only real tool output, where `--- ` and
`+++ ` are genuine file headers, and it no longer special-cases synthetic
markers at all. Copy text comes from a one-way serializer.

Also include agent identity in the web-search snapshot key: handoff agents
repeat provider tool-call ids, so without it one agent's search results
replaced another's.

* fix(client): stop counting empty edit sides as changed lines

A pure deletion (`new_text: ""`) rendered a blank green row and reported one
addition, because `''.split('\n')` yields one element. A trailing newline did
the same at the end of either side. Both sides now go through one helper that
treats an empty side as no rows and a trailing newline as a terminator. The
defect predates the structural builder; it was carried over from the string
preview it replaced.

* fix(client): restore the released text for non-text answers too

Only the free-text path sets consumedComposerText, so gating the restore on it
discarded the stashed ordinary message whenever the user answered by clicking an
option or skipping, while the deletion below ran regardless. The stash is now
restored whenever one exists, independently of the reset condition, and it
outranks whatever the composer holds since that is the answer draft the
submission just consumed.

* fix(client): make group identities collision-proof and localize handoff labels

Disambiguate duplicate tool-group identities by how many earlier groups already
claimed the same provider tool-call id. Those ids repeat across agents in a
handoff transcript and restart per turn within one agent, and a lone tool with
reasoning now groups too, so sibling groups could share a React key and one
expansion override. Occurrence order is stable because groups are append-only,
and the first occurrence keeps the bare id, so an id that never repeats is
unchanged and still survives a content-index shift.

Restore a stashed ask message regardless of the current Save drafts setting. The
stash is only ever created while saving is off, so it never reached the
conversation draft; gating the restore on the setting dropped it whenever the
user enabled saving between expanding and collapsing.

Localize the handoff field labels the SDK defines (instruction, instructions,
context). Any other key is an admin-authored promptKey from the agent graph, so
it stays as written, like an agent's own name.

* fix(client): reject unsafe vertical links and scope group identity message-wide

Filter provider-supplied vertical URLs through the markdown allowlist. Search
result payloads are copied into the attachment without validation, so an image
or shopping target could be `javascript:` or another non-network scheme and the
card handed it straight to href. The same helpers are used when admitting a
result and when rendering it, so the two cannot disagree.

Derive tool-group identity from a message-wide occurrence ordinal instead of a
per-instance counter. Phase slices render through separate nested ContentParts
that share the expansion map, so a per-instance count restarted and let a later
slice inherit an earlier group's override. The ordinal is stable under
content-index shifts, and ordinal 0 keeps the bare id, so a group keeps its
identity when a completing phase moves it into a slice.

Build group attachments as a union. Repeated provider ids inside one group
resolve to the same bucket, so appending per part rendered each file and search
snapshot once per repeated call.

* fix(client): let an output diff supersede a create preview, and guard two edges

A diff in the output now supersedes everything, including a create's authored
content. `create_file` overwriting an existing file returns a summary plus a
unified diff, and preferring the authored content there rendered that diff
twice: once through DiffView and again verbatim as the raw output section. This
restores the precedence the string-preview version had.

Give image tiles distinct React keys. Syndicated images reuse one thumbnail
across results that link to different pages, and grouped searches merge
attachments, so the source alone collided.

Require the composer to still hold the submitted text before restoring the
stashed ask message. The textarea stays editable while the resume is in flight,
so anything typed since is newer than both the stash and the answer.

* fix: address remaining Codex findings after dev rebase

Stamp agent ownership on streaming and final search snapshots. Compose the shared floating thought button. Preserve rebased group behavior, correct stale test selectors, and keep expansion callbacks outside state updaters.

* Resolve follow-up review findings

* Scope grouped background verdicts by execution step

* Fix canonical artifact ownership and frontend review regressions

* Fix terminal answer handoff and encoded edit previews

* style(client): keep the search rows on dev's glyph rail

The rebase onto dev landed both halves of #15643's row rail except in
`WebSearch`, whose completed row had since moved its glyph into a shared
`Button` and whose streaming row kept a 10px gap. Restore the shared
`ROW_GLYPH_SLOT` around the completed row's favicon stack or globe and
drop the streaming row's gap to 8px, so both search rows put their glyph
on the avatar's axis and their text where the header's name starts.

* fix(client): pass the thinking preference into ReasoningCompact

`showThinking` is an app-global display preference the group only reads,
and `ToolCallGroup` already receives it from its host. `ReasoningCompact`
still reached for `showThinkingAtom` itself, coupling a grouped thought
to `~/store` and blocking the move to a feature-owned workspace. It
takes the preference as a required prop now, from the value the group
already holds.

* test(client): pin both web-search rows to the shared glyph rail

The rebase onto dev silently dropped `ROW_GLYPH_SLOT` from the completed
row — its glyph had since moved inside a shared `Button` — and left the
streaming row on a 10px gap, so nothing caught either. `Part.tsx` routes
web search past `ProgressText`, so this renderer owns its glyph and has
to take the slot itself; the test fails on both regressions.

* fix(client): keep grouped markers and folded search media visible

Two things a fold could swallow.

A detached-subagent projection is an empty THINK part flagged
`reasoning_unavailable`, which `Part` renders as a `ReasoningMarker`.
`ToolCallGroup` sent every THINK part to `ReasoningCompact`, which has
no text to show and returns null, so the marker disappeared the moment
its call joined a group. Those parts go back through the standalone
renderer.

A phase hoists its span's media out of the fold, and the nested segment
renders with `hideAttachments` so a `WebSearch` row inside it stands
down for that hoist. The hoist was `AttachmentGroup` alone, which drops
`web_search` attachments outright, so a folded search lost its images,
products and places instead of lifting them out. The card renders
`SearchVerticals` beside the attachment row, mirroring `ToolCallGroup`.

* fix(client): recover a released composer stash on revisit

Recovery of the ordinary unsent message stashed while the card owns the
composer was gated on `lastAnswerableRef` — what this hook happened to
observe. Navigating away mid-resume clears that ref while the stash
rightly stays put, so a resume that succeeded or expired while the user
was elsewhere left nobody to hand the message back: returning to the
conversation found `answerable === false` with no ref, exited early, and
the text sat unreachable in `releasedComposerTextAtom` for the session.

The stash carries its conversation now, and recovery keys on that, so a
revisit is a hand-back like any other exit. Only the exit this hook
armed knows what the composer held when the resume started; on a revisit
an empty composer is the only target that cannot overwrite something
newer, and either way the entry is dropped.
2026-09-06 14:56:50 -04:00
Danny Avila
0fa313443d
🛅 feat: Add Agent File Management APIs (#15666)
* feat: expose agent file list and unlink API

* feat: add agent file upload management route

* fix: harden agent management file uploads

* fix: coordinate agent upload limits across replicas

* fix: keep agent upload coordination active

* fix: validate agent uploads before processing

* fix: reject unusable agent file uploads

* refactor: move agent upload lock into api package
2026-09-06 14:35:34 -04:00
Danny Avila
9089d8cba8
🚮 fix: Require Sign-In After Missing OpenID Sessions (#15655) 2026-09-06 12:47:58 -04:00
Danny Avila
aeac7a2065
🪪 feat: Add Per-Agent Git Identity (#15628)
* feat: Add per-agent Git identity

* fix: annotate git identity schema

* fix: complete git identity controls

* fix: clear git identity on version restore

* fix: Require a complete agent Git identity

* fix: Complete Git Identity Across Bash And Form Validation

* fix: Discard Incomplete Hidden Git Identity Edits

* fix: validate Git identity across panel lifecycle

* fix: preserve saved Git identity when discarding drafts
2026-09-05 23:56:23 -04:00
Mihidum
54511b2b8c
🧠 fix: Return 400 for Invalid Memory Keys (#14618)
* fix: return 400 for invalid memory key format instead of 500

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: trim PATCH rename key to match POST normalization

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: return 400 when PATCH rename key is not a string

A non-string `key` in the PATCH body (e.g. {"key": 123}) previously fell
back to the URL key and updated the memory with a 200, hiding the invalid
field. Reject any defined non-string key with 400 before normalization.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: share memory key validation between schema and routes

* fix: reject blank memory rename keys

* test: use real data-provider exports in memory route suite

* fix: share memory key validation with ID updates

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com>
2026-09-06 04:34:06 +02:00
Ravi Kumar L
000349681e
🩻 feat(insights): Scope Insights to Authorized Agents (#15549)
Some checks failed
Docker Dev Images Build / publish (push) Has been cancelled
Sync Helm Chart Tags / Ignore non-main push (push) Has been cancelled
Sync Helm Chart Tags / Sync chart tags (push) Has been cancelled
* feat(insights): add agent-scoped access

* fix(insights): exclude unattributed assistant messages

* fix(sharing): key role insight toggles by principal

* fix(sharing): preserve insight grant snapshot

* fix(permissions): preserve insight bits atomically

* fix(permissions): guard insight audit rollback

* fix(insights): keep admin grant controls accessible

* fix(permissions): reconcile duplicate principal updates

* fix(insights): show automatic admin access

* fix(permissions): harden insights access updates

* fix(insights): simplify authorization and preserve client state
2026-09-04 20:16:58 -04:00
Danny Avila
57c52de33c
🛎️ fix: Start Code Environment Reconciliation After Mongo Connects (#15620) 2026-09-04 19:08:44 -04:00
Danny Avila
3d085b227d
🛰️ feat: Show BYOM Worker Readiness (#15618)
* feat: Show BYOM worker readiness

* test: Exercise approved BYOM commands end to end

* test: Wait for BYOM worker readiness
2026-09-04 19:02:35 -04:00
Danny Avila
5e3cdd0b2c
📮 fix: Consume an Invite Only Once the Account Exists (#15611)
* 📮 fix: Consume an Invite Only Once the Account Exists

`checkInviteUser` deleted the invite token and then called `next()`, but everything
that can still reject a registration runs after it: the schema, the allowed-domain
check, and the email-already-in-use check. A mistyped password confirmation therefore
destroyed the invite — the invitee corrected it, resubmitted, and got "Invalid invite
token" with no way back short of an admin re-inviting them.

The deletion moves to `registrationController`, after `registerUser` reports success.

That report needed a new signal. `registerUser` returns the same 200 and the same
generic message whether it created an account or found the email already in use —
deliberately, so the response cannot be used to enumerate accounts — so the status
alone cannot say whether an account exists. It now also returns `userCreated` on the
creation path, which the controller reads and never forwards; the response body is
unchanged.

A failed deletion is logged rather than surfaced. By that point the account exists,
and leaving a usable invite behind is recoverable in a way that telling the user their
registration failed is not.

Fixes #15541

* ♻️ test: Fold the Invite Tests Into the Existing AuthController Spec

From Copilot's review. The new spec reached for `jest.requireActual` on
`@librechat/data-schemas`, `~/server/services/AuthService` and `~/models`, which pulls
real implementations into a unit test — `~/models` builds the data-schemas methods
against mongoose — and diverges from `AuthController.spec.js`, which stubs each module
outright.

Rather than restate that harness with narrower stubs, the tests move into the spec that
already has it. `deleteTokens` joins its `~/models` mock, which also keeps that shared
mock in step with the controller's imports: a stale mock there hands the controller an
undefined function, and the omission only surfaces when some later test happens to
exercise the path.
2026-09-04 15:38:32 -04:00
Danny Avila
fe30e3db32
🪫 fix: Back Off Failed Retention Deletes (#15608)
* 🧹 fix: Stop Undeletable Files Starving the Retention Sweep

`getExpiredFiles` returns the oldest `expiredAt` first, capped at `limit`,
and `processDeleteRequest` leaves the record in place when storage deletion
fails. Nothing records the failure, so the same files come back at the head
of the next batch an hour later, forever: no backoff, no cap, and — once
`limit` of them cannot be deleted — no file that expires afterwards is ever
swept again. On the deployment behind #15511 that is ~29k stranded objects
permanently occupying a 100-slot queue, which is why fixing the Code
Interpreter side alone (LibreChat-AI/code-interpreter#85) would not have
resumed deletion there.

Failures are now recorded on the file. `deletionRetryAt` holds it back with
a backoff doubling from one sweep interval to a day, and `deletionAttempts`
retires it from the query entirely once it reaches
`FILE_RETENTION_SWEEP_MAX_ATTEMPTS` (10, so roughly five days of retries).
Both fields are absent on existing records and absence means "never
attempted", so nothing already in the collection changes eligibility.

The record itself is kept rather than deleted — the reference is what an
operator needs to reconcile a bucket the sweep could not clear, and dropping
it would restore the silence that made this leak invisible. Raising
`FILE_RETENTION_SWEEP_MAX_ATTEMPTS` re-admits everything previously given up
on, which is the supported way to resume once the storage-side failure is
fixed; the give-up is logged with that instruction.

The counter is incremented server-side with `$inc` so concurrent sweeps on
separate nodes cannot overwrite each other's progress toward the cap, and a
failure to record a failure is logged and skipped rather than aborting the
rest of the batch.

* 🧭 fix: Delete Code Environment Files Through the Route That Exists

`deleteCodeEnvFile` tried `/sessions/:sid/objects/:fid` before falling back
to `/files/:sid/:fid`. Both have been there since #13424, but only the
second is mounted by any released codeapi — the first gained DELETE in
LibreChat-AI/code-interpreter#85 — so every deletion paid a guaranteed 404
and a wasted round trip, and #15511 read that 404 as the whole bug.

Call `/files/:sid/:fid` directly. It is the safe direction to collapse
toward: codeapi has mounted it since its first release, so this works
against older deployments as well as post-#85 ones, whereas keeping the
other path would not.

Collapsing the loop tightens two behaviours that only existed to serve it.
A 405 now surfaces instead of being swallowed on the way to a second
attempt; there is no second route to try, and a service that refuses the
method should say so. A 404 is still treated as "already gone" — that is
the only thing it can now mean — but it is logged rather than passed over
in silence, because a 404 caused by a misconfigured base URL looks
identical and this branch drops the file's metadata record either way.

* 🔒 fix: Settle sweep retry state from the write, not the read

Two findings from the review of 0e52924.

- `recordFailure` derived the attempt number by adding one to the count the
  batch had queried. Two nodes sweeping the same file read the same value,
  so both believed themselves to be the same attempt: each `$inc` landed,
  the stored count crossed `FILE_RETENTION_SWEEP_MAX_ATTEMPTS`, and neither
  caller ever saw the threshold. The file drops out of the query — the
  starvation guard still holds — but the give-up is never reported, and
  that log line is the operator's only notice, and carries the instruction
  for resuming. Return the count from the increment itself so every caller
  gets a distinct attempt number and exactly one observes the cap.

  The same staleness shortened the backoff, so `deferExpiredFile` now
  writes with `$max`: a deferral can only move later, and a node that
  computed a shorter delay cannot pull the file forward past one another
  node already committed.

- The backoff doubled from a hard-coded hour while claiming to start from
  one sweep interval. At the default they coincide; away from it the
  schedule stops meaning anything — on a six-hour sweep the first three
  attempts all land on consecutive passes, and on a five-minute one the
  first retry skips twelve. Derive the base from
  `FILE_RETENTION_SWEEP_INTERVAL_MS`, floored at a minute so a
  pathologically short interval cannot spend the whole give-up budget on a
  transient outage.

* 🧯 fix: Keep the give-up notice and the retry budget honest

Four findings from the review of ee1bac5.

- The give-up was reported after the deferral write, inside the same catch.
  Once the increment lands the counter is durable, so `getExpiredFiles`
  already excludes the file; a deferral that then failed left only the
  generic recording error and dropped the one line naming the file and
  saying how to resume. Report it as soon as the increment returns, and let
  the deferral fail on its own.

- Retry deadlines were measured from `Date.now()` after the deletion I/O,
  but `startExpiredFileSweep` arms its interval before the sweep runs. A
  one-interval delay therefore expired just *after* the next scheduled
  pass, which skipped the file and pushed its first retry out by a whole
  extra interval — and the same drift applied to every delay that is an
  exact multiple. Anchor deadlines to the sweep's start instead.

- The threshold used `>=`, so once two nodes pushed a file past the cap
  every one of them past it logged the give-up: one error per replica per
  exhausted file rather than one actionable notice. Only the attempt that
  lands exactly on the cap reports it.

- Retry state outlived the content it described. `processCodeOutput` reuses
  a record for a repeated `(filename, conversationId)` — new bytes, new
  storage key, and a fresh `expiredAt` from `getRetentionExpiry` — while
  `createFile` and `updateFile` set only supplied fields. A record carried
  to the cap by its previous content stayed excluded from the sweep
  forever, stranding the new object exactly as this PR set out to prevent;
  a partially failed one started the new object's budget already spent.
  Both write paths now clear the fields: the budget belongs to the storage
  a record currently points at.

The retry-state fixtures in `file.spec.ts` were seeded through `createFile`,
which now clears them, so they drive the real methods the sweep uses.

* 🎯 fix: Clear the retry budget only when a retention lifecycle starts

Both findings from the review of 8d26f9b, and both are consequences of that
commit's reset rather than of the original change.

- The reset was unconditional on every `createFile`/`updateFile`, on the
  reasoning that those paths write content. Two of them do not.
  `prepareImages{Local,Azure,Firebase}` call `updateFile({ file_id })` with
  nothing but the id — a TTL touch — every time an existing image is
  encoded for another chat, and the deferred preview uses the same method
  to transition `status`. Either handed a stranded record a fresh set of
  attempts and another give-up notice, on repeat, defeating the cap for the
  files most likely to be stranded.

  Gate it on the write actually setting `expiredAt`. The budget belongs to
  a retention lifecycle: that is the write which starts a new one, it is
  what `processCodeOutput` supplies when it repurposes a record, and a
  record with no retention deadline is never swept, so the fields are inert
  there anyway.

- Both retry writes bumped `updatedAt`. `processCodeOutput` falls back to
  `updatedAt` as the writer-order stamp for records that predate
  `metadata.sourceDispatchedAt`, so a failed sweep landing mid-harvest read
  as a newer content writer and the harvest dropped its attachment. Mark
  them `timestamps: false`, for the reason `claimCodeFile` already does:
  bookkeeping is not a content write.

* 🅿️ refactor: Park exhausted files instead of excluding them

Three review rounds in a row found defects in how the give-up cap interacts
with record reuse, each in the fix for the last. That is a design error, not
a bug list: a permanent exclusion has to be bound precisely to the content
lifecycle it was recorded against, and File records outlive their content.
`processCodeOutput` repurposes a row for a repeated
`(filename, conversationId)`, `createFile`/`updateFile` set only supplied
fields, and `getRetentionExpiry` returns `{}` on a lookup failure so the row
inherits its old deadline — three separate ways for bookkeeping to survive
into a lifecycle it does not describe, each needing its own guard, and the
two retry writes needing to be lifecycle-conditional on top.

Remove the category instead. `deletionRetryAt` becomes the sweep's only
hold, and reaching `FILE_RETENTION_SWEEP_MAX_ATTEMPTS` parks the file for a
month rather than excluding it. The bound on the batch is the same — a
stranded file costs one slot a month instead of one an hour — but a deadline
that outlives its content can only delay the next object, never lose it, so
nothing outside the sweep has to reason about this state at all.

That deletes more than it adds:

- `createFile` and `updateFile` go back to their original form. No reset, so
  no question of which writes install content, and `prepareImages*` and the
  deferred preview stop mattering here.
- `getExpiredFiles` loses `maxAttempts` and its `$and`; eligibility is one
  `$or` on the deadline.
- The interleaving race between the increment and the deferral degrades from
  a stranded object to a delayed one.

Working through a large backlog is throughput-bound either way: every
attempt costs a slot in the bounded batch, so N stranded files need N ×
`FILE_RETENTION_SWEEP_MAX_ATTEMPTS` passes to settle. Lower that limit when
recovering a deployment that has accumulated many.
2026-09-04 15:38:17 -04:00
Danny Avila
c302ae6f35
🪁 fix: Honor Endpoint Drop Params in Parameter Panels (#15610)
* Remove parameters from UI when parameter is dropped through dropParams

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Addressed copilot and codex review suggestions

* 1. Normalize drop parameter names in client/src/components/SidePanel/Parameters/Panel.tsx
  Admin-configured dropParams for Azure/OpenAI-compatible custom endpoints use the effective backend field names (maxTokens, topP, frequencyPenalty, presencePenalty), but the panel's filter compared them against the UI's
  snake_case keys (max_tokens, top_p, etc.), so the controls stayed visible and silently discarded whatever the user set. Added a dropParamsBackendToUIKey map (in packages/data-provider/src/parameterSettings.ts) and normalize
  each dropParams entry through it before filtering.

  2. Apply the same drop-parameter filtering in client/src/components/SidePanel/Agents/ModelPanel.tsx
  The Agent builder's model panel built its parameter list independently and never consulted endpointsDropParamsMap at all, so it kept offering controls for Azure/custom providers whose values the backend drops. Reused the
  same resolution logic (including the new backend→UI key normalization) there, sourced from useGetStartupConfig.

  3. Remove any escapes from Azure fixtures in packages/api/src/app/config.test.ts
  Three tests built azure groupMap/modelGroupMap fixtures via ... as any as AppConfig['endpoints'], bypassing type checking for that shape. Replaced them with two typed helpers, createAzureGroupMap and createAzureConfig, built
  from the existing TAzureConfig/TAzureGroupMap/TAzureModelGroupMap types, so the fixtures are now fully type-checked with no any.

* HAL-1081 Deploy librechat open

  1. Gate the backend-name alias to OpenAI-compatible parameter sets (packages/data-provider/src/parameterSettings.ts)
  dropParamsBackendToUIKey had been applied unconditionally, rewriting a dropped topP to top_p even for a custom endpoint whose defaultParamsEndpoint is anthropic/google (or
  a native bedrock-* endpoint) — where topP is the UI key, so the rewrite broke hiding the control. Replaced the plain map with resolveDropParamsUIKeys(dropParams,
  endpointKey), which only aliases backend names for OpenAI-compatible endpoint keys (openAI, azureOpenAI, custom, openRouter) and passes native-provider keys through
  unchanged otherwise. Updated both Panel.tsx and ModelPanel.tsx to call it with overriddenEndpointKey, and added a resolveDropParamsUIKeys test suite in
  parameterSettings.spec.ts.

  2. Prune stale model_parameters when a control becomes hidden (client/src/components/SidePanel/Agents/ModelPanel.tsx)
  When a parameter an agent already had set gets added to its endpoint's dropParams, the control disappeared but the value stayed in model_parameters and was saved unchanged
  by composeAgentUpdatePayload — invisible to the user and silently reactivated if the endpoint later stopped dropping it. Added a useEffect, mirroring the conversation
  panel's existing pruning effect, that strips any model_parameters key no longer present in the currently-visible parameters list. Also fixed a pre-existing test regression
  (missing useGetStartupConfig mock) and added two tests covering pruning-on-drop and value retention when the control stays visible.

* fix: Preserve parameters for unknown agent providers

* fix: Sanitize agent parameters on submission

* fix: Preserve agent model overrides during pruning

---------

Co-authored-by: Marc Amick <MarcAmick@jhu.edu>
Co-authored-by: MarcAmick <5194465+MarcAmick@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-09-04 13:52:23 -04:00
Danny Avila
09da878a47
🚰 fix: Throttle Shared Link Reads and Aggregate Audit Findings (#15605)
* 🪵 fix: Aggregate Audit Findings and Rate Limit Shared Link Reads

Audit-mode content filter rules wrote one `logger.info` per matching
fragment, and inspection deliberately continues past every finding. A
shared conversation full of distinct matching strings therefore produced
one log write per fragment, regenerated on every retrieval of
`GET /api/share/:shareId` — a public, unauthenticated route with no
limiter. The 4,096-entry inspection dedupe set is a memory bound, not an
event budget: once full, further values are inspected and logged again.

Audit metadata carries no inspected text — only rule, source, field and
provenance — so thousands of those writes were byte-identical lines.
Findings are now counted inside an aggregation scope and reported once
per distinct key with an `occurrences` count when the scope ends:

- `assertModelBoundContent` opens a scope when audit rules are configured,
  bounding one inspection pass (a single message's fragments).
- `assertConversationImportContentAllowed` opens the outer scope for
  import and shared-link snapshots, so per-message inspections nest into
  one report instead of one per message.
- `createShareContentPreflight` spans the shared-file metadata pass too.

Nested scopes reuse the outermost aggregation, and outside any scope the
previous immediate write is kept.

`GET /api/share/:shareId` re-inspects the whole snapshot on every request,
so it now carries IP and user limiters like the neighbouring fork route
(`SHARE_IP_MAX`/`SHARE_IP_WINDOW`, `SHARE_USER_MAX`/`SHARE_USER_WINDOW`,
`SHARE_VIOLATION_SCORE`); the user limiter skips anonymous viewers.

* 🔒 fix: Address Codex Findings on Share Audit Aggregation

- The aggregation key joined rule fields with a space, but the filter
  schema allows spaces in custom pattern ids and labels, so
  `{id: 'a', label: 'b c'}` and `{id: 'a b', label: 'c'}` collided on the
  same source/field/provenance and merged two rules' counts under one
  identity. Serialize the tuple instead.
- `SHARE_VIOLATION_SCORE` left unset reached `logViolation` as
  `undefined`, which selects that function's default score of 1 rather
  than the documented zero. With default ban settings a viewer refreshing
  a rate-limited shared link would be banned after 20 rejections. Default
  the score to 0 in code, not only in `.env.example`.
- `removePorts` returns a full IPv6 address, so an attacker holding a
  prefix could rotate the host portion for a fresh bucket on every
  request — and for anonymous viewers the IP limiter is the only bound.
  Derive the key through `ipKeyGenerator` so IPv6 clients group by /56.
2026-09-04 12:38:34 -04:00
Danny Avila
7d9db14ba5
📓 feat: Author Files in Attached Workspaces (#15548)
* feat(code): route file mutations to attached workspaces

* fix(code): Inspect attached edits before commit

* fix(api): Annotate workspace limits

* fix(code): Normalize workspace edit previews

* style(api): Sort workspace imports

* fix(api): Preserve Workspace List Validation
2026-09-04 12:16:23 -04:00
Danny Avila
770238f22b
🔣 refactor: Replace Mongo Filters With Typed Criteria (#15580)
* ♻️ refactor: Take Typed Criteria, Not Mongo Filters, for Actions and Assistants

`createActionMethods` and `createAssistantMethods` accepted `FilterQuery<T>`,
putting Mongoose's query language in the package's public surface: every caller
wrote raw Mongo, and no engine other than Mongo could satisfy the signatures.

Both now take domain criteria — `ActionQuery` and `AssistantQuery` — naming
concepts rather than stored fields, with an array meaning "any of these". A
per-domain field map translates them, so `FilterQuery` survives only inside the
two translators.

`buildFilter` throws on a criterion the field map does not cover. Callers in
`api/` are JavaScript and get no compile-time checking, and the server sets
`strictQuery`, under which a silently dropped criterion widens the filter
instead of narrowing it — an unscoped `findOne` returns an arbitrary document
rather than none. Failing closed is the only safe default.

`AssistantQuery.avatarFilepath` covers the avatar-authorization lookup, which
queries a nested path no plain field name reaches.

No behaviour change: every migrated call site produces the same filter as before.

* 🧪 test: Update Avatar Authorization Assertion to Typed Criteria

`validateImages.spec.js` asserted the old `{ 'avatar.filepath': { $in: [...] } }`
call shape for `getAssistant`. The earlier sweep matched on `action_id`,
`agent_id` and `assistant_id`, none of which appear in a dotted avatar path, so
this one assertion was missed.

The `getAgent` assertions in the same file keep the filter shape — that method
still takes a `FilterQuery`.

* 🔒 fix: Reject Unknown Criteria Before Omitting Undefined Ones

`buildFilter` skipped a criterion whose value was `undefined` before checking it
against the field map, so a JavaScript caller misspelling a key that happened to
carry `undefined` — `deleteActions({ agent_id: maybeId })` — produced `{}` and
reached `deleteMany` unscoped. That is the exact failure the guard exists to
prevent, defeated by the order of the two checks.

Validate every key first, then apply the undefined-omission rule. The lookup is
an own-property check so inherited names cannot resolve through the field map's
prototype: `{ toString: 'x' }` previously found `Function.prototype.toString`,
passed the truthiness test, and wrote a garbage filter key instead of throwing.

A recognized criterion left `undefined` is still omitted, so optional parameters
keep working.

* 🔒 fix: Reject Query Fragments as Criteria and Keep the Translator Internal

Three review findings on the criteria translator, all of the same shape: the
guard was narrower than the surface it protects.

Criterion values are now validated as scalars or lists of scalars. `matchAny`
copied any non-array through unchanged, so a JavaScript caller could pass
`{ agentId: { $ne: null } }` and have the operator land verbatim in the filter
— the fail-open case the field map exists to close. `null` is rejected too; it
would have matched documents missing the field entirely.

`matchAny`, `buildFilter` and `FieldMap` are no longer re-exported from the
package barrel. They emit Mongo, and shipping them as public API undercut the
point of the change; they were reachable as `require('@librechat/data-schemas')
.buildFilter`. `OneOrMany` moves to `types/query` because the domain query types
reference it and it names no engine — which also drops the `types` -> `utils`
import.

`loadActionSets` names `ActionQuery` through `import()` so the JSDoc type
actually resolves.
2026-09-04 11:54:21 -04:00
Danny Avila
a21c7944ee
🏷️ fix: Record the Media Type of Saved Images, Not the Declared One (#15606)
`saveBase64Image` recorded the media type declared in the incoming data URL
while persisting bytes that sharp had re-encoded. Those are not always the same
format: sharp rasterizes SVG to PNG, so an image arriving as `image/svg+xml` was
stored as `<id>-<name>.svg`, typed `image/svg+xml`, holding PNG bytes.

That type is not cosmetic. `encode.js` hands `file.type` to providers verbatim —
`media_type` for Anthropic, `inlineData.mimeType` for Google, and the `data:`
prefix for OpenAI — so re-attaching such an image sends PNG bytes under a media
type the provider does not accept for images, and the request fails.

A declared type is also only ever a claim. The same mismatch arises whenever a
producer mislabels what it sends, which for MCP tool output means any connected
server can decide what the record says about bytes it did not have to match.

`resizeImageBuffer` already read the encoded output back to measure it, so it now
resolves that metadata to a media type and returns it, and `saveBase64Image`
records it in place of the declared one, falling back to the declared type only
when sharp reports a format that has no media type of its own. The upload paths
were already correct — they record `image/${imageOutputType}`, the format they
convert to — so this brings the tool-output path in line with them.

`resolveImageMimeType` lives in `packages/api` because AVIF and HEIC share the
heif container and are told apart by its compression, which is worth stating once
with tests rather than open-coding at each call site.
2026-09-04 11:51:28 -04:00
Danny Avila
fddf7e31f2
🛻 feat: Route Bash Through Attached Workspaces (#15546)
* feat(code): Route bash through attached workspaces

* fix(code): harden attached bash schema adapter
2026-09-04 11:49:51 -04:00
Danny Avila
e23e13e712
🌳 feat: List Attached Workspace Trees (#15527)
* feat(code): list attached workspace files

* test(code): include workspace list history

* fix(code): validate workspace tool scope consistently

* fix(code): Harden workspace listings

* fix(code): Align workspace list validation

* fix(code): Continue complete workspace listings

* fix(code): preserve canonical path protections

* test(code): keep workspace list specs type-safe
2026-09-04 10:52:34 -04:00
Marco Beretta
10c5c91594
🎨 feat: Theme-Adaptive SVG Support for Custom MCP and Group Icons (#13817)
* feat: theme-adaptive SVG support for custom MCP and group icons

Custom icons (MCP server iconPath, model spec groupIcon) were rendered as
plain <img>, so monochrome SVGs kept fixed dark colors and were nearly
invisible in dark theme.

Introduce a shared CustomIcon component that detects monochrome SVG glyphs
and tints them with currentColor so they follow the active theme, while
multi-color SVG logos and raster images keep their original colors. The
monochrome decision parses the SVG's color tokens; content is fetched once,
cached, and any failure falls back to the original image. Monochrome SVGs
render via CSS mask, never inlined, so no SVG markup reaches the DOM.

Apply across all custom-icon surfaces: MCP settings cards, the chat MCP
dropdown, stacked MCP icons, tool-call headers, and model group icons.

Also support SVG in the MCP avatar uploader: add SVG to the accepted file
types and sanitize uploaded SVGs with DOMPurify before storing them, and
make the dialog preview theme-adaptive via the same component.

Add unit tests for SVG detection, monochrome analysis, sanitization, and
CustomIcon rendering.

* fix: reset adaptive icon tint state when the source changes

A reused CustomIcon instance kept the monochrome verdict from a previous
source until its effect re-ran, so switching to a raster image or a new
multi-color SVG could briefly render it as a currentColor silhouette.

Key the resolved verdict to the current source and reset it synchronously
during render (seeding from cache when available), so a stale verdict can
never tint a different icon. Add hook tests covering the source change.

* fix: do not tint custom SVGs that have an opaque background

A grayscale SVG with an opaque full-canvas background (for example an
exported logo with a white background rect and a black glyph) passed the
monochrome check and was drawn through a CSS mask. Masks key off the alpha
channel, so the opaque background filled the whole area with the tint color
and the icon collapsed into a solid block.

Detect a full-canvas opaque background rect and exclude such SVGs from
tinting, rendering them with their own colors instead. Transparent
single-color and multi-shade glyphs remain tintable. Add tests for the
background cases.

* fix: detect opaque SVG backgrounds without a viewBox

Opaque background detection only read canvas dimensions from the viewBox, so
an SVG that declares width and height on the root element but omits the
viewBox slipped through and was tinted into a solid block.

Fall back to the root svg width and height when no viewBox is present, and
match attribute names exactly so stroke-width is not mistaken for the canvas
width. Add tests for the no-viewBox cases.

* fix: parse comma-separated SVG viewBox values

The viewBox regex only accepted whitespace between values, so a valid
viewBox like "0,0,24,24" failed to parse and an opaque background went
undetected, tinting the icon into a solid block. Accept commas and
whitespace as separators. Add a test for the comma-separated case.

* refactor: detect SVG tintability with DOMParser instead of regexes

The monochrome/tintable decision scraped SVG markup with regexes, which kept
missing edge cases (opaque backgrounds, missing or comma-separated viewBox,
stroke-width vs canvas width, embedded raster images).

Parse the SVG once with DOMParser and inspect real elements and attributes:
reject embedded <image>/<foreignObject> content, detect a full-canvas opaque
background rect, read the canvas size from the viewBox or root width/height,
and gather paint colors from attributes, inline styles, and <style> blocks.
Unparseable input is treated as not tintable. Tests cover these cases.

* fix: only tint single-tone grayscale SVGs

A grayscale SVG can draw its background as a full-canvas path (not just a
rect), e.g. a white background path plus a black glyph. The rect-only
background check missed that, and the icon flattened to a solid currentColor
block under the CSS mask.

Tint only when the SVG resolves to a single grayscale tone. Any second tone
(a background shape drawn as a path or rect, an accent, or a second shade)
now preserves the icon's own colors, which covers full-canvas path
backgrounds without per-shape geometry parsing.

* fix: count default black fill when detecting tintable SVGs

* fix: treat currentColor as a tone and stroked closed shapes as filled

* fix: ignore non-rendering template paint and count filled open paths

* fix: scan defs and symbol paint rendered through use references

* fix: resolve currentColor against fixed color and match style fills for default paint

* fix: treat alpha-zero fills as transparent in SVG tint detection

* fix: resolve inherited and CSS fill for backgrounds and default paint

* fix: resolve CSS currentColor and default-black use instances

* fix: count default-filled polylines when detecting tintable SVGs

* fix: resolve inherited fill and style/CSS opacity in SVG tint detection

* fix: ignore display:none shapes and stop counting CSS color as paint

* fix: only count CSS paints that match rendered elements

* fix: match root for CSS currentColor and skip unreferenced defs tones

* fix: count paint only on rendered shapes and filter hidden CSS currentColor

* fix: resolve use-instance currentColor and skip hidden use default fills

* fix: resolve CSS paints onto rendered painters and skip overridden use fills

* fix: keep checking ancestor opacity after resolving paint opacity

* fix: resolve CSS paints by specificity and skip transparent default fills

* fix: apply CSS over presentation attributes and follow nested use targets

* fix: strip CSS comments, honor visibility, and inherit paint through nested use

* fix: skip transparent svg use references

* Account for SVG filter colors

* fix: propagate outer use color through nested currentColor references

* fix: preserve url() id casing and record every nested use chain

* fix: preserve SVGs whose filters recolor the source

* refactor: detect monochrome icons via canvas pixel sampling

Replace the SVG source parser with offscreen-canvas pixel sampling: draw the icon, read pixel data, and treat it as monochrome only when every non-transparent pixel is grayscale within tolerance and the image has some transparency (a fully opaque image would mask to a solid block). Verdicts are cached per src.

An explicit monochrome flag on CustomIcon skips detection; sampling is the fallback. Image load failures and canvas taint from non-CORS cross-origin icons fall back to untinted rendering instead of throwing.

* harden custom SVG icon handling across security, a11y, and perf

Sanitize user-provided MCP iconPath server-side; the client-side
DOMPurify pass was bypassable by posting iconPath straight to the API.
Adds sanitizeMcpIconPath in @librechat/api (allowlist SVG sanitizer that
preserves case-sensitive names) and runs it in the create/update
controllers, plus a length cap on iconPath in the shared schema.

- gate theme detection to same-origin/data sources so a remote icon is
  no longer auto-fetched from every viewer's browser
- restore forced-colors (High Contrast) visibility and the broken-icon
  onError fallback for tinted icons
- mark redundant icons decorative to avoid screen-reader double reads
- base64-encode inlined SVG data URIs and bound the verdict cache
- harden the client SVG sanitizer and guard FileReader failures
- cover the tinted render branch, sanitizer allowlist, and edge cases

* fix: preserve local SVG references while stripping external hrefs

The hardened sanitizers dropped <use> and every href outright, blanking
self-contained exporter output like <defs><path id="p"/></defs>
<use href="#p"/> and gradients inheriting stops via href="#g".

Re-allow <use> and href/xlink:href on both sanitizers, restricted to
same-document fragments: the client uses a dedicated DOMPurify instance
with an afterSanitizeAttributes hook (kept off the shared default
instance), and the server mirrors the rule with a sanitize-html tag
transform plus an empty allowedSchemes list as a second layer. External,
protocol-relative, relative-path, and javascript: hrefs are still
stripped, leaving the element inert.

* fix: keep xlink namespace and safe filters in the server icon sanitizer

The server allowlist stripped xmlns:xlink from the root while keeping
xlink:href, leaving an unbound prefix that is a parse error once the
icon is stored as an image/svg+xml data URI, so SVG 1.1 exporter output
went blank after save. It also dropped <filter>/fe* primitives that the
client sanitizer's svgFilters profile allows, so icons relying on
effects like feDropShadow lost them between preview and reload.

Allow xmlns:xlink and mirror the client's filter allowlist (elements
plus their presentation attributes); feImage passes through the existing
fragment-only href transform, so external references are still stripped.

* fix: require empty pixels for tinting and block external url() references

Two issues from review of the icon sanitizer and monochrome detector:

- scanMonochrome flagged any pixel below full opacity as transparency,
  so an SVG that fills the whole canvas with a semi-transparent grayscale
  wash was tinted and rendered as a solid currentColor block. Require a
  genuinely empty pixel (alpha at or below the paint threshold) instead.

- The fragment-only reference rule only covered href/xlink:href, so a
  url() in filter/fill/mask/clip-path/style kept external targets like
  filter="url(https://evil/f.svg#f)". Both sanitizers now strip any
  attribute carrying a non-fragment url(), preserving local url(#id).

* fix: preserve internal SVG stylesheets while scrubbing their references

Exporter SVGs that store multi-color paint in an internal <style> block
(e.g. .red{fill:#e00} with class="red") lost all styling because the
sanitizers dropped <style> outright, so multi-color logos rendered with
default paints after upload.

Re-allow <style> on both sanitizers and scrub its CSS: strip comments
and @import at-rules and rewrite any non-fragment url() to none, keeping
local url(#id) paints. These icons only render in inert <img>/CSS-mask
contexts isolated from the host page (no script, and no subresource
loads once external refs are scrubbed), so a script-free stylesheet is
safe to keep; a premature </style> close still has its trailing markup
re-sanitized by the parser.

* fix: normalize icon value before deciding it is not an SVG data URI

A posted iconPath with leading whitespace or C0 controls (e.g.
"\n data:image/svg+xml,...") slipped past the anchored data-URI check,
so sanitizeMcpIconPath returned it raw while a browser trims the prefix
and still renders the SVG, keeping its external <image>/url() and other
stripped content. Normalize the value the way URL parsing does, trimming
leading/trailing C0 controls and spaces and removing embedded
tab/newline, before the SVG check so these variants are sanitized too.

* fix: cap sanitized icon length and re-encode as compact base64

The schema length check ran on the input, but sanitizeMcpIconPath then
re-encoded the markup with encodeURIComponent, which expands SVG by well
over the base64 input size (a 235KB base64 icon became a 374KB percent
string). create stored that over-limit value, and editing the server
resubmitted the prefilled value and failed MCPServerUserInputSchema.

Re-encode the sanitized SVG as base64 (far more compact for angle-heavy
markup, which sanitizing can itself grow via explicit close tags) and
drop anything still over MAX_MCP_ICON_PATH_LENGTH, so a stored icon can
never exceed the cap that a later edit re-validates against.

* fix: resolve CSS escapes before stripping external SVG references

A literal url(/@import matcher missed CSS-escaped references: a value
like style="fill:u\72l(https://attacker/x)" or an escaped @import
survived sanitization because the browser un-escapes \72 to r at
tokenization time while the regex never saw a url(...). The external
reference was then persisted and served to other clients.

Un-escape CSS the way a browser does (single pass over \hex and
\char escapes) before the url()/@import matchers run, on both the client
and server sanitizers. Also scrub the multi-declaration style attribute
in place instead of dropping it, so co-located local paint rules survive
while escaped external references are neutralized.

* fix: re-sanitize after scrubbing style blocks to block markup reintroduction

scrubStyleBlocks runs after sanitizeHtml and splices un-escaped CSS back
as raw markup, so an escaped sequence like \3c/style\3e\3cimage/\3e
(inert text during the first pass) became a real </style><image href>
element after unescaping, past the allowlist. Re-run the allowlist over
the scrubbed result whenever a <style> block was rewritten, stripping any
element the un-escaping surfaced while leaving legit local rules intact.

The client sanitizer is unaffected: it sets the scrubbed CSS as a DOM
text node, which serializes with < and > escaped, so no element is
reintroduced. Added a regression test pinning that behavior too.

* fix: make forced-colors icon tint override the inline background color

The forced-colors rule for .custom-icon-tint had no !important, so it
lost the cascade to the element's inline `background-color: currentColor`
and the masked glyph still blanked out in Windows High Contrast — the
exact regression the rule was meant to prevent. Verified in a real
forced-colors render: without !important the tinted icon is invisible;
with it the glyph paints in CanvasText and stays visible.

* fix: enforce icon length cap in the sanitizer, not the schema

The schema `.max()` on iconPath rejected the whole update at parse time.
A server whose stored icon predates the cap (previous versions allowed
large data-URI images) re-submits that value from the edit dialog, so
the user was locked out of changing any field or clearing the bad icon.

Drop the schema `.max()` and enforce MAX_MCP_ICON_PATH_LENGTH in
sanitizeMcpIconPath for every value type: an over-cap SVG is compacted
or dropped, an over-cap raster/URL is dropped. Editing a server with a
pre-existing oversized icon now succeeds and clears the icon instead of
failing validation.

* fix: decode XML entities and parse quoted URLs in SVG CSS scrubbing

Two more bypasses of the CSS reference scrubber, both live once the
stored image/svg+xml is parsed by a viewer:

- A <style> block reaches the scrubber as raw text, so an entity-encoded
  reference like &#64;import (or &#x40;import) was never seen as @import;
  the browser decodes it at render time. Decode XML character references
  (numeric + the five predefined named) before the matchers run.
- The url() regex excluded ')' even inside quotes, so a valid quoted URL
  like url("https://x/a)b") slipped through. Parse quoted and unquoted
  URL tokens separately so a ')' inside quotes stays part of the target.

Applied to both the server (sanitizeMcpIconPath) and client (sanitizeSvg)
scrubbers. Entity decoding also catches an entity-encoded </style> markup
breakout, which the re-sanitize pass then strips.

* fix: close custom icon review threads

* fix: transpile sanitize-html's ESM dependency chain in api jest runs

* fix: preserve marker definitions and fragment-only marker references

* fix: keep object-cover sizing when tinting masked icons

* fix: preserve textPath labels and currentColor color scopes in icon sanitizer

* fix: preserve pattern coordinate-system attributes in icon sanitizer

Keep patternUnits, patternContentUnits, and patternTransform so patterned
SVGs do not fall back to objectBoundingBox after server-side sanitize.

* refactor: sanitize icons with one shared DOMPurify policy

The server re-implemented DOMPurify's SVG profiles as two hand-written
sanitize-html allowlists, so every element and attribute the client kept had to
be transcribed by hand, and each miss surfaced as an icon that previewed
correctly and then lost its markers, patterns, filters, or xlink binding once
stored. Run DOMPurify on jsdom instead and share the config and reference hook
with the client, which drops both allowlists.

Restrict url() values to same-document fragments on every attribute rather than
on the marker properties alone, so external references in fill, stroke, filter,
mask, and clip-path are stripped as well.

Restore feDropShadow casing after sanitizing. DOMPurify has to parse as HTML,
its XML mode drops filter primitives and gradients, and the HTML tag-name
adjustment table predates that primitive, so it survived lowercased and left its
filter empty once the stored icon was re-parsed as image/svg+xml.

* fix: defer jsdom load until MCP icon sanitization

jsdom and dompurify were imported at module scope, so every
require('@librechat/api') paid their startup cost. Load them on first
SVG sanitize instead.

* fix: sort type import in MCP icon sanitizer

The static-check import sorter wants value imports before type-only
imports. Moving the DOMPurify type import after librechat-data-provider
clears the drift.

* fix: address PR review bot findings

chatgpt-codex-connector:
- Resolve icon URLs through new URL() instead of trusting a leading slash, so
  /\attacker.example/icon.svg is no longer treated as same-origin
- Check every url() token in an SVG attribute rather than only the first, and
  reject values carrying a CSS escape that would decode into one
- Forbid animateTransform, animateMotion, animateColor, and mpath, which the
  SVG profile admitted despite the policy intending to remove animation
- Preserve the radial-gradient fr attribute the profile omits
- Reject multi-tone grayscale in scanMonochrome, which a mask would flatten
- Sample at 128px so a small chromatic accent is not averaged away
- Settle a stalled icon load after 10s so its in-flight entry is released
- Bound the decoded SVG before building a jsdom tree for it
- Reject an oversized icon upload with a visible error instead of accepting it
  and silently clearing it on save

* fix: address Codex findings and trim icon sanitizer comments

- Bound icon files by size before reading or sanitizing them
- Track tone spread across every painted pixel, not only solid ones
- Settle monochrome detection on any sampling throw
- Use named DOMPurify/JSDOM types and shorten PR comments

* fix: percent-decode SVG data URI bodies before base64 decoding

* fix: declare the SVG namespace on sanitized icons and keep icon rejections out of form validity
2026-09-04 10:49:43 -04:00
Danny Avila
9a64e85b1e
🕯️ feat: Search Text in Attached Workspaces (#15525)
* feat(code): search attached workspaces

* fix(code): remove duplicate workspace type import

* fix(code): abort attached workspace searches

* docs(code): correct workspace abort parameters

* test(code): include workspace search history

* fix(code): keep workspace search foregrounded

* fix(code): preserve attached search routing

* fix(code): Bound workspace search output

* style(code): Format workspace search output
2026-09-04 10:07:06 -04:00
Danny Avila
b7fd4ba2a2
👓 feat: Read Attached Workspace Files (#15524)
* feat(code): read attached workspace files

* style(api): sort workspace handler import

* fix(code): abort attached workspace reads

* test(code): type workspace fetch doubles

* style(code): sort workspace bridge imports

* fix(code): Preserve workspace read boundaries

* style(code): Flatten workspace line validation

* fix(code): Bound attached workspace responses

* fix(code): Require canonical workspace paths

* fix(code): fence workspace bridge operations
2026-09-04 09:58:46 -04:00
Dustin Healy
5840e2f2ae
🪓 feat: Add Tenant-Scoped Agent Deletion (#15573)
* feat: add Agent Management delete endpoint

* fix: scope agent deletion cleanup by tenant
2026-09-04 09:51:12 -04:00
Danny Avila
30cd1c2f2e
🔇 fix: Stop logging an absent create_file target as an error (#15591)
Some checks are pending
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Codegraph E2E Votes / vote (full suite) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
`create_file` reads its target before writing so it can tell a create from
an overwrite, so `readSandboxFile` missing the path is the ordinary case for
a create — yet it was reported at error level, through `logAxiosError`, which
rendered the sandbox's own `cat: …: No such file or directory` as "An error
occurred while setting up the request" plus a stack. Every ordinary file
creation emitted an error-level entry claiming a transport fault about a file
that was written half a second later, and an operator reading it concluded the
file had been lost.

Split the two failures `readSandboxFile` was conflating. A request that never
completed still goes to `logAxiosError`; a request the sandbox answered with
stderr is now classified on that stderr — an absent path logs at debug, and
anything else (permission, a broken interpreter) keeps error level with the
sandbox's own wording. The thrown error is unchanged, so the authoring flow's
create/overwrite decision still reads it the same way.

The classifier moves to `packages/api/src/files/code/errors.ts` and is now
shared: `handlers.ts` had two near-duplicate copies of it, the narrower of
which documented itself as narrower than the broader one without either
deriving from the other.

Also carry the cause on `[preflightCodeOutputBatch] … could not be inspected`.
That warning follows each `create_file` in the same request, and the batch
discarded the error entirely — so a Code API that refused the download, one
routed to the wrong execution profile, and a file too large to inspect all
arrived as the same sentence, and neither this warning nor the one above could
be told apart from the failures around them. It goes through
`getSafeErrorMetadata`, which is what keeps the upstream message and the
artifact's name — both of which can echo submitted content — out of the log.
2026-09-04 09:21:24 -04:00
Dustin Healy
ab0d74b492
✏️ feat: Add Agent Management Update Endpoint (#15566)
Some checks are pending
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Codegraph E2E Votes / vote (full suite) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
* feat: add Agent Management update endpoint

* fix: reject unsupported Agent update values

* test: simplify Agent update mocks
2026-09-04 00:16:57 -04:00
Danny Avila
9a43362663
🪤 chore: Scope Assistant Tool-Resource Lookups (#15579)
`DELETE /api/files` looked the assistant up by `id`, but the Assistant schema
stores it as `assistant_id`. `api/db/connect.js` sets `strictQuery`, under which
Mongoose drops filter keys absent from the schema — so the lookup degraded to
`findOne({})` and returned whichever assistant happened to be first in the
collection, regardless of owner.

The unlink path then read that stranger's `tool_resources` and intersected it
with the caller's requested files, so a file the caller named could be unlinked
on the strength of another user's assistant record. With an empty collection the
same lookup returned `null` and the unguarded `assistant.tool_resources` threw,
answering 400 instead of completing the request.

Filter on `assistant_id` and guard the dereference. Adds three route tests that
mirror the server's `strictQuery` setting, without which the harness cannot
reproduce either failure.
2026-09-04 00:14:44 -04:00
Danny Avila
78b320cbbc
🗜️ fix: Bound Conversation Page Size (#15576)
`GET /api/convos` read its page size as `parseInt(req.query.limit, 10) || 25`
and handed it to `getConvosByCursor` unclamped, where it becomes
`.limit(limit + 1)`. `?limit=-1` therefore issued `.limit(0)`, which MongoDB
reads as no limit at all, and the route returned the caller's entire
conversation list in one response; `?limit=999999999` forced the same unbounded
fetch. `attachSharedFlags` then amplified it with a second query whose `$in`
carried every returned id.

Every other list route already clamps, so the fix reuses that shape: the
projects handler's local `normalizeLimit` moves to `packages/api/src/utils/query`
and both routes share it, and `getConvosByCursor` bounds its own page size so
the invariant holds for any caller.
2026-09-03 23:52:36 -04:00
Dustin Healy
2ffa9ec420
➕ feat: Add Agent Management Creation Endpoint (#15564)
* feat: add Agent Management creation endpoint

* 🧫 fix: Reject Null Agent Management Models (#15581)

---------

Co-authored-by: Danny Avila <danny@librechat.ai>
2026-09-03 23:45:04 -04:00