Commit graph

610 commits

Author SHA1 Message Date
Marco Beretta
5b8bb3c31f
⏱️ fix: Bound Remaining Outbound Calls With Timeout Budgets (#17468)
* fix: Bound outbound HTTP calls that had no timeout

Add timeouts.toolsMs, speechMs and imageGenerationMs to the timeouts block and apply the
existing budgets to the RAG delete paths, built-in tool APIs, TTS/STT providers (TTS also
aborts when the client closes), Stable Diffusion, Firebase reads and Mailgun. Calls made
before app config exists (remote config, RAG health, service key URL, Google refresh) get a
fixed 10 second budget.

* fix: Honor configured budgets for RAG deletes and per-chunk TTS deadlines

* refactor: Share one budget helper between speech and image CJS callers

* test: Cover a stalled RAG delete with a mock scenario

* test: Wait for the RAG embed before stalling the delete

* test: Embed at upload so the stalled delete has a vector to remove

* fix: Close a started TTS response on a late chunk timeout and share the service budget helper

* fix: Fail startup when the remote config fetch times out
2026-10-29 09:55:18 +01:00
Marco Beretta
65d0ba8563
🧯 fix: Return Approved Tool and Generation Error Text Instead of Raw Exceptions (#17508)
* fix: Return approved tool and generation error text instead of raw exceptions

* fix: Redact generation error text without the data-schemas helper

* fix: Redact credentials and emails from shown generation errors

* refactor: Move the Wolfram status policy into packages/api

* test: Fix the Wolfram probe constructor and jest summary match

* test: Match the jest pass count through color codes

* fix: Redact credentials a tool input error echoes from its arguments

* fix: Drop free-text fields from typed generation errors under a content policy

* fix: Keep only the code and numeric fields of typed errors under a content policy
2026-10-28 00:39:01 +01:00
Danny Avila
8c51a3f9f8
🙈 feat: Let Config Profiles Hide librechat.yaml MCP Servers and Remove Their Fields (#17327)
* 🙈 feat: Let Config Profiles Hide librechat.yaml MCP Servers and Remove Their Fields

Config profiles are the `__base__`, role, group and user documents written through `/api/admin/config`. A profile can tombstone `mcpServers.<name>`, and the merge then removes that server from the principal's resolved `mcpConfig`.

* 🛡️ fix: Apply MCP Hiding to Server Instructions, Failed Removals and the Startup Audit

- Server instructions bound for the model now leave out librechat.yaml servers hidden from the acting user, including one a model spec pins. `applyContextToAgent` passes the request user through `formatInstructionsForContext`, which drops the user's hidden set from the user-less catalog it reads.
- A config-tier candidate that removes a librechat.yaml value (a field, or a key of a record such as `headers`) and fails inspection now stands as a failed config-source entry instead of falling back to the librechat.yaml base that still carries the removed value. A failed change that removes nothing still falls back, and an entry with no transport (fields written over a hidden server) keeps the documented librechat.yaml fallback.
- The startup tombstone report reads every tenant's profiles in the system tenant scope, so it also runs from entry points without an outer system scope under strict tenant isolation, and names each profile's tenant.

* 🗂️ fix: Project the Startup MCP Tombstone Report Query and Run It Alongside Connections

* 🔑 fix: Keep Removed OAuth Headers Out of the MCP OAuth Callback

* 📝 docs: Note That Removed OAuth Headers Stay Out of MCP Sign-In

* 🔐 fix: Recheck the MCP OAuth Flow's Server Before Initiation Redirects

OAuth initiation redirected to a flow's stored authorization URL, or started
a new authorization from the flow's stored server URL, without resolving the
server again, so a principal whose profile hid the server after the flow was
created could still be sent to its authorization endpoint. The callback's
active-server check and its OAuth header fallback lived in the CJS route.

resolveMCPOAuthTarget (packages/api/src/mcp/oauth/target.ts) now owns both:
it resolves the server in the principal's current config with a strict read,
refuses a flow admitted for another server, a server the principal can no
longer use, or a redefined one, and selects the headers the flow sends (the
initiation snapshot, else the principal's config). Initiation calls it before
either redirect (404 or 400); the callback calls it before the exchange and
from the token-store fence.

* 📝 docs: Note That a Hidden MCP Server Ends OAuth Sign-Ins Already Started

* 🚩 feat: Publish the yamlMcpHide Admin Config Meta Flag

Profiles can hide librechat.yaml MCP servers and a hidden server is an
access boundary, so GET /api/admin/config/meta now reports
features.yamlMcpHide for the admin panel to gate its hide UI on. The
meta.spec probe checks the behaviour itself: the admin API stores an
mcpServers.<name> tombstone, the merged config drops the server, the
registry withholds it from principal lookups and checkout but not from
app-level lookups, process-backed servers stay, and an unreadable
principal config withholds every hideable server.

* 🧪 test: Align MCP Tombstone Specs With the Portable Config Store

The admin config handlers now write whole documents through
writeConfigDocument, so the end-to-end tombstone spec wires it in place
of the removed upsertConfig/patchConfigFields deps. A reset of a whole
MCP record now also prunes the parents it leaves empty.
2026-10-22 14:10:31 +02:00
Marco Beretta
8718338728
⏱️ fix: Bound Outbound Calls Made Inside a Request (#17263)
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/chat (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
* fix: Bound Outbound Calls Made Inside a Request

RAG queries for file search and message context, OCR provider calls,
action HTTP calls, the moderation check, the stored-image fetch for
base64 providers, and Flux result polling had no timeout. A stalled
upstream hung the chat turn, the upload or the tool call indefinitely,
and Flux kept polling forever on statuses that never become Ready.

Each now runs under a budget from a new librechat.yaml timeouts block
with finite defaults (getOutboundTimeoutMs in @librechat/api). Action
calls also receive the run's abort signal, so stopping a run closes the
socket.

* test: Cover a Stalled RAG Query in the Mock Harness

* fix: Share One Flux Budget Across Submit and Polls, Bound the Vertex Token Exchange

* refactor: Poll Flux Results Through pollUntilSettled

* refactor: Leave Flux Polling for a Separate Migration

* fix: Cap Configured Timeouts at the Node Timer Limit

* fix: Bound the Action Token Refresh and the Whole Image Download

* fix: Cap Every Outbound Budget by Wall-Clock Time

Axios's timeout only fires on an idle socket, so a RAG, OCR, moderation,
action or token response that keeps trickling bytes never ended.
outboundRequestBudget pairs each timeout with an AbortSignal deadline, and
action calls combine it with the run's own signal.

* fix: Name the Budget That Ran Out and Give Actions Five Minutes

The actions default rises to five minutes, since action endpoints are
arbitrary third-party APIs and the old minute could cut off legitimately
slow ones after an upgrade.

A budget overrun now fails with an error naming the timeouts key and its
value, whether it was the idle timeout or the wall-clock deadline, and
logAxiosError logs it as a warning so operators know what to raise. A
deadline cancellation is no longer read as a user stop, so an action that
runs out of time reports a timeout instead of looking like a stopped run.

* fix: Hold Outbound Deadlines Weakly So Finished Requests Leave No Timers

* fix: Check the Budget Before Reading an Error Message

* fix: Report a Wrapped Deadline as a Failure, Not a Stop

* fix: Bound the OAuth Code Exchange and Keep the OCR Budget Hint When Protected

* chore: Sort Imports in axios.ts After Rebase
2026-10-21 19:10:13 +02:00
Marco Beretta
e57aa3aa5b
🙊 fix: Keep API Keys and Internal Errors Out of Logs and Responses (#17258)
* fix: Keep API Keys and Internal Errors Out of Logs and Responses

The log redaction patterns did not cover the appid query parameter, so a
failed Wolfram request logged its AppID with the axios request URL. appid
now joins the redacted token and query names.

OpenWeather returned a fetch error's message to the model verbatim, and
node-fetch puts the full request URL, appid included, in that message. The
tool now passes it through redactMessage, as ToolService does.

The public startup config route and the unauthenticated password reset
route sent raw error text on unexpected failures. Both now answer with a
fixed message and keep the detail in the server log.

* refactor: Format Tool Error Text in packages/api

* fix: Redact appid Metadata Keys in Structured Logs
2026-10-19 21:36:46 +02:00
Marco Beretta
aec11338e6
🪦 chore: Retire the DALL-E 3 Tool (#17205)
* chore: Retire the DALL-E 3 Tool

OpenAI shut down dall-e-3 on May 12, 2026, so the built-in DALL-E 3 tool can no longer generate images on api.openai.com. Remove the tool, its manifest entry, registry definition, and env docs, along with the loadTools functions flag that only existed to register it. The OpenAI Image Tools cover the same use case. Stored agents that still list dalle load without it, and dalle stays in imageGenTools so past images keep rendering.

* test: Cover the Retired DALL-E 3 Tool in Mock Scenarios

* docs: Drop DALL-E from the README Image Generation List
2026-10-17 18:24:22 +02:00
Marco Beretta
ab8dc9d3d2
🕶️ fix: Keep Temporary Chats Out of Langfuse (#17202)
* fix: Keep Temporary Chats Out of Langfuse

* fix: Gate Forced-Ephemeral and Open Responses Turns From Langfuse

* fix: Treat Legacy and Chat Completion Temporary Turns as Untraced

---------

Co-authored-by: Joel Hirzel <joel.hirzel@eps.ch>
2026-10-17 11:57:35 +02:00
lia-by-librechat[bot]
8363766ccb
🌠 chore: Default OpenAI Image Tools to GPT Image Flare (#17014)
Co-authored-by: Lia <lia@librechat.ai>
2026-10-16 17:56:12 -04:00
Marco Beretta
5fc4371c6a
🪦 refactor: Remove Dead Legacy API Modules and Root Tooling (#17114) 2026-10-15 12:25:24 +02:00
Marco Beretta
e2b2839375
🗃️ refactor: Remove Dead Data Schemas Methods and Data Provider Exports (#17113) 2026-10-15 12:23:29 +02:00
Danny Avila
6b5cf0a231
🏝️ fix: Apply the No-Workspace Decision Wherever an Agent's Code Route Resolves (#16798)
* 🏝️ fix: Apply the No-Workspace Decision Wherever an Agent's Code Route Resolves

A conversation set to run without attached workspaces failed mid-turn with
"Choose an attached workspace before using this agent." when its agent's
default machine was attached and the turn loaded a skill or another tool at
execution time. Request-start initialization honoured the decision, but the
execution-time tool loader re-resolved the agent's attached default and then
demanded a workspace selection the conversation intentionally never made.

The per-agent code rule now lives in one typed function,
resolveAgentCodeExecution (packages/api/src/code/agent.ts): it applies the
conversation's no-workspace opt-out, the run-code grant, the stateful
capability and the stateful environment policy, then resolves the base route.
Request-start initialization, lazy subagent metadata and graph members, the
execution-time and definition tool loaders, and the legacy execute_code
loader all go through it, so an opted-out agent lands on the managed default
route with no code tools at every site. Per-call subagent machine choices
offer and accept no attached machine in such a conversation, and a source
invariant test keeps new resolver call sites on the shared rule.

* fix: Pass the Implicit Stateful Route Rollout Into the Shared Code Rule

The per-agent code rule read the implicit stateful route rollout from the environment itself. It now takes it as a parameter, and the request boundaries (initializeAgent and withRequestCodeInputs) resolve it from the deployment configuration, so the rule stays a pure function of its inputs.

* fix: Carry the Initializer's Code Opt-Out Into Tool Definition Loading

initializeAgent hands the tool loaders a partial agent record (id, tools, provider, model) together with the code route it already resolved. Without the agent's route fields the definition loaders could not see a no-workspace opt-out and recomputed code execution as enabled, so tool classification could advertise the programmatic bash tool that execution then refuses. initializeAgent now passes attachedEnvironmentOptOut through every tool loader, and the shared rule keeps an opt-out its caller already decided.
2026-10-06 07:40:42 -04:00
lia-by-librechat[bot]
114394c6a0
🦉 feat: Compare Review Commit Ancestry Without Git (#16734)
* 🦉 feat: Compare Review Commit Ancestry Without Git

* test: Cover Attached Reviewer Compare Registration

* 🦉 feat: Compare Review Commit Ancestry Without Git

* test: Cover Attached Reviewer Compare Registration

* 🦉 feat: Use SDK GitHub Comparison With Host Eligibility Gates

* test: Await the Comparison Timeout Assertion

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-10-05 08:20:51 -04:00
lia-by-librechat[bot]
1418d44ad9
🕊️ feat: Supply Authorized Scheduled MCP Resource Bearers (#16699)
* 🕊️ feat: Supply Authorized Scheduled MCP Resource Bearers

* 🥟 fix: Preserve Scheduled Bearer Denials and Request Headers

* 🪼 fix: Retain Bearer Denials Across Scheduled Recovery

* 🐡 fix: Retain Unsettled Scheduled Generation Evidence

* 🧭 fix: Recover Retained Scheduled Generation Obligations

* 🪢 fix: Drive Retained Recovery in Every Scheduler Mode

* 🦔 fix: Fence Complete Scheduled Denial Receipts

* 🪵 fix: Require Durable Scheduled Denial Acknowledgement

* 🕯️ fix: Preserve Fresh Terminal Writers During Cleanup

* 🪷 fix: Preserve Durable Scheduled Receipt Acknowledgements

* 🧿 fix: Acknowledge Scheduled Evidence Before Erasure

* 🧪 test: Verify Merged Scheduled Receipt Union in Redis

* 🪡 fix: Deduplicate Merged MCP Agent Context

* 🪷 fix: Reauthorize Scheduled MCP Transport Requests

* 🛟 fix: Preserve Scheduled Catalog Authority Denials

* 🛟 fix: Fence Scheduled Dispatch and Stale Owner Settlement

* 🛟 fix: Gate Scheduled Cleanup on Owner Evidence

* 🛟 fix: Preserve Scheduled Drain and Transport Rejection Evidence

* 🛟 fix: Quiesce Scheduled MCP Before Occurrence Settlement

* 🛟 fix: Fence Scheduled Owner Recovery and Back Off Receipt Admission

* 🛟 fix: Index Initially Retained Scheduled Generations

* 🛟 fix: Require Durable Admission for Scheduled Policy Denials

* 🛟 fix: Abort Occurrence Bearer Work Before Quiescence

* 🛟 fix: Cancel Connection Credential Waiters During Failed Initialization

* 🛟 fix: Fence Scheduled HTTP Dispatch at the Cancellation Cutoff

* 🛟 fix: Bind SDK Request Deadlines to Scheduled Denial Admission

* 🛟 fix: Recover Retained Creation and Isolate SDK Caller Cutoffs

* 🛟 fix: Fence Scheduled App Reads and Share Cold Connection Ownership

* 🛟 fix: Retain Observed Scheduled Denials Across Caller Cancellation

* 🛟 fix: Invalidate Retained Discovery on Each Re-Arm

* 🛂 fix: Classify Scheduled Resource 403 as Permission Denial

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-10-04 22:20:50 -04:00
Danny Avila
c23fbc8f77
🧬 fix: Default Subagents to Their Parent's Code Machine and Workspace (#16756)
* 🧬 fix: Default Subagents to Their Parent's Code Machine and Workspace

A subagent resolved its code machine from its own saved fields only, so
when a chat routed the parent to an allowlisted machine the subagent fell
back to its own default and whatever workspace the conversation had
selected there, or failed the parent's whole turn when none existed.

Subagents now inherit the parent's resolved attached machine when it is
their own default or on their allowlist where per-chat choice applies,
the principal can use it, the sealed decision already selected it, and no
selection names the subagent as an explicit owner. Inheritance is derived
per request from the sealed decision and current agent configuration and
fed to every routing site; it is never persisted, so existing chats and
older clients get it without a decision change. The composer mirrors it.

A subagent whose machine has no usable workspace is advertised to the
parent as unavailable instead of failing the turn; a locked decision
stays fatal.

* fix: Inherit Across Every Spawning Path, Graph Members and Deferred Code Tools

A subagent now inherits only when every agent that can spawn it, at any
depth, runs on the same machine; spawn cycles keep their own routes.
Subagent graph members inherit like explicit subagents. The deferred
execute_code loader passes inheritance to its fallback resolver. Subagent
reads and VIEW checks move to a packages/api loader shared by inheritance,
lazy descriptors and graph members. The composer lets a draft's subagent
follow its parent's machine before a workspace is picked, and keeps an
inheriting subagent's former selection without asking for a move.

* fix: Prune Spawn Back-Edges, Gate the Composer on an Inheritance Capability

Spawning parents follow the run's path semantics, so a back-edge the
descriptor tree prunes no longer blocks inheritance, and agents that spawn
each other follow their single outside parent machine when it routes them
all there. Only admitted subagents count toward the walk's node limit.
Graph members re-read and re-check VIEW when they initialize. The composer
echoes an inheriting subagent's former selection without gating on that
machine, and mirrors inheritance only when the API advertises
codeWorkspaceInheritanceVersion; approval modes keep intersecting every
machine an agent could use.

* fix: Settle Each Mutually Spawning Group on Its Own

Independent spawn cycles no longer merge into one group, so a pair under
one parent follows that parent even when another pair follows a different
machine. Also types the data-provider spec for its ES5 target.

* fix: Bound the Inheritance Walk, Normalize Parallel Roots, Move Subagent Availability to TS

The walk reads in batches no larger than the remaining node budget, stops
once the limit is reached, and runs through the run's subagent load limiter.
Roots are keyed by saved agent ID, so a parallel root such as id____1 can
never receive an inheritance entry. Resolving a lazy subagent's code route,
reporting it unavailable, and guarding its descriptor now live in
packages/api (resolveSubagentCodeAvailability, guardUnavailableSubagent).

* fix: Keep Missing Subagent Loads Parallel Near the Node Limit

Batches never shrink below eight IDs, so missing or unviewable subagents
near the limit still load in parallel under the injected limiter, and at
most a handful of reads land past the limit.
2026-10-04 22:19:00 -04:00
Marco Beretta
8ae65f28dd
⚡ perf: Async Local File Saves and Compile Hot-Path Regexes Once (#16712)
* perf: Async Local File Saves and Compile Hot-Path Regexes Once

* perf: Check Closing Code Fences Without a Per-Length Regex Cache

* test: Build the Delivery Route Config Before Routing Instead of Mutating It

mergeFileConfig now memoizes by config identity, so the CSV fallback tests
must set textFallbackWithoutTools when they build the request config rather
than mutate the object after the agent's routing already merged it.

* fix: Write Local Buffers Atomically So Concurrent Saves Cannot Interleave

Async writeFile calls to one deterministic path (OpenID and SAML avatars)
could truncate and interleave each other. Write through a temp file and a
rename instead, and add scenario specs for local saves and longer closing
fences.

* refactor: Move Local Save Logic Into packages/api

saveLocalBuffer, the temp-upload move and the atomic directory writes now live
in packages/api/src/storage/local.ts and receive their paths from the caller;
the Local strategy in /api keeps its logging and calls through. The traversal
check now runs before any directory is created.

* fix: Copy Moved Uploads Through a Temp File and Rename Into Place

Concurrent async copies to one destination could interleave just like direct
writes, so moveLocalFile now fills a sibling temp file and renames it.

* fix: Contain Every Local Write and Move Inside Its Target Directory

The traversal check that guarded saveLocalBuffer now runs in writeLocalFile
and moveLocalFile too, before any directory is created, and the buffer
save accepts only the images and uploads base paths.

* test: Define the Success Assertion Inside the Local File Saves Scenario

* fix: Give Atomic Write Temp Files a Fixed-Length Name So Long Targets Still Fit

* test: Send Image Dimensions and Read the Message Array in the Local Saves Scenarios
2026-10-04 15:52:55 -04:00
lia-by-librechat[bot]
38a9dab3f5
🦫 feat: Enforce Scheduled MCP Read-Only Authority (#16681)
* feat: enforce scheduled MCP read-only authority

* fix: preserve startup admission and enforce consent deadline

* fix: fail closed on malformed scheduled consent

* fix: preserve scheduled MCP authority failure receipts

* fix: preserve scheduled MCP handoffs and manual runs

* fix: persist mandatory scheduled tool policy denials

* fix: fence late scheduled consent and retain denial recovery

* fix: retain scheduled transport denials and prevent replay

* fix: merge retained scheduled denials during settlement

* fix: prevent enrolled schedule completion wakeup escapes

* fix: close scheduled consent admission and receipt races

* fix: retain scheduled completion authority across approval

* fix: retain safe scheduled authorization dependency denials

* fix: sanitize scheduled authorization preparation failures

* fix: bind schedule completion authority to task origin

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-10-03 20:39:43 -04:00
lia-by-librechat[bot]
73d704656e
📔 feat: Preserve Owner Text During PII Redaction (#16311)
* 📔 feat: Preserve Owner Text During PII Redaction

* 🧵 fix: Keep Ordinary Chat Views Outside Private Text Provider

* 🧷 fix: Preserve Owner Text Across Copy and Edit Paths

* 🔏 fix: Protect PII on Denial and Abort Paths

* fix: preserve protected text through denial, stop, and owner reload

* test: cover preliminary private metadata in disconnect fixture

* test: carry preliminary metadata in resume controller fixture

* test: preserve Stop prerequisite identity in tenant fixture

* fix: keep protected owner text out of search and exports

* fix: preserve trusted PII placeholders through provider inspection

* fix: coordinate protected turns across Stop and native sharing

* fix: Preserve Private Text Admission and Query Lifecycles

* fix: Track Private Query Effect Dependencies

* fix: Fence Protected Admission and Screenshot Targets

* fix: Share Protected Admission and Preserve Native Token Trust

* test: Wait for Private Message Concurrency Indexes

* fix: Preserve Protected Admission Across Recovery and Titles

* fix: Coordinate Protected Root Admission and Early Stop

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-10-02 11:43:10 -04:00
Danny Avila
2eee568542
🧳 feat: Choose Agent-Allowed Machines For New Chats (#16651)
* feat: Let New Chats Choose Agent-Allowed Machines

* test: Keep Machine Choice Contracts And Native Selectors In Sync

* fix: Preserve Graph Machine Choices And Reference Lifecycles

* fix: Explain Graph Workspace Requirements And Validate Machine Choices

* test: Cover Default And Non-Default Graph Machine Choices

* test: Keep Unauthorized Machine Duplication Mocks Isolated

* fix: Preserve Graph Agent Machine Ownership And Explain Requirements

* fix: Preserve Stable Workspace Ownership Across Runtime And Config Changes

* test: Wait For Verified Generation Readiness In Native Canaries
2026-10-02 08:38:14 -04:00
Lia
9dc8db0ea8 🛶 fix: Preserve Canary Sync Resolutions (#16361)
Retain the tracked-file integration outcomes recorded by original canary sync PR #16361.

No new implementation is introduced. Shared and ambiguous corrections are carried by the final sync-resolution commit so the resulting tracked tree equals frozen canary f66ad88e1c.

Original-PR: https://github.com/LibreChat-AI/LibreChat/pull/16361
Resolution-Sources: 6d7ba72b89, 241c692b63, 6113242b7b, 3c8a5703e7, a45be88578, 3789cbf590, 81e038972f, c505db2256, 420760d8b2
2026-10-01 03:46:19 +00:00
Marco Beretta
2be35b2f91 💬 refactor: ChatForm UI redesign with unified palette (#14473)
* 💬 refactor: ChatForm UI redesign with unified palette

Replace the scattered composer controls (badge row, tools dropdown, attach
menu, floating steer chips) with one system: a searchable palette with
favourites, a composer bar holding active tools plus effort and speech
controls, a tray staging files and manual context, and a queue rail that
buffers messages while a reply is running.

Collapses the 94 development and review-fix commits of PR #14473 into one
commit so the branch could be rebased onto dev once; the upstream merge of
this pull request is a squash merge either way. The pre-rebase history is
kept locally at tag prerebase-backup (afde3e4b9a).

* fix: finish the dev rebase of the composer redesign

The rebase onto dev left four defects the merge itself produced, plus one
review finding the branch had never answered:

- ChatForm's `min-w-0` JSX comment lost its closing brace, so the file did
  not parse at all.
- `useSteering` carried both dev's local draft consumer and the host-injected
  one under the same name; the host's `consumeDraft` owns the storage key
  autosave actually parked on, so the local copy is gone.
- `useUploadOptions` kept dev's `awaitingAgentProvider` gate after the merge
  replaced the block that derived `isSavedAgent`; the predicate is back, from
  the same `isEphemeralAgentId` the shared allowance helper uses.
- `MessagesView` still reserved a band for the in-flight steer overlay and
  read `steerOverlayHeightFamily`, which nothing writes now that pending
  steers render inside the streaming reply. The reservation is gone and
  `ScrollButton`'s lift is optional; composer panels keep standing the button
  down through `composerOverlayCountFamily`.
- The aggregate MCP chip keyed on `mcp:pinned`, which a server literally
  named `pinned` also produces (`mcp:${serverName}`), so both entries shared
  one React key and one packing slot. It uses a key outside that namespace.

Also drops the locale keys whose only consumers the redesign deleted, ports
dev's extracted-text delivery path into `useAttachExisting` (every
attach-existing surface routes through it now), repoints the mock e2e
built-in helpers at the palette, and repairs test fixtures the merge left
stale (a query mock that blanked agent metadata, a Jotai store mismatch, an
ambiguous tray query, an ephemeral-agent fixture standing in for a saved one).

* test: cover the composer redesign's acceptance scenarios end to end

Twelve mock-harness scenarios, one `@scenario:` tagged test each, over the
behaviours this change is accountable for: the single searchable palette
(open, search, favourite across a reload, keyboard-only operation), the
composer bar and tray (active tool chip, a staged file riding with the
message, a per-turn thinking level that applies to the next turn only), the
queue rail (Enter buffers during a run and drains after it, keyboard reorder
changes the send order, the draft survives run completion), and the composer's
portaled surfaces (Stop reaches the run from inside a portal, a pending tool
approval in the bar resumes the run).

Two contract scenarios are deliberately absent, with reasons: split-pane Stop
isolation is not runtime-reachable because `ChatRoute` mounts one pane, and
code-approval mode mid-run needs an attached stateful code environment the
mock lab does not configure, so dev's `ChatForm.approvalMode` unit spec stays
its coverage.

* fix: make the composer's acceptance run and the whole client suite green

The first verification run of the twelve scenarios passed six and failed six,
and the full client jest suite (which CI runs sharded, unlike the diff-scoped
local precheck) failed fourteen tests. One of each group was a real defect; the
rest were queries and fixtures still aimed at surfaces the redesign replaced.

Defects:

- `useQueueDrain` held its send lock after a revealed queued turn settled, so
  the next server-owned row could never be selected. The reveal path now owns
  its own lock and releases it when the revealed turn clears.
- `ChatForm` recomputed the during-run slot without `consumeComposer` in its
  dependency list, and still carried a landing flag the host prop replaced.

Tests and lab:

- The five `ChatForm.attachments` focus cases now drive the palette dialog and
  the tray's quote chips instead of the deleted attach menu and quote popup,
  with the same strict focus assertions; the harness gains the `main` landmark
  the palette portals into, and the touch fixture a complete `matchMedia`.
- `Palette.spec` no longer closes a hoisted `jest.mock` factory over a later
  `const`; `useSteering.spec` follows dev's toast wording.
- The six failing scenarios were repointed at what this lab actually renders:
  uploads go through the palette's local-computer row, the reasoning control
  needs `interface.parameters`, the queued-row contract is the row and its
  drain rather than a control the submit consumes, the palette's keyboard path
  uses a built-in the lab grants, the slow-reply wait uses the fixture's chunk
  marker, and the approval scenario selects its agent through the builder flow
  the passing approval specs use.

* fix: close the eight findings Codex raised on the rebased head

Codex reviewed the rebased heads and reported eight issues; all eight were
real. Two of them concern code this session added.

Behaviour:

- A custom or OpenRouter endpoint that declares neither `paramDefinitions`
  nor a `reasoningFormat` no longer gets a reasoning control inferred from the
  generic settings list. Capability now has to be declared (a reasoning-key
  parameter definition, a non-disabled `reasoningFormat`, or a known reasoning
  provider as the default params endpoint); a `disabled` format always
  resolves nothing, and every consumer — the composer control, the pre-send
  validation and the server — asks the same resolver, so a gateway backed by a
  non-reasoning model can no longer offer a level the turn would fail on.
- Restoring a queued attachment keeps its `llmDeliveryPath`, so an extracted
  document is routed as its text rather than as raw provider content.
- The placeholder-to-durable reasoning migration now requires this pane's own
  live submission, so opening another conversation from a new chat no longer
  carries the pending level into it. The created/sync case it was written for
  still carries.
- The queue rail treats an acknowledged server-owned row as an ordering
  boundary: local rows still reorder among themselves, a server-owned row
  cannot move, and a move that would cross one is refused out loud — the
  queued-turn API has enqueue, list and cancel only, so a client-side reorder
  across that boundary could not be made authoritative.
- The palette resolves an agent's skill scope with `resolveAgentSkillsScope`
  instead of treating an empty list as an open catalog, and the attach target
  resolves `useResponsesApi` with `resolveUseResponsesApi`, matching what the
  run will actually do.

Policy:

- The reasoning-override behaviour moved out of the CJS middleware into
  `packages/api/src/modelSpecs/reasoningOverride.ts`, which returns a
  discriminated result; the middleware is wiring again, and the behavioural
  cases moved with it.
- `showComposerTips` and `showFilesDialog` are Jotai atoms now, the tips
  preference keeping its storage key and reaching the composer as a prop.

* fix: make the redesigned composer reachable from the mock e2e helpers

CI's Playwright shard failed four `file-provisioning` tests on this branch
because the shared upload helpers still clicked `#attach-file-menu-button` and
`#attach-file-button`, entry points the redesign removed — attaching now goes
through the palette, which also owns the file input. Both helpers drive the
palette now, `uploadViaLegacyOption` mapping its two destination names onto the
palette rows that route to the code environment and the vector store, and the
specs that drove the old surfaces directly (`code-upload`, `thread-renderers`,
`unified-upload`) follow.

Also closes the last client/server disagreement the acceptance run exposed: a
custom endpoint that declares a reasoning key in `paramDefinitions` had that
declaration merged into the provider defaults and then discarded by model-name
inference, so the composer offered a level for `mock-model-a` that the server
rejected with "Invalid reasoning override". An explicitly declared key now
selects the merged setting before inference, while an undeclared generic custom
or OpenRouter target still resolves nothing.

The twelfth acceptance scenario is rescoped: a paused approval keeps the
composer usable and resumes to completion, but the composer-hosted approval
panel and chip are not asserted, because the pending action is keyed by the
stream's conversation id while the composer stays bound to the new-chat
sentinel — in code byte-identical to dev, and mirroring the write onto the
sentinel did not surface the panel. Tracked at berry-13/LibreChat#39.

* test: finish the acceptance run and keep the client typecheck green

- The thinking scenario read `reasoningOverride` from a `userMessage` wrapper
  the chat request does not have; the trace shows the request carrying
  `{ key: 'effort', value: 'max' }` at the root, so the assertion reads it
  there. Source behaviour was already correct.
- The approval scenario timed out on mobile because the Agent Builder drawer
  stayed open after selecting the agent and swallowed the pointer events meant
  for the composer; it now closes the sidebar and waits for the drawer to go
  inert before sending.
- Two specs typed a named custom endpoint's label as an `EModelEndpoint`, which
  CI's client typecheck rejects (the label is exactly what the case is about).

All twelve acceptance scenarios now pass in desktop light, desktop dark and
mobile emulation.

* fix: close the nine findings Codex raised on the verified head

Two were defects in code this session added while closing earlier findings:

- A reasoning key declared in `paramDefinitions` but absent from the generic
  settings list was accepted as capability and then never inserted, so the
  resolver exposed and validated the generic `reasoning_effort` instead. A
  declared key is now appended to the effective settings and resolved before
  any fallback, for `effort`, `thinkingLevel` and `thinkingBudget` alike.
- The queue's reorder guard validated from the destination row's own index, so
  `target === index` rejected every pointer drag and only keyboard reordering
  worked. It validates the dragged row's identity now; the server-owned
  boundary, its announcement and the disabled grips are unchanged.

The rest:

- Stop no longer falls through to the document-wide control once a focused
  pane has been resolved: focus in an idle pane while another generates used
  to abort the other pane's run.
- `PendingSteers` is mounted once in `MessagesView`, above the renderer
  switch, so a sent or failed steer keeps its in-flight, retry and
  send-as-new surface with `FLAT_THREAD` off, where the recursive renderer
  had none and the composer no longer carries a fallback.
- The file-list policy moved out of the CJS route into
  `packages/api/src/files/list.ts`, and its cap is `interface`-level config
  (`fileListLimit`, default 100) instead of a literal in the route.
- The steer-arm confirmation window is `interface.steerArmConfirmationTimeoutMs`
  with its current 10s as the default, travelling the same path as the other
  client-consumed timings.
- The pause predicates judge the active branch's tail rather than the last
  assistant in array order, so an inactive sibling branch can no longer
  enable or disable the inline escalation control.

* fix: move persisted reasoning validation into api package

* fix: restore composer entry points and defaults

* style: normalize reasoning helper formatting

* test: open mobile sidebar before account menu

* test: use settled sidebar layout for mobile account menu

* test: handle empty mobile sidebar in account scenario

* test: target account menu in mobile drawer

* fix: keep composer surfaces and mobile drawer reachable

* fix: let thread approvals receive pointer events

* fix: stabilize composer steering and shortcuts

* fix: commit queue drags and centralize file modal

* fix: return a canceled steer's text to the composer

Canceling a pending steer dropped the words the user had written: the
bubble disappeared and nothing carried the text back, so a reclaim that
the server confirmed still lost the message.

Hand the reclaimed text to `pendingComposerTextByConvoId`, which the
composer already drains on its first render, and append rather than
overwrite when the composer holds a draft the user typed while the cancel
request was in flight.

* fix: close the six findings Codex raised on the pre-rebase head

Pending steers keyed off the Recoil conversation id, which lags the route
during warm-cache navigation, so the surface could sit at the destination
thread's tail while its Cancel and Escalate acted on the source run. It
now keys off the rendered tree, as the mount window already does.

Arming a steer removes the control that was activated, dropping keyboard
focus on the document body. `useSteerEscalate` already exposes `onArmed`
for exactly that; the bubble now passes one that moves focus to the row's
Cancel action.

Opening the file manager from the account menu left its dialog with no
opener: the modal rejects an active element inside a menu, and nothing
supplied a fallback, so closing it returned focus to the body. The opener
is published alongside the open flag and cleared on close, which keeps the
shortcut path's composer-focus behaviour intact.

A steer the server rejected was swept into the queue with no marking, and
the run-end drain then sent those words as a fresh turn without the user
touching Retry or Send as new. Converted failures now carry
`needsExplicitSend`, which the drain skips the same way it skips a row the
rail is mid-edit on.

The queued-turn reconciliation window was a hard-coded 60s, unreachable by
an operator behind a slow proxy or a delayed read replica. It ships as
`interface.queuedTurnReconciliationTimeoutMs` with that value as default,
beside the steer arm timeout it belongs with.

Reasoning-override shape validation moved to
`parseReasoningOverrideRequest` in packages/api, leaving the middleware to
map a rejection onto its own error response.

* fix: keep the composer's reasoning level in step with the parameters panel

`stableConversation` memoized the conversation without any reasoning field
in its key, so editing the level in the Parameters panel produced a new
conversation object that every listed dependency ignored. The composer
went on showing the old level while the next ordinary send already used
the new one.

* test: stop the sidebar helper waiting for a drawer desktop never renders

`ensureSidebarOnScreen` measured `#mobile-drawer` whenever the sidebar had
no Pinned region. Desktop renders no drawer, and `boundingBox()` on a
locator that matches nothing waits for it, so every scenario that reached
that branch at a desktop viewport timed out instead of continuing. Check
for the drawer's absence rather than measuring it.

* test: open the mobile drawer from its inert state, not its geometry

A closed drawer stays mounted and keeps its layout box, so measuring the
Pinned region reported it on screen while every control inside was still
untappable. `inert` is the state the component actually sets when it
closes, so the helper reads that and clicks the header opener before
anything else measures.

* fix: return a canceled steer whole, through one recovery boundary

A steer that stops being a steer was handed back three different ways,
and each one lost something. The immediate cancel wrote `steer.text`
into the composer handoff atom, dropping the attachments, quoted
excerpts, manual skill picks and reasoning override that `settleReclaimed`
then deleted with the pending object. The cancel that won its race
against its own POST cleared the pending marker and restored nothing at
all, so those words disappeared. A definitively rejected steer could
only be resent unchanged, because the row offering to edit it was gone.

Give the recovery one boundary. `useSteerRehome` hands the whole steer
to the composer through the guarded restore the queue rail already uses,
and converts it into an ordinary queued follow-up when the composer
refuses: a draft in the box, another chat on screen, a paused question,
or a composer that unmounted while the reclaim was in flight. The chip
goes either way, since a pending row claiming the server still holds the
words is a lie once they live somewhere else.

The composer is a sibling of the message list rather than its ancestor,
so the thread had no way to reach that restore. The pane's host now
holds the reference and both sides read it there, which also means a
reclaim resolving after the composer is gone refuses instead of writing
into a dead form.

Because the restore refuses rather than overwrites, a draft typed while
a cancel is in flight is no longer glued to the returned steer; the
steer becomes its own queued message and the draft is left as typed.

* test: drive the surfaces these scenarios actually reach

Four scenarios were failing against surfaces the user never touches.

The approval scenario clicked Approve on the thread's copy of the
pending card. The composer's review panel floats over the tail of the
thread and owns the batch submit, so that copy sits behind it and the
click retried until the test timed out. Drive the panel instead; the
thread card stays asserted as the record of the request.

The palette scenario counted rows the moment the dialog painted, then
expected clearing the filter to restore that number. The catalog arrives
in waves: the MCP server list is released by the app-wide warmup timer
and the skills catalog only starts fetching once the dialog's open
effect has run, so the count kept climbing under the test. Wait for the
last wave and for the count to hold still, then snapshot.

The sidebar helper opened the mobile drawer twice through two signals
that disagree. It waited for `inert` to clear, which happens on a state
commit several frames ahead of the slide, then fell through to a
bounding box still reading off-screen and clicked the opener again, into
a machine already opening. One open, through `inert`, then wait for the
drawer to settle in the viewport.

Splitting the cancel scenario follows the recovery change: an empty
composer takes the steer back, and a staged draft keeps the box while
the steer becomes a queued message of its own.

* fix: hold a server-rejected steer for an explicit send

Editing a definitively failed steer falls back to the queue when the
composer will not take it. Queued like any other follow-up, the run-end
drain would send it the moment the reply finished, which turns the
server's refusal into an automatic new turn carrying the payload it
refused.

Mark that fallback the way the rest of the rejected-steer path is
marked, so the row waits for the user to send it.

* test: restore two assertions this branch broke while rewriting specs

Both specs were updated for the redesigned surfaces and both lost a step
they needed, and both fail deterministically in CI as a result.

thread-fold pressed Enter mid-run and waited for a queued row, under a
comment claiming Enter queues by default. It does not: the default
during-run action is steer, so Enter produced a pending steer and the
queued row the next line waits for could never appear. Ctrl/Cmd+Enter is
what takes the other action, which is the one this test needs.

mcp-oauth-readiness asserted on the server card's Cancel button straight
after clicking Connect. Connect opens the OAuth dialog over the panel,
and it is modal, so while it is open the card underneath is marked
aria-hidden and Cancel is not in the accessibility tree at all, which is
why the failure reads "element(s) not found" rather than "not visible".
The rewrite dropped the dismissal the previous flow performed; restore it
as a helper both call sites share.

* test: reach the account menu without the pinned section

The two account-menu tests borrowed `ensureSidebarOnScreen`, which also
settles the Pinned section's placement for the pinned specs. They never
touch that region, and on a run where an earlier test left a pinned
conversation the section exists but has not been laid out yet, so both
tests spent fifteen seconds polling it and failed on the wait rather than
on anything they assert.

Give them a helper that does only what they need: open the mobile drawer
from `inert`, the one signal that distinguishes a closed drawer from an
open one while it stays mounted, then wait for the slide to reach the
viewport. Desktop renders no drawer and needs nothing.

* test: open the drawer by what it shows, not one early read

The helper decided once, from a single read of `inert` taken right after
navigation. On a fresh mobile load the drawer can still be mounting, so
that read reports a state the app has not settled into, the helper
returns believing the drawer is open, and the account menu inside it is
never shown.

Retry against the thing the caller actually needs, the account menu being
visible, re-checking before each attempt. While the drawer is open its
control is labelled "Close sidebar", so the retry cannot toggle it shut.

* fix: keep the composer observing MCP authorization where its tools apply

The old badge row mounted its provider with observeToolAuthorization set
whenever the composer showed ephemeral tools, so on a plain endpoint the
chat kept MCP connection status and discovered tools in the query cache.
The redesigned composer mounts the same provider without the prop, so it
defaults to off and nothing on the chat side loads that state any more.

The Agent Builder's tool library reads that cache. With it empty, every
server reads as Unknown with no tools, and clicking one opens its detail
dialog offering to connect instead of adding it to the agent.

Pass the same gate the badge row used: showTools is the old
showEphemeralBadges expression.

* test: let the palette close before reopening it, and name what is asserted

enableBuiltinTool pressed Escape and returned while the palette was still
animating out. A caller that reopened it straight away resumed the same
popover, scroll offset included, so the Attach rows at the top sat outside
the virtualized window and upload helpers timed out looking for them. Wait
for the dialog to be gone before returning.

The staged-file assertions matched the bare file name, which the palette
now also lists under recent uploads while it closes; scope them to the
tray they are about.

The OAuth dialog dismissal waited for a title built from the server's
display name, but the dialog is titled with the server name.

* feat: make the queued-send lock expiry configurable

The per-pane lock that stops the run-end drain and an explicit Send now
from submitting the same queued message twice gives up a broken claim
after a fixed 60 seconds. Until then every drain and every Send now for
that pane is refused, and a deployment had no way to tune that window.

Expose it as interface.queuedSendLockTimeoutMs beside the queued-turn
reconciliation timeout, defaulting to the same 60 seconds so nothing
changes unless an operator sets it. The interface loader copies each
field explicitly, so the value is added there too; without that line a
configured value would never reach the client.

* fix: decline interrupt-and-steer while reasoning is staged

With a reasoning choice staged, the Interrupt & steer row is disabled,
but its keyboard chord still reached interruptSteer, which fell back to
interruptAndSend: it aborted the run and threw away the partial answer
the action promises to keep.

A staged reasoning choice belongs to a new generation that a steer into
the live one cannot carry, so decline the chord exactly as the row does,
the same way the function already declines while paused on an approval.
The words stay in the composer, where Enter queues them as a turn of
their own.

* fix: wake the queue drain when a late steer retry is queued

Retry marks a failed steer sending, and a sending steer is kept out of
the run-end sweep so its own POST settles it. When the run finishes
while that POST is in flight, the drain spends its one-shot signal on a
queue the steer is not in yet; the late ack or NO_ACTIVE_RUN then moves
it into the queue, where it sat until the user sent it by hand or
another run ended.

Every other late conversion re-posts the last completed run end through
the composer's rewakeDrain. The retry lives in the thread, so the
composer now publishes that function through the same host it already
uses to hand a reclaimed steer back to the draft, and the retry calls it
after converting. It stays a no-op unless the run completed cleanly and
no newer signal is armed, or when no composer is mounted.

* fix: honour thinking-budget ranges wider than 200,000

The request-scoped reasoning override capped thinkingBudget at 200,000
in the shared schema. An operator's paramDefinitions may advertise a
wider range, and the composer renders it, but every value above the cap
was dropped by the control's parse and rejected by the server's before
the range-aware check could run.

That check already exists: resolveReasoningOverride validates the value
against the endpoint's resolved range. Drop the fixed ceiling so the
resolved range is the bound, keeping the integer and lower-bound rules.
The new case covers both directions on a custom endpoint whose range
goes to 500,000.

* refactor: persist the preliminary reasoning override through the shared helper

The agents controller validated the request's reasoning override with
the schema itself before writing the preliminary user message. That is
behavior in the CJS layer, and it duplicated resolvePersistedReasoningOverride,
which @librechat/api already exports and BaseClient already uses for the
same field.

Call the helper instead. A preliminary message is always a fresh turn,
so it is never an edit or a compaction. The two controller specs that
replace @librechat/api with a hand-built mock now take the real helper.

* fix: clear the file manager's state at the session boundary

The file manager's open flag and its opener live in Jotai's default
store, which outlives the authenticated route. A file manager left open
at logout reopened for the next account, still holding a ref to the
previous session's unmounted opener. Reset both in useClearStates, next
to the other composer state this branch already clears there.

* fix: decline interrupt-and-steer on the first turn while reasoning is staged

* test: read the phone layout from the viewport and keep the drawer open

* fix: name both reasons a queued message cannot be edited yet

* test: reuse a published file through the composer palette

* style: move the composer onto the design-system rules

* style: move the file row's new layout styles into classes

* fix: keep the composer's reused thumbnails, focus ring and disabled dimming intact

* fix: bring a steer back when its deferred cancel does not remove it

* fix: treat a run as over only when every pane holding it is idle

* refactor: pass enter-to-send into the composer from its host

* feat: make the palette's recent-file count configurable

* fix: let a file already in the composer be reattached at the limit

* test: hide the chip before replaying a deferred cancel

* refactor: restore the resume request through one packages/api facade

* fix: keep a conversation's staged reasoning across a visit to another model

* fix: keep a connected MCP server's variables configurable from the palette

* fix: resolve every pane-scoped shortcut through the pane holding focus

* refactor: keep every reasoning-override decision out of the /api wiring

* perf: skip paging the skill catalog for an agent that can show no skill

* test: type the reasoning snapshot the override helper records

* test: pin the applied budget and the untouched parameters in the override specs

* style: give the stop button the send button's shared submit recipe

* fix: name only the newline key when no chord sends

* fix: name the stop key only once the stop control can act

* fix: clear every staged reasoning selection at sign-out

* fix: stop advertising send-now while staged reasoning forces a queue

* fix: resolve the reasoning target of an ephemeral agent in the composer and the request

* test: type the staged reasoning the sign-out spec seeds

* fix: check the composer will take a queued row before discarding its parked copy

* style: carry the composer's classes onto Tailwind v4

* style: sort the composer's classes in Tailwind v4 order

* fix: return a refused queued row to the durable queue instead of memory

* i18n: localize the whole attachment-limit message

* refactor: validate the reasoning override inside the packages/api facade

* style: give the composer's submit slot its own IconButton variant

* test: pin the submit slot to IconButton's submit variant

* test: stub the seen-state hook the rebased MessagesView now calls

* fix: turn file search on for an embedded file attached through the shared hook

* chore: record the composer's design-rule counts against the rebased base

* fix: keep the composer's container query inert under Tailwind v4

* test: point the v4 focus scenarios at the redesigned composer's controls

* fix: keep a re-queued row on its own lineage after the run ends

* test: assert a re-queued row carries its lineage

* refactor: pass the dictation preferences into the composer from its host

* test: read the usage atom from the store the ask hook renders under

* fix: read a pending steer's pause from its own pane's branch

* a11y: keep focus on the quote chips until the last one is removed

* fix: keep staged reasoning for the next message across a manual compaction

* test: expect focus on the remaining quote chip after removing one of two

* style: sort the imports the canary rebase merged

* refactor: remove the side-panel files table the account menu replaced

* fix: settle a retried steer's late ack against a racing cancel

A cancel clicked while the retry POST was in flight left the optimistic
marker unread: the ack re-minted a live chip and injected words the user
had asked back, and a failed retry after that cancel lost them entirely,
because the failure path maps chips the optimistic cancel had removed.
The ack path now defers to the marker the way the composer's does, the
failure path re-adds the chip before settling it, and the queued row a
late ack produces binds its recovery identity only under protocol v2,
the same default the composer's degradation path trusts.

* fix: strip a replayed reasoning override that no longer validates on resume

A paused turn's reasoning override is replayed onto its resume request
and then validated as if it were fresh client input, so an operator
changing the endpoint's reasoning config between pause and approve made
the checkpoint permanently unresumable with a 400. The replay now marks
the request, and a replayed override that fails validation is stripped
so the resume proceeds on defaults; a fresh override that fails is still
rejected.

* refactor: derive the enforced spec fields inside the modelSpecs facade

The set of keys an enforced model spec locks is the input contract of
the reasoning-override refusal rule, and deriving it in the route
middleware left the policy untestable from packages/api and free to
diverge from the facade that owns the rest of the preset application.
applyModelSpecPreset now returns the enforced fields beside the private
ones it applies, and the middleware consumes them.

* fix: restore the pre-override parameters when a resume degrades

Stripping a replayed reasoning override that no longer validates removed
only the metadata field, while the resume had already replayed the paused
turn's model parameters with the override applied into the endpoint
option, so the provider still received what validation had refused. The
strip now inverts the application from the replayed base: the recorded
pre-override value returns and the thinking flag the override forced on
comes off.

* fix: resolve the effective responses route for upload targets

The attach target returned the conversation or agent's saved
useResponsesApi flag, so an Azure chat auto-routed to the Responses API
by responsesApiRouting preflighted its uploads against the chat
completions route and lost provider-document uploads. The resolver now
applies resolveEffectiveUseResponsesApi with the endpoint, model,
web-search state and routing policy, the same resolution the during-run
upload target makes.

* fix: name the interrupt chord in the hint only while it still interrupts

The during-run hint advertised Alt+Enter Interrupt & send even when the
chord had been claimed: a submitMessage rebound to Alt+Enter, a chord
yielded to a global shortcut, or shortcuts disabled altogether each make
the keydown resolver return something else. The hint now reads the same
resolver verdict the during-run send button does and omits the chord it
no longer owns.

* test: assert the unseen count the scenario adds rather than a zero baseline

The tab title counts every unseen conversation, and a shared
verification run leaves legitimately-unseen conversations from earlier
scenarios behind, so the three title-count scenarios failed on other
scenarios' leftovers instead of the behavior they seed. Each now reads
its baseline and asserts the count it adds and clears.

* test: hold the unseen count to its direction on the mobile project

The away poll that lights a dot also discovers conversations the client
had not counted yet, so on the mobile project the title count can jump
past any baseline taken mid-test. Opening still has to clear this
conversation's contribution and an away reply still has to raise the
count, which is what the assertions now hold.

* test: enable the MCP Apps server through the redesigned palette

The MCP Apps integration spec still drove the old composer's MCP
Servers menu, which the redesign replaced with toggleable rows in the
attach-and-tools palette; the lane failed on the missing menu on every
run. The helper now opens the palette, waits for the server wave, and
flips the row's pressed state.

* fix: preserve numeric reasoning defaults on blur

* test: reopen persisted code cards before checking highlights

* test: follow the current file manager navigation

* fix: offer only reasoning options a request override can carry

* fix: keep the favorited copy when skills share a name

* fix: restore composer focus by the interaction that closed the palette

* test: expect a keyboard close to refocus the composer on every project

* chore: re-record the design-rule backlog on the rebased composer

* chore: drop the files table and label the rebase brought back

* test: tolerate other projects' unseen conversations when marking one unread

* test: open the file table header scenario from the account menu

* fix: let the stop shortcut reach a hidden stop control from a dialog

* fix: keep staged reasoning out of tool-limit recovery and MCP App turns

* fix: degrade a queued turn's stale reasoning override instead of dead-lettering it

* fix: refresh the attach target when web search changes the route

* fix: re-arm the run-end drain after moving a steer to the queue

* test: hover the MCP row before reaching its revealed Connect action

* test: pick the parts scenario's MCP server from the tools palette

* fix: cancel a recovered row's parked steer only after the composer takes it

A recovered row's only durable copy is the steer parked on the server, and
once its run has ended nothing can re-create it, so a composer that refused
the row after the cancel left the words in memory until the next reload.
The composer now takes the words first; a cancel that then fails holds the
row out of the run-end drain instead of sending it a second time.

* fix: name only the idle composer affordances that act

* fix: keep steer escalation off until the pane owns the rendered conversation

The branch tail that decides whether a run is paused is keyed by the pane's
conversation, which can still name the previous chat while a cached one
renders. Until the pane catches up, a pause on any cached branch now keeps
Escalate disabled instead of reading a missing or foreign tail as unpaused.

* fix: route the host's Enter and auto-send preferences into the composer's nested hooks

ChatForm takes enterToSend and autoSendText from its host, but useTextarea,
DuringRunSendButton and both speech engines still read the store atoms, so a
host whose values differ advertised one behavior while the handlers ran
another. Pass the host values through instead.

* fix: settle a browser dictation take only after its final transcript lands

stopListening resolves on the recognizer's end event, after the final result
reached useSpeechRecognition's reducer but before React committed it, so the
take settled while the composer still held the interim text. Settle from an
effect declared after the transcript effect, off a state update queued behind
the result.

* fix: drop a restored reasoning override the current setting no longer offers

The staged override was only checked for a matching parameter key, so a value
restored after a capability change on the same target stayed staged, blocked
live steering, and was dropped at send time. Validate it against the setting's
options and range.

* test: scan the attach and tools palette for accessibility

The a11y suite still opened the removed tools dropdown. Open the palette
instead, and add a scenario that runs Axe over the open palette.

* fix: make the palette's virtualized list the grid that owns its rows

The rows sat under a wrapper grid behind react-virtualized's scroller, which
always renders aria-label and aria-readonly and so could not be made
presentational. Axe reported both the disallowed attribute and the grid's
invalid child. The scroller is now the labelled grid, with a rowgroup holding
the rows.

* fix: state the palette grid's row total and each row's position

Only the rows in view are mounted, so without aria-rowcount and aria-rowindex
assistive technology reads the rendered window as the whole grid.

* fix: key an empty destination's pending steers to the route

An empty tree has no message naming its conversation, so the pending-steer
surface fell back to the chat context, which still names the source chat
during warm navigation, and its controls acted on the source run. Fall back
to the chat's messages key, which follows the route.

* fix: keep assistant uploads available when the file config fails

Assistants upload directly and never needed the destination policy, which is
why the replaced AttachFileChat rendered their uploader outside the policy
gate. Restore that exception so a failed or paused file config request does
not remove every attachment entry.

(cherry picked from commit f568a4ba30)

Original-PR: https://github.com/LibreChat-AI/LibreChat/pull/14473
2026-10-01 03:46:18 +00:00
lia-by-librechat[bot]
36ba2d3ce0 🫗 fix: Bound MCP App Responses and In-Flight Work (#16300)
* 🫗 fix: Bound MCP App Responses and In-Flight Work

* 🫗 fix: Stop Oversized App SSE Reconnect Loops

* 🫗 fix: Validate and Inject MCP App Operation Budgets

* 🫗 fix: Keep Safe MCP App SSE Streams Open

* 🫗 test: Admit Large Apps Under Configured Byte Caps

* 🫗 fix: Bound SSE-Typed App Error Responses

* 🫗 fix: Share App Admission With Initial Document Reads

* 🫗 fix: Apply App Byte Limits During Tool Discovery

* 🫗 fix: Honor Configured App SSE Line Budgets

---------

Co-authored-by: Lia <lia@librechat.ai>
(cherry picked from commit fe2b547e64)

Original-PR: https://github.com/LibreChat-AI/LibreChat/pull/16300
2026-10-01 03:46:17 +00:00
Dustin Healy
7b27e7941e 🧩 feat: MCP Apps support (#13831)
* feat: add MCP Apps support

* fix: preserve MCP App results and enforce sandbox policy

* fix: bind persisted MCP Apps to their server configuration

* fix: complete MCP Apps runtime integration

* fix: type the optional MCP App binding codec explicitly

* test: provide MCP Apps policy in bridge mocks

* fix: pass admitted App policy to the tool call owner

* fix: align MCP Apps CI contracts

* test: preserve MCP abort reasons in recovery mocks

* fix: preserve MCP compatibility across policy profiles

* test: use profiled MCP catalog generations

* test: expect the standard MCP session profile

* fix: remove the unused MCP abort import

* test: expect profiled MCP fixture arguments

* test: seed profiled MCP manager fixtures

* Fix request-header bearer resolution after canary merge

* Preserve MCP App views across canary message updates

* Document message-owned MCP App placement

* ci: Recheck MCP Apps Against Canary Base

---------

Co-authored-by: Lia <lia@librechat.ai>
(cherry picked from commit a98d40f61c)

Original-PR: https://github.com/LibreChat-AI/LibreChat/pull/13831
2026-10-01 03:46:16 +00:00
Marco Beretta
cd44344647 🔔 feat: Unseen Reply Indicators, Reply Notifications, and Mark as Unread (#15025)
* feat: add unseen reply indicators, reply notifications, and mark as unread

A reply that lands while the user is elsewhere now leaves a trace. The
conversation carries a durable reply stamp written with the assistant message
that backs it, the sidebar row shows an unread dot until that message is
actually rendered, and an optional tab badge, desktop notification and chime
announce arrivals in a tab that is away. Rows can also be marked unread by hand
from the row menu, in the archived view as well as the main list.

The stamp is written by a compare-and-swap so concurrent replies order on the
database rather than on the application hosts' clocks, and only once output that
a reader can actually see is persisted: a stopped turn with nothing to read, an
empty synchronized row, or a failed message write never lights a dot that cannot
be cleared. Read intent survives archives, metadata edits and preset applies,
and a later read always outranks a delayed unread.

* fix: gate reply alerts on config and announce only readable replies

Three review rounds kept finding the same two shapes, so both are answered once
rather than patched again.

The alert capabilities are now operator-configurable through
`interface.replyNotifications` in `librechat.yaml`: the tab badge, desktop
notifications and the chime each have a gate, and the away poll's page size is a
field rather than a constant, with defaults that reproduce the shipped behavior.
A capability the operator turns off reads as off whatever the device stored, and
its settings toggle is not offered.

Deciding whether a persisted turn may raise an indicator now lives in one place
in `packages/api`, with the Responses API controller, the abort route, the
Assistants thread sync and the client's override path all calling it instead of
carrying their own copy. That closes the last case where a reply nobody can read
lit a dot nothing could clear: a `/v1/responses` completion whose output held
only reasoning or tool calls persists an empty row, and stamping it left an
unread conversation that opening could not settle.

Also: the retention backfill no longer advances `updatedAt` past a reply stamp,
which an away tab reads as a metadata-only promotion and withholds the alert
for; arrival evidence is swept of conversations no cached list still holds, so a
long-lived tab stops growing with its lifetime number of replies; and generated
Lighthouse profile directories are ignored where the runner leaves them.

* test: open the sidebar by what the drawer paints, not by its test ids

The drawer became a mounted, sliding panel on canary, so the controls this
helper read no longer say what it assumed. `close-sidebar-button` answers from
the off-canvas copy before the expanded state commits, which returned the helper
with the conversation list still hidden behind the pane, and the panel's own
`new-chat-button` has a rail copy that a plain locator reaches first. Both
readings passed on the previous drawer, which unmounted when closed.

Settling on the close control's accessible name, and on the first candidate that
is actually painted, is what a reader perceives and survives either drawer. One
click is one toggle and the opener sits in the pane the drawer marks inert for
the whole of its travel, so each attempt is given that travel to itself rather
than reissued into it.

Also serves `interface.replyNotifications` in the operator-gate scenario with a
fresh body instead of the upstream response, since reusing its encoding headers
for a re-serialized payload leaves the client unable to read the config, which
looks exactly like an operator who configured nothing.

* fix: gate the assistant save on renderable output and stop overselling the poll limit

Two gaps this round's own work left behind.

`saveAssistantMessage` still decided to stamp from the message id alone, so an
Assistants run that persisted an empty row raised a dot that opening the
conversation could never clear. It now asks `isAnnounceableReply`, the same
predicate every other persistence path asks, which is the point of having moved
that decision into one place.

`pollLimit` advertised a range up to 1000 while `getConvosByCursor` clamps every
conversation read to a hundred-row page, so an operator who set 500 would have
been told it applied and silently served a hundred. The schema now stops at the
page the server will actually return; covering a deployment whose replies
outpace one page needs the server-side unseen query, not a wider page.

* test: let the mobile scenarios use the surface they are actually asserting on

Three scenarios opened the drawer on a page they only ever send a reply from.
On the mobile project that drawer sits over the composer and marks the pane
inert, so there was nothing left to type in and the run waited out its whole
budget. They ask for the composer now, which is what they were always about.

The two that read a row after leaving the list open it again first. A reply sent
from another tab closes this one's drawer, because `sidebarExpanded` is stored
per browser rather than per tab, and opening a chat closes it the way it does
for a reader. Both are what someone would do to look at the row, and neither
changes what is being asserted.

Mark as unread is dispatched rather than clicked, like the row controls around
it: the menu is portaled, and behind the drawer's scrim it inherits
`pointer-events: none` and goes click-dead.

* test: dispatch the row menu's unread item like the controls around it

The portaled menu sits under the mobile drawer's scrim, which intercepts the
pointer, so a real click retried until the budget ran out. The sibling scenarios
and the row's own controls already dispatch; these two were the last real
clicks.

* fix: hold reply alerts until the deployment answers, and read the resolved temporary state

The capability gate treated a startup config that had not loaded yet the same as
one that set nothing, so a device that stored "on" could badge, poll or notify in
the window before an operator's `false` arrived. Nothing is permitted now until
the config is in hand; only a loaded config that lacks the field reads as the
shipped default, which is the case a backend predating the setting produces.

The Responses API announcement read the temporary flag from the request body
alone, while the conversation save beside it resolves it from the stored
conversation first. A temporary chat restored or resolved on the server without
the flag in the body would have been announced through the unread indicators;
both completion branches now resolve it the same way the save does.

* fix: route the last reply stamps through the shared owner and hand back failed claims

Moving the announce decision into packages/api left three callers still deciding
for themselves. The agents controller re-stamped an unfinished turn whose
terminal persistence was skipped, and the resumed legacy turn stamped its
directly saved row, both from the message id alone, so a preempted or stopped
turn that persisted nothing readable lit a dot that could never be
acknowledged. Both ask isAnnounceableReply now. The non-agents abort path
carried an inline copy of the same predicate; it calls announceReply instead.
Error turns keep their direct stamp: the error card is what renders them.

A notification claim was written to shared storage before the notification
was constructed, so a constructor that throws left the reply claimed in every
tab with nothing ever shown. The claim is handed back when construction fails,
removed only while it still names that exact stamp.

* fix: judge the normal reply save by the shared predicate and hand back failed chimes

The regular BaseClient save still stamped any assistant reply that persisted,
readable or not, because the conversation write took a bare reply id. It takes
the persisted reply now and asks isAnnounceableReply before it stamps, which
leaves the error turns as the only direct stamps, and those are rendered by the
error card. saveTurnConversation is exercised against a real store in both
directions. announce.ts derives its write-context type locally so the two
modules do not import each other.

The chime claimed its replies before building the tones, so an output that
failed while they were being scheduled left them claimed in every tab with
nothing played. Those claims are handed back on failure, the same way a
notification that could not be constructed now releases its own.

* feat: let operators set the reply polling cadence

The away poll and the focused refresh were fixed at 30 seconds and five minutes,
which are request-rate levers on the conversation list and nothing an operator
could tune. Both are fields on `interface.replyNotifications` now, bounded and
defaulting to the values they had, and the watcher reads them through the same
capability hook as the rest of the block.

* fix: keep reply identity through list merges and drop rows the server no longer has

The list merge carried three of the four read-state fields by hand and left out
`lastResponseMessageId`, so an SSE update on an unseen conversation erased which
branch the reply landed on, and a missing identity reads as visible. It uses the
same `preserveReadState` helper as the other two merge paths now, and the test
that covered the other three fields covers this one too.

A local cache merge was only inspected on a list's first page for new arrivals.
A title or oldest-first sort leaves a replied row where it is, so its first
reply on a later page went into the alerts baseline without an arrival and its
chime or notification was lost. Local merges scan every loaded page; server
responses keep the first-page rule, and only rows already known are considered.

An unread request that matched nothing means the conversation is gone: the
server's owner-scoped update returns the row even for a no-op. The mutation
rolled back the read fields and kept the row; it removes it from the caches now,
as a delete does.

* fix: discard a job completion that resolves after the watcher has gone

The fetch that settles a finished job had no teardown guard, unlike the away
poll. Signing out or switching accounts unmounts the watcher, and a response
still in flight for the previous session would then merge into the caches the
next one reads. The result is dropped once the watcher has unmounted, tracked
on unmount rather than in the jobs effect's cleanup, which re-runs on every
change to the running set while its earlier completions are still wanted.

* fix: move error-turn stamps into packages/api and settle overlapping unread no-matches

Error turns were stamped in CJS: the error middleware checked eligibility, called
the stamp and shaped the event's conversation snapshot itself, and the agents
controller stamped its own. Both call announceErrorTurn now, and the
skipped-persistence restamp goes through announceReply, so no stamp is issued
directly from /api any more. The existing sendError tests pass against the real
helper unchanged.

An unread call that no longer owned the row dropped a server no-match with the
rest of its stale answers, so a deleted conversation could be restored by a newer
call's rollback. The no-match now evicts before ownership is consulted. It stays
after the superseded check: a superseded call never reached the server, and its
synthetic `modified: false` is not a no-match.

Also: Settings offers the reply toggles only once the startup config has loaded,
matching the capability hook; a cancelled reply-discovery snapshot is restarted
even though nothing observes it; and the focused refresh is capped at the five
minutes the discovery snapshot stays authoritative, since that refresh is what
renews it.

* fix: settle the assistant final in packages/api, announce attachment-only replies

Both assistant controllers carried the same persistence barrier: write the
response, check the row and the conversation both persisted, and unwrap the
settled conversation for the final event. That is behaviour, and it was
duplicated in CJS; settleAssistantFinal owns it now and the controllers call
it. Their existing tests pass unchanged.

The announce predicate ignored attachments, so a reply made only of files,
such as a resumed workspace artifact with empty content and text, raised no
dot, badge or alert. The message body renders attachments and acknowledgement
checks the body, so such a reply can be cleared as well as announced; every
announce path now passes them through.

The stopped-reply announcement took the storage engine's own id type in its
exported signature. It takes plain string ids now, and saveConvo accepts them
alongside its own, since the update casts them against the schema; the id type
stays inside data-schemas.

* fix: normalize the stopped reply's written ids in packages/api

The abort route filtered and stringified the ids of the rows it had written
before handing them to announceStoppedReply. That is data shaping, and it sat
in CJS; the announcement takes the ids as the caller holds them and drops the
unwritten ones itself.

* style: order the conversation row classes for Tailwind v4

The v4 upgrade on canary changed the class order Prettier enforces; these
three rows carried the v3 order.

* fix: replay replies a dead tab's focus lease held back, keep the focused refresh at a full page

A tab killed without firing blur or pagehide leaves its focus lease for up to
a minute. A reply arriving under it was baselined and then suppressed, and
nothing reran when the lease lapsed, so its chime and notification were lost.
Arrivals held back only by another tab's lease are kept and rechecked when
that lease expires; a lease the focused tab keeps refreshing still holds them.

The focused refresh reused the away-poll limit, so an operator who lowered it
also shrank the discovery page that keeps the unseen count complete behind a
filtered list. The limit now bounds only the away poll.

* fix: announce a held reply as soon as the focused tab releases its lease

A tab that blurs normally clears its lease long before the lapse, and a reply
held back for it is due as soon as nobody is looking. Lease changes from other
tabs now trigger the recheck, not only the expiry timer.

(cherry picked from commit b947738d0d)

Original-PR: https://github.com/LibreChat-AI/LibreChat/pull/15025
2026-10-01 03:46:16 +00:00
Marco Beretta
0a85ff5c59
✂️ fix: Keep Parts After a Summary in the Summary-Bounded History Read (#16434) 2026-09-30 09:26:46 +02:00
Danny Avila
f15c8a0f1b
🗂️ fix: Stop Telling Attached Workspaces That Uploads Are at /mnt/data (#16389) 2026-09-26 22:04:05 -04:00
lia-by-librechat[bot]
dd21e7fb6d
📣 fix: Surface MCP Credential Failures During Tool Loading (#16323)
* 📣 fix: Surface MCP Credential Failures During Tool Loading

* fix: address MCP credential propagation review

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-24 22:53:31 -04:00
Danny Avila
f13b0eaef4
🚚 chore: Point Repository and Image References at LibreChat-AI (#16005)
Some checks failed
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
Docker Dev Images Build / publish (push) Waiting to run
Sync Helm Chart Tags / Ignore non-main push (push) Waiting to run
Sync Helm Chart Tags / Sync chart tags (push) Waiting to run
Publish `@librechat/client` to NPM / pack (push) Has been cancelled
Publish `librechat-data-provider` to NPM / pack (push) Has been cancelled
Publish `@librechat/data-schemas` to NPM / pack (push) Has been cancelled
Publish `@librechat/client` to NPM / publish-npm (push) Has been cancelled
Publish `librechat-data-provider` to NPM / publish-npm (push) Has been cancelled
Publish `@librechat/data-schemas` to NPM / publish-npm (push) Has been cancelled
Update package repository and bugs URLs, GitHub links in docs, templates and comments, and image references (compose files, deployed-update, Helm values and renovate hints) from danny-avila to LibreChat-AI / librechat-ai. Covers the rag-api repository and its images, which moved to the organization. Sponsor links and the sealed star-history chart are unchanged.
2026-09-23 23:08:36 -04:00
lia-by-librechat[bot]
44703da3c6
🫖 fix: Skip Blank RAG Queries Before Embedding (#16231)
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
Co-authored-by: Lia <lia@librechat.ai>
2026-09-23 01:15:04 -04:00
Danny Avila
aacf1de9da
🗂️ fix: Keep a Running Attachment Chat in the Sidebar (#16104)
* 🗂️ fix: Keep a Running Attachment Chat in the Sidebar

Since #15694, a turn with model-bound attachments defers its user-message
write until the model admits the payload. That write was also what created
a new conversation's row, so for the whole first model call, which with a
long generated script or extended thinking can run for minutes, the
conversation did not exist. Any conversation-list refetch in that window
(starting another chat, deleting one, reloading) dropped the running chat
from the sidebar until its run finished, and GET /api/convos/:id answered
404 for it.

When attachments are the only reason to defer, the new conversation's row
is now written as the run starts, carrying the same fields the message
write would set but no message. The message itself stays deferred until
admission, and its write waits for a seed still in flight so the two
upserts never race. A content policy still holds back every write, the
row included, as #14425 intended.

The conversation half of saveMessageToDatabase moves into
saveConversationToDatabase so the seed and the message write share one
path.

* 🧱 refactor: Own Turn Conversation Writes in packages/api

The conversation half of a turn's writes (the row a message save
upserts, the retention context it stamps, and the new seed ahead of a
deferred first message) moves into `conversations/save.ts`, which takes
`getConvo`/`saveConvo` from the caller. BaseClient keeps only the
wiring: the retention lookup that must stay synchronous for Stop, the
message save, and the calls into the module.

The seed passes an empty `appendMessageIds`, which tells `saveConvo`
the row holds no messages yet, so it no longer reads the message list
before the upsert. It also resolves the conversation once and leaves it
on the request, so the deferred message save reuses it instead of
looking the conversation up again.

save.spec.ts drives the real data-schemas methods against an in-memory
MongoDB: the seed creates an empty row without reading messages, the
message save appends to it without a second lookup, an existing chat and
a subagent thread are left alone, a temporary chat keeps its retention,
and a failed lookup settles instead of rejecting.
2026-09-19 15:51:02 -04:00
Danny Avila
db674eda60
🔓 fix: Stop Code Outputs and Tool-Routed Spreadsheets From Locking Threads (#16058)
Since #15694 bounded each turn's attachments across history, a thread whose
history counts more than `fileLimit` model-bound files is refused on every turn,
including turns that attach nothing. Two kinds of file reached that count that
never belonged in the prompt.

Code outputs: priming clears an expired sandbox reference on the turn's copy of
the record so the file is re-provisioned, and a route-less record without a
reference was classified as prompt content, so it counted toward the limit and
could be encoded as media. Code outputs now stay tool-owned regardless of
reference liveness, through one predicate shared by admission, BaseClient
delivery and the child run-file encoder.

Tool-routed spreadsheets: with `textFallbackWithoutTools`, #16027 delivered the
fallback text until a tool held a copy. Run Code receives its copy only on its
first call, which a refused turn never makes, so the text counted on every later
turn. An enabled Run Code is a reader again for the types it can read; File
Search still reads only what its store holds.
2026-09-18 06:04:47 -04:00
lia-by-librechat[bot]
9e83b10545
📭 fix: Deliver Attachment Text Until a File Tool Holds It (#16027)
* 📭 fix: Deliver Attachment Text Until a File Tool Holds It

A `none`-routed upload had its extracted text withheld whenever a file tool was
enabled, on the assumption the tool would serve the file. A plain chat with the
File Search toggle runs an ephemeral agent, so the upload is filed under no tool
resource and never embedded: the text was withheld for a vector store that never
received the file, and the attachment reached nothing.

Withholding now requires the record to show the tool holds the file, which is the
same evidence deferred provisioning reads before queueing it. `resources.ts`
delegates to that shared predicate so the two cannot disagree again.

* test: Give the Code-Running Primary Agent a Sandbox Copy

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-16 15:46:35 -04:00
Danny Avila
dea7346d72
🧷 feat: Carry Ask User Answers Past Compaction (#15944)
* 🧷 feat: Carry Ask User Answers Past Compaction

The user's answers to `ask_user_question` lived only in the tool result that
received them. A checkpoint summary, the tool-output pruner or a full context
window could remove that message, and the agent then asked again or acted on
a summary's paraphrase.

Every answered ask on the conversation branch is now rendered verbatim into
the run's dynamic instructions, on the first request and on every resume,
where the answer just given is read from the seeded content. Older answers
drop first past a token budget; the newest set is always kept.

New lever: `endpoints.agents.askUserQuestion.retainedAnswers` (`enabled`,
`maxTokens`), on by default with a 4096-token budget.

* 🧷 feat: Carry Ask User Answers Past Compaction

The user's answers to `ask_user_question` lived only in the tool result that
received them. A checkpoint summary, the tool-output pruner or a full context
window could remove that message, and the agent then asked again or acted on
a summary's paraphrase.

Every answered ask on the conversation branch is now quoted verbatim at the
top of the current user turn's prompt copy, in the user's own role: rebuilt
from the stored rows every turn, never persisted, excluded from the memory
copy, and counted in the prompt total with the active encoding. A warm
event-actor turn reads the branch on demand. Older answers drop first past a
token budget that includes separators; the newest set is always kept.

New lever: `endpoints.agents.askUserQuestion.retainedAnswers` (`enabled`,
`maxTokens`), on by default with a 4096-token budget.

* 🧷 refactor: Read The Warm Branch Inside The Module

The warm event-actor read lived as a conditional and a `getMessages` call in
the CJS client. The typed module now takes `historyLoaded`, the identity and
the query as dependencies, decides when to read, and owns the failure policy
for both the read and the block itself; the client passes plumbing only.

* 🧷 fix: Complete The Branch Behind A Summary Cut

`loadHistory` already stops its walk at a checkpoint summary, so the rows
`buildMessages` receives never held the answers this feature carries. The
module now detects a branch that stops short of its root, whatever cut it,
and completes it through the injected stored-row query, stored rows winning.

The block goes on the latest user-authored row so a continued generation
keeps it, and the render measures the whole block before reserving the
omission note, so a set is only dropped when something truly has to go.

* 🧷 fix: Reuse Loaded History And Read Every Ask Stamp

A post-compaction turn read the conversation twice: once in `loadHistory`,
which cuts at the checkpoint summary, and again in the module to complete
the branch. The loader now keeps the rows it read and the module prefers
them, querying only for a turn that made no history read.

Two stored shapes were missed: a pause record whose `args` is the bare
question string, now read as the legacy question, and a call whose input
failed validation, whose persisted error output is no longer quoted as an
answer.

* 🧷 fix: Keep The Block Off The Stored Row And Out Of Memory Copies

Array-form content is replaced instead of edited through the array the
stored row shares, the block's cost is measured as two fresh counts of the
same copy rather than against a possibly calibrated stored count, the
memory copy is only built when memory extraction will read it, the loaded
rows reach the agents client through a hook and are released once the block
exists, and the tool-call-id merge is gone: rows are unique by message id
and providers may reuse ids across turns.

* 🧷 refactor: Apply The Answers Block Inside The Module

The placement lookup, the prepend, the count delta and the memory-copy
decision lived in the client after the context kickoff. They now live in
`applyRetainedAnswers`, which receives the rows, the prompt copies, the
count map, the counter and the memory dependency; the client keeps one
call and passes plumbing.

* fix: Apply Retained Answers After Summary Replay 🧷

* perf: Count Retained Context Exactly Within Its Budget 🧮

* fix: Preserve Retained Counts Across Checkpoint Recounts 🧾

* fix: Isolate Retained Context Counting and Provenance 🧵

* fix: Replace Warm Retained Context and Verify Answer Provenance 🪪

* fix: Use Workspace-Compatible Array Traversal 🧭

* fix: Refresh Retained Context at the Warm Turn Boundary 🧲
2026-09-14 21:35:07 -04:00
Danny Avila
2ffee7e143
🪂 feat: Opt-In Text Fallback for Files No Tool Can Read (#15940)
* 🪂 feat: Opt-In Text Fallback for Files No Tool Can Read

An upload routed to tools (`llmDeliveryPath: none`) reaches nothing when the
agent handling the turn runs neither Run Code nor File Search, or runs one that
cannot read the type. With `fileConfig.endpoints.<endpoint>.textFallbackWithoutTools`
(also accepted at the top level and inherited from `default`), such a turn
delivers the text extracted at upload instead. The setting is off by default,
which keeps today's behavior.

- Upload: when the setting is on and an inferred `none` route finds no reading
  tool, the built-in document parser or native text reader stores the text on
  the file, best effort, under the extracted-text size cap and content policy.
- Turn: `resolveTurnLLMDeliveryPath` re-resolves each inferred route against
  the tools the agent runs, and `applyTurnTextFallback` marks copies of the
  records a turn loads, so endpoint filtering, limits, inspection, history
  replay and steer media all see the text the turn delivers. The stored route
  is never rewritten.
- Explicit destinations, records predating routing, and turns whose tools are
  unknown are left as they are.

* 🧪 test: Resolve Custom Endpoint Fallback Under the Endpoint Name

Uploads route a custom endpoint agent by its saved provider, the endpoint name. initializeAgent marks turn copies before getProviderConfig swaps the provider for the backing client, and the endpoint keeps the name afterward, so the client and child encoders resolve the opt-in under the same endpoint. Cover both the initialization path and the post-initialization agent shape.

* ♻️ refactor: Share One Extracted-Text Storage Cap Across Uploads

The fallback defined its own copy of the 15 MiB cap context uploads already apply to extracted text. Export MAX_STORED_EXTRACTED_TEXT_BYTES from files/extract and use it in both places, documenting that it bounds what a MongoDB file document can hold rather than operator policy.

* 🧭 fix: Keep Fallback Text Wherever a Later Turn Can Deliver It

Extraction skipped uploads filed under a reading tool, so a handoff agent
without that tool, or the same agent after its tools or grants changed, had
no text to fall back to. Store fallback text for every inferred route on a
message attachment; files kept on an agent's tool resources never reach a
prompt and still skip it.

Turn marking only ran while the fallback was enabled, so a stored tool-routed
record whose type the endpoint now routes to text stayed marked `none` and
`extractFileContext` skipped it. applyTurnTextDelivery (renamed from
applyTurnTextFallback) now marks any stored `none` record with text that the
turn resolves to text, and returns early when no such record is loaded.

* 🚦 fix: Admit Every Attachment by the Route Its Turn Delivers

A record upload routed to tools that the current endpoint sends to the
provider stayed marked `none` on the turn copy, so admission skipped it while
BaseClient encoded its bytes, bypassing attachment count and size limits.
applyTurnDelivery (renamed from applyTurnTextDelivery) now gives every record
whose route upload inferred the route the turn resolves, before endpoint
filtering, limits and inspection, matching the run-file encoder.
hasInferredLLMDeliveryPath shares the inferred-route rule with the resolver.

Fallback extraction selected the document parser inside the CJS upload path.
resolveUploadFallbackText now takes the upload and picks parseDocument or
parseTextNative itself, with the extractors injectable, so process.js passes
request data only. Its tests run the real parser against the xlsx fixture and
the real native reader against temporary files.

* 🎚️ fix: Read Custom Endpoint Dialect From Config on Both Sides of Init

initializeAgent materializes turn routes before getProviderConfig swaps the
saved custom endpoint name in agent.provider for its backing client, so
routing read that name as a non-OpenAI dialect. Media a custom endpoint opted
into could then be materialized off the provider path, skipping admission,
while the finalized client still sent the bytes. resolveAgentDeliveryRouting
now reads the dialect with getCustomEndpointProvider, as upload does, which
holds before and after the swap.

The upload fallback plan now keys on the chosen-destination marker the turn
resolver reads, so an upload recorded as chosen, including every legacy
chooser upload, never pays for text a turn cannot deliver.

* 🛡️ fix: Apply Turn Routes Only While the Record Stays Admitted

Resolution while initializing and at delivery can disagree: delivery reads a
Responses API choice only the finished client config holds. Applying a route
that takes a record out of admission, off the model path or to text it never
stored, would then skip the limits for a file the client still sends.
applyTurnDelivery now applies a route only while the record stays model-bound;
admitting a record the turn leaves out cannot slip past a limit.

* 🕹️ feat: Run Declared Project Actions on Attached Workers (#15943)

* feat: use declared attached project actions

* Complete named action definitions and approval previews

* Sort named environment imports

* Sort native environment fixture imports

* 🔓 fix: Keep Code Approval Mode Selectable Mid-Run (#15938)

* 🔓 fix: Keep Code Approval Mode Selectable Mid-Run

The composer's code approval mode selector was disabled while a run streamed, and a mode picked during a run was reverted when the final or abort event merged the server conversation back. The selector now stays usable in flight and both merges retain a mid-run selection, which the next send carries.

* 🔓 fix: Retain Mid-Run Approval Mode Across Cache and Recovery

Stamp the live approval mode onto the submission conversation at send so the retention baseline matches what was read, keep a retained mode in the conversation query cache on final and cancel, and rebuild failed or aborted conversations from a preset that carries the mid-run pick.

* 🔓 fix: Scope Retained Approval Mode to the Submitted Conversation

Retention now requires the live conversation to be the one the run submitted, or the id the server assigned to a new chat, so navigating elsewhere mid-run cannot write that conversation's mode back. A single recovery helper rebuilds failed or aborted conversations from the retained preset and patches the detail cache for every recovery site.

* 🔓 refactor: Keep the Local Approval Mode on Every Server Merge

Replace per-path retention with one rule: a locally picked code approval mode is newer than any server copy of the same conversation, so the final and abort merges and the error recovery preset keep it. The selector writes the pick into the conversation's detail cache, which navigation rebuilds from, so the pick is conversation-scoped without reading the index-global atom from the SSE handlers.

* 🔓 fix: Prefer the Live Conversation When Caching the Final Merge

The final handler's detail-cache merge now takes the local approval mode from the open conversation when it is the one that finished, falling back to the cached record only for a conversation that is no longer on screen.

* 🔓 fix: Keep the Local Approval Mode Through Settled-Start Reconciliation

The resumable transport's settled-start reconciliation and replacement handoff wrote a fetched conversation straight into conversation state and the detail cache. Both now apply the same local-mode rule as the event handlers, treating a new chat's pending id as the settled conversation's own.

* 🔓 fix: Seed the Detail Record When a Mode Is Picked

A conversation that has its id but no detail record yet now gets one from the live conversation when a mode is picked, the same key the resumable transport seeds optimistically, so recovery and navigation find the pick. A chat with no id yet still keeps the pick in conversation state alone.

* ⬆️ chore: bump agents to 3.8.7 (#15947)

* 🧭 refactor: Settle Turn Delivery Routing Once in Agent Initialization

`initializeAgent` resolved the provider and its client options only after the
turn's files were loaded and admitted, and the two delivery readers each rebuilt
the attachment routing from the agent object at their own moment: `BaseClient`
took the custom-endpoint dialect from the already-swapped `agent.provider`, the
run-file encoder from whatever child config it was handed.

Move `getProviderConfig`/`getOptions` ahead of file discovery, where nothing in
between fed them, and settle one `deliveryRouting` value with every input final:
the file policy under the endpoint's own name, the dialect its config declares,
the Responses API decision the model call uses, and the transcription setting.
`InitializedAgent`, the child encoder and `BaseClient` consume that value;
`resolveTurnLLMDeliveryPath` is the one place a stored route is resolved again.

* fix: Preserve attachment reachability across handoffs and late steers

* test: Type the untrusted attachment reference fixture

---------

Co-authored-by: Ravi Kumar L <upman@users.noreply.github.com>
2026-09-14 21:02:54 -04:00
Danny Avila
2f8bc3dfcd
🎞️ fix: Deliver Opted-In Custom Endpoint Media Safely (#15937)
* feat: send video/audio to custom endpoints that opt in via supportedMimeTypes

The video and audio encoders only emitted OpenAI-format parts (video_url,
input_audio) for OpenRouter, and Google's media part for Google/Vertex. For
every other provider the file was validated and then silently dropped, so a
custom OpenAI-compatible endpoint (vLLM, LiteLLM, ...) never received the
attachment even though the wire format is identical to OpenRouter's.

Emit the OpenAI-format part for OpenAI-like providers when the endpoint's
fileConfig supportedMimeTypes explicitly allows the file's type. The inherited
default list does not count as opting in (isExplicitMimeConfig, keyed on
referential identity like the client's picker), so endpoints whose gateway
cannot handle media are unaffected.

* feat: let a configured custom endpoint pick and attach video/audio

The attach menu's Upload to Provider filter and the drag-drop viability check
only opened video/audio for Google and OpenRouter, or for a custom endpoint
with a fully permissive (.*) supportedMimeTypes. Honor any admin-configured
allowlist on a custom endpoint instead, so a finite list that includes
video/.* or audio/.* is enough, matching the server-side encoders.

* fix: canonicalize input_audio format from MIME type

The `input_audio.format` value was derived from the filename extension via
`filename.split('.').pop()`, which produces values providers reject:

- `clip.wave` (audio/wave) emitted `wave`, but the accepted format is `wav`
- a file with no extension (`recording`) emitted the whole filename, since
  splitting a dotless string yields a single-element array, so the existing
  non-empty guard never fired
- `clip.mpeg` (audio/mpeg) emitted `mpeg` rather than `mp3`

All of these pass MIME validation and then fail at the provider. Derive the
format from the MIME type instead, mirroring the canonicalization already in
STTService, and fall back to the filename extension only when it is itself a
supported format. Throws when neither source yields one rather than sending an
unsupported value.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix: route opted-in custom endpoint media to the provider path

In unified upload mode an upload carries no tool resource, so its delivery path is
inferred by resolveDefaultLLMDeliveryPath. That resolver judged audio and video for any
named endpoint with isMediaSupportedProvider, which lists only Google, Vertex and
OpenRouter, so a custom endpoint that opted into media through supportedMimeTypes still
recorded video as none and audio as text, and the encoder branch was never reached.

The upload resolver already holds the endpoint's file config, so it now passes the
endpoint's supportedMimeTypes through, and an explicit match on an OpenAI-compatible or
custom endpoint counts as provider-capable, mirroring isConfiguredProviderMediaType on
the encoder side. The inherited default list is still not an opt-in, and known providers
whose encoders emit nothing for media are unchanged. BaseClient re-resolves per turn with
the same function, so the turn path follows.

* fix: scope the media opt-in to custom endpoints that run as OpenAI

The opt-in applied to the built-in openAI and azureOpenAI endpoints too, but the picker
and drag-drop only open media for custom endpoints, so that was a route the client could
not send to. It is now limited to endpoints that are not a known provider.

A custom endpoint may also declare provider: anthropic, in which case initialization runs
it as Anthropic and the encoders emit no media part for it. getCustomEndpointProvider
reads that declaration off the app config, the upload callers pass it as endpointProvider,
the agent encoder and BaseClient pass the agent's resolved provider, and an endpoint known
to run as something other than OpenAI keeps its previous route: video stays off the model
path and audio still reaches transcription.

* fix: reject unsupported provider audio during upload

---------

Co-authored-by: Renato Garita Figueiredo <renato.garitafigueiredo@uni-osnabrueck.de>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-14 16:38:51 -04:00
Danny Avila
345cf8877f
🍵 fix: Support Renewable MCP Credentials for Schedules (#15908)
* fix(schedules): forward renewable MCP credentials

* fix(schedules): require unattended MCP credentials

* fix(schedules): resolve MCP credentials during execution

* refactor(schedules): inject unattended credentials

* fix(schedules): scope renewable credential resolution

* fix: isolate lazy scheduled OBO credentials across MCP lifecycle

* fix: preserve MCP cancellation and retryable credential lookup

* fix: bind MCP cancellation to the owning run signal

* test: supply flow manager in OBO cancellation regression

* fix: preserve MCP cancellation across exchange and API ingress

* style: sort MCP manager imports

* fix: propagate cancellation through agent discovery

* test: preserve agent discovery edge literals

* fix: propagate agent initialization cancellation

* fix: expose initialization signal in OpenAI adapter
2026-09-14 10:27:47 -04:00
Marco Beretta
b204216c64
🧷 fix: Keep a Failed Summary From Bounding the Conversation History (#15913)
* 🧷 fix: Skip Failed Summaries When Resolving the Conversation Checkpoint

* 🧷 fix: Keep a Failed Summary Out of the Model-Facing History Boundary

* 🧭 refactor: Own the Summary Checkpoint Predicate in packages/api

* 🧯 fix: Reject Unfinished Summaries Everywhere and Recount Stripped Turns

* 🧬 fix: Version Event-Actor Summary State So Legacy Prefixes Cannot Warm

* 🏷️ fix: Stamp Inherited Summaries Where Actor State Is Assembled

* ⚖️ fix: Drop Unusable Summaries While Building the Prompt

* 🧷 fix: Repoint Prompt Content Instead of Splicing Stored Parts

* 🧭 fix: Treat a Streamed Summary Without a Boundary as Unfinished

The server has stamped `failed` on an errored summarize round only since
#14546, and `summarizing` never reaches storage, so every round that errored
on v0.8.7 or rc2 was persisted as a plain summary holding its partial deltas.
The flag checks cannot tell that row from a checkpoint, so upgraded
conversations kept losing the history before it.

The aggregator settles it structurally, identically in every SDK release
that has shipped compaction (3.1.63 through 3.8.6): deltas stream `content`
blocks into the part, and only a completed round replaces the part with the
final block, which is the sole writer of `boundary`. A `content`-block summary
without a boundary therefore never finished. `isUsableSummaryPart` and the
shared `isCompactedLeaf` both apply that rule; bare-`text` rows predate the
aggregator and stay governed by the flags.

Fixtures that stand for completed summaries now carry the boundary a real
run writes, and the flag fixtures keep one so they still test the flags.

* 🔁 fix: Strip Unusable Summaries From Responses API Continuations

`previous_response_id` loads the stored conversation and hands each message's
`content` array straight to `formatAgentMessages`, whose summary scan takes
the last summary part carrying text as the history boundary. The chat client
strips unusable summaries before that scan; this entry point did not, so a
conversation continued through the Responses API still lost everything before
a failed round. The same packages/api helper now runs ahead of the formatter.

* 🧭 refactor: Own Event-Actor Summary Selection in packages/api

`getLatestEventActorSummary` decides which summary a warm continuation
carries forward, how a missing token count is recorded, and how the state is
stamped. That is compaction behavior, and every helper it relies on already
lives in `packages/api/src/agents`, so it moves beside `isUsableSummaryPart`
and the controller imports it.

* 🧪 test: Give the Finished Compaction Leaf the Boundary a Completed Round Writes

`isCompactedLeaf` now requires the boundary only a completed summary block carries, so the client fixture for a finished compaction needs one, and a boundaryless leaf joins the interrupted compactions that can be retried.

---------

Co-authored-by: Danny Avila <danny@librechat.ai>
2026-09-14 10:22:47 -04:00
Danny Avila
696bcb6c1e
🏦 fix: Reserve Credits for In-Flight Requests (#15879)
* 💳 fix: Reserve Balance for In-Flight Requests

Admit each balance-checked request against the credits that other
in-flight requests have not already reserved, and hold its prompt cost
on the balance record until the turn settles. Apply a due auto-refill in
the same fenced write so one refill window credits exactly once.

- data-schemas: reserveBalance / releaseBalanceReservation replace
  createAutoRefillTransaction; the write is a compare-and-swap on
  tokenCredits, reservations and lastRefill (no pipeline updates)
- balance.reservations is select:false so existing reads never see it
- checkBalance returns a reservation handle; BaseClient and the
  assistants controllers release it once the turn settles
- balance.reservationTtlMs bounds how long an unreleased reservation
  counts (default 30 minutes)

* 🧮 refactor: Admit Reservations Without Contention and Record Refills Durably

- admission is a conditional $push/$inc against a reservedCredits total,
  so concurrent admissions of a funded balance commit on their first write
- expired reservations are pruned per element with their credits
- auto-refill is fenced on every setting its decision reads and leaves a
  pendingRefill ledger marker in the same write; any later read records the
  transaction under the fixed id and clears the marker
- a missing record is created with $setOnInsert inside reserveBalance
- reservation lifecycle moves to packages/api (createBalanceReservations,
  withBalanceReservations); BaseClient releases once usage is recorded

* 🪪 fix: Resolve Each User to One Balance Record

- balance records a creator inserts are keyed by the user id, so creators
  racing on a missing record converge on one document; every balance read
  and write resolves a user to their oldest record, so existing duplicates
  stay inert
- upsertBalanceFields takes insert-only fields; the balance-config
  middleware, schedules and lazy initialization pass the starting credit
  through them so it never overwrites a record another writer created
- the auto-refill write is also fenced on reservedCredits
- the scheduled-chat balance pre-skip counts reserved credits as unavailable

* ⏳ fix: Count Only Unexpired Reservations in Scheduled Balance Checks

findBalanceByUser with includeReservedCredits now totals the reservations
that have not expired, so a reservation left by a crashed request stops
pre-skipping scheduled chats at its expiry instead of when a later
reservation write prunes it.

* 🔁 fix: Renew Balance Reservations While Their Request Runs

A reservation is renewed every half TTL until it is released, so only a
reservation whose process stopped expires. Pruning removes a reservation
only while it is still expired at the write, so one renewed after the
pruning read survives.

* 🛟 fix: Keep Reservations Alive Through Renewal Failures and Lost Acks

- renewal reschedules itself: every half TTL, capped to the timer range,
  and a failed renewal retries within a tenth of that window
- an admission write that errors removes its possibly committed
  reservation before rethrowing

* 🛑 fix: Hold a Stopped Turn's Reservation Until Its Charge Lands

- an aborted turn lets its reservations lapse after a minute (or the TTL)
  instead of releasing them, so the Stop request's charge lands before the
  credits are admitted again
- balance.reservationTtlMs has a 10 second minimum, enforced in the schema
  and at runtime, so renewal stays bounded

* ↩️ revert: Release a Stopped Turn's Reservation When the Turn Settles

An aborted turn releases its reservations when it settles, the same as
every other exit, instead of holding them for a fixed lapse window that
refused funded requests after every Stop. The minimum reservation TTL
stays.

* ⏸️ fix: Hold Assistants Reservations Through Background Run Retries

An in-progress Assistants run continues in the background after the
handler responds; the turn's reservations now stay held until that run
settles (createBalanceReservations().holdUntil).

* 🔁 fix: Apply an Auto-Refill Once per Admission

A refill interval that is due again the moment it is applied, such as a zero
interval, let one admission refill repeatedly until the retry bound. Each
admission now applies at most one refill, as the previous check did.

* 🧹 fix: Prune Expired Reservations in One Write

An admission that found expired reservations issued one write per hold, so a
backlog left by a stopped process fanned out into as many concurrent writes.
The prune is now a single write fenced on every hold it removes; a hold renewed
after the read makes the write miss and the admission re-read.

* ⏱️ fix: Renew Reservations From Their Stored Expiry

The next renewal was scheduled half a TTL after the previous write settled,
and the first one half a TTL after the admission returned, so a slow write
could let a live hold expire before its renewal. Renewals are now scheduled
from the expiry the last write stored.

Expired holds are pruned as one bulk write of per-hold fenced updates, so a
hold that changed after the read is skipped while the rest are removed, and
the admission no longer spends a retry on the whole prune.
2026-09-13 12:53:19 -04:00
Danny Avila
8f13845da5
📿 fix: Inspect Stored File Locators Per Message (#15841)
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: inspect stored file locators per message

* fix: declare traversal diagnostics for isolated declaration builds

* refactor: inject locator traversal reporting from application callers

* fix: propagate traversal diagnostics across protected entry points

* fix: complete middleware reporters and hydration message counts
2026-09-11 16:47:48 -04:00
Danny Avila
65bb64bc68
🛟 fix: Recover CodeAPI File Uploads After Throttling (#15784)
* fix: recover CodeAPI uploads after throttling

* fix: cover eager CodeAPI uploads

* fix: scope CodeAPI upload recovery

* test: clarify upload recovery deadlines

* fix: isolate CodeAPI recovery state

* fix: cancel CodeAPI recovery waits

* test: provide CodeAPI registry in handler fixture

* fix: propagate CodeAPI recovery controls

* fix: bound CodeAPI recovery by run

* fix: preserve skill upload cancellation

* test: update deferred loader signal contract

* fix: preserve recovery cancellation

* fix: cancel recovery source reads

* fix: classify Axios upload cancellation

* fix: preserve lazy provisioning cancellation

* fix: close resource recovery boundaries

* fix: preserve provisioning failures compatibly
2026-09-09 15:48:11 -04:00
easyicetrusty
fdaf4db938
🔢 fix: Normalize PDF Citation Page Numbers (#15731) 2026-09-09 00:45:38 -04:00
Danny Avila
0d85af0a77
🧫 chore: Keep Jest Specs Out of Tool Discovery (#15766)
* fix: Skip test modules during structured tool discovery

* fix: Keep tool discovery validation in TypeScript
2026-09-08 23:58:04 -04:00
Danny Avila
ec15075dc8
🚚 feat: Route Attachments and Provision Tools Lazily (#15763) 2026-09-08 23:28:52 -04:00
Danny Avila
ab6cde0c79
⏳ fix: Separate Temporary and General Chat Retention (#15734)
* fix: separate temporary and general chat retention

* fix: inherit retention when branching messages

* fix: harden retention lifecycle boundaries

* fix: preserve subagent retention context

* fix: trust stored chat retention for uploads

* perf: overlap generated file retention lookup

* fix: derive retention from trusted chat state

* fix: preserve retention across the full turn lifecycle

* test: accept the conversation retention read adapter

* fix: carry retention deadlines through durable job saves

* fix: resolve retention at cached and new chat admission

* fix: resolve direct tool retention before execution

* fix: preserve retention across assistant writes and direct tools
2026-09-08 11:22:54 -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
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
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
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
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
676cd512b0
🫙 fix: Drop Blank Content Blocks From Promptless Sends (#15530)
* 🫙 fix: Drop Blank Content Blocks From Promptless Sends

* fix: Preserve the promptless turn instead of dropping it
2026-09-02 20:15:00 -04:00
Danny Avila
164f146bdf
🛞 feat: Manage Personal Code Environment Lifecycles (#15369)
* feat: add self-service code worker pairing

* fix: enforce code worker principal boundaries

* fix: separate pairing control planes from execution

* fix: preserve principal worker routing

* fix: pin artifact traffic to code workers

* fix: authenticate code worker selection

* test: mock worker-aware artifact headers

* fix: harden self-service code worker routing

* fix: fail closed for principal code pairing

* feat: manage personal code environments

* fix: harden personal code environment lifecycle

* fix: satisfy backend lifecycle types

* fix: harden principal environment lifecycle and quotas

* fix: fence environment lifecycle races

* fix: reconcile code environment stack

* style: format code execution headers

* fix: reconcile code environment lifecycle

* fix: close self-service pairing gaps

* fix: close code environment reconciliation gaps

* fix: close code environment UI review findings

* fix: satisfy code environment type checks

* fix: route code priming to selected worker

* fix: harden code environment lifecycle fences

* fix: type lease renewal interval

* fix: harden environment lifecycle recovery

* fix: close lifecycle recovery races

* fix: type compensated agent timestamps

* fix: fence lifecycle cleanup by tenant and revision

* fix: scope environment revision fencing
2026-09-01 21:10:05 -04:00