mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-16 13:00:55 +00:00
254 commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
b9994b9ead
|
🦣 fix: Honor Trace Policy in Memory Runs (#18006)
Co-authored-by: Lia <lia@librechat.ai> |
||
|
|
bffa50e7a8
|
🚦 fix: Keep the Gateway Message on Classified Rate Limit Errors (#17903)
* fix: Keep the Provider Message on Classified Rate Limit Errors * fix: Honor maxProviderErrorChars for Classified Generation Errors * test: Cover Classified Gateway Errors in the Mock Harness * test: Cover a Zero Provider Detail Limit on Generation Errors * refactor: Resolve Classified Provider Errors in the TypeScript Backend * fix: Redact Provider Details Before Truncating Them |
||
|
|
654ce897e9
|
🗄️ fix: Skip Attachments Deleted by Storage Retention Instead of Failing the Turn (#17910)
* fix: Skip Attachments Deleted by Storage Retention Instead of Failing the Turn A file that storage retention removed from an earlier message made every later turn of the conversation fail, because the encoders rethrew the storage miss and the user has no way to remove an attachment from history. History replay now passes a handler to the encoders, which leave missing files out of the request and report them; the message's file context tells the model which files were deleted and were not read. Current-turn attachments keep the strict error, since the user can remove and re-upload them. Code Interpreter priming names files missing from storage in the tool context and only requires resource recovery for other failures. * refactor: Keep Code Reupload Failure Policy in packages/api Tally priming reupload failures in createCodeReuploadFailures so the decision that a file deleted from storage is named instead of requiring resource recovery lives in TypeScript, and add mock e2e scenarios for a follow-up after an attachment is deleted from storage. * fix: Classify Code Files as Deleted Only at the Storage Read A 404 from the Code API upload was counted as a source file deleted from storage, which skipped resource recovery. openCodeFileSource marks a miss where the stored object is read, and only that error counts as deleted. Move the history replay of attachments with tolerated misses into replayMessageAttachments so BaseClient only calls it. * fix: Name Local Code Files Whose Stream Reports a Missing Object Local storage returns a read stream that raises ENOENT only once read, so openCodeFileSource now holds a stream until its first chunk or error and names a miss there. The missing-files context assignment moves into setMissingCodeFilesContext so both tool loaders only call it. * fix: Close a Held Code File Stream When Priming Is Cancelled openCodeFileSource waits for a source stream's first chunk; when that wait fails, as on cancellation, the caller never receives the stream, so destroy it before rethrowing instead of leaking its file descriptor. |
||
|
|
f03a4686ff
|
🚋 fix: Scope Document Name Traversal to Bedrock Agents (#17627)
* 🚋 fix: Scope Document Name Traversal to Bedrock Agents
* test: Preserve Replay Content Across Token Cache Refreshes
* fix: Include All Bedrock Replay Recipients in Document Naming
* fix: Include Lazy Provider Metadata in Document Naming
* perf: Short-Circuit Reachable Agent Predicates
---------
Co-authored-by: Lia <lia@librechat.ai>
|
||
|
|
3d3edaff01
|
🐘 fix: Preserve Authored Skills Across Approval Resumes (#17630)
* fix: preserve authored skills across approval resumes * fix: complete authored skill resume contracts * fix: keep restored skill identity authoritative across batches * fix: reject replacement skills during authored recovery --------- Co-authored-by: Lia <lia@librechat.ai> |
||
|
|
0f868baf26
|
🍘 fix: Separate Runtime Context From User Input (#17454)
* fix(agents): skip the empty-memory notice for agents that cannot use memory Since #16301 formatMemoryContext('') returns the bare memory instructions sentence, and prepareRuntimeAgent applied it to the primary agent whenever the user had no saved memories. An agent with no memory tools and no automatic memory extraction can neither read nor write memory, so the sentence told the model nothing it could act on, yet it reached the model as per-turn context. The empty-store notice is now added only when the agent has memory tools or automatic extraction is on. Saved memories are still injected as before. * fix(agents): distinguish relocated context from user input * fix(agents): narrow runtime context types --------- Co-authored-by: shars <32410570+Shabonasar@users.noreply.github.com> Co-authored-by: Lia <lia@librechat.ai> |
||
|
|
6189220697
|
🏷️ fix: Resolve endpoints.all Title Settings per Field and Fold Ollama Endpoint Names (#17316)
Some checks failed
Codegraph E2E Votes / vote (shard 10/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 2/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 3/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 4/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 5/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 6/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 7/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 8/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 9/10) (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
Publish `@librechat/client` to NPM / pack (push) Waiting to run
Publish `@librechat/client` to NPM / publish-npm (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
Sync Locize Translations & Create Translation PR / Sync Translation Keys with Locize (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
Sync Locize Translations & Create Translation PR / Create Translation PR on Version Published (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
* 🏷️ fix: Resolve endpoints.all Title Settings per Field and Fold Ollama Endpoint Names Conversation titles picked `endpoints.all` as a whole block, so any `all` block (even one holding only streamRate, headers or activity label keys) hid every per-endpoint titleConvo, titleModel, titleMethod, titleEndpoint and title prompt. `resolveTitleConfig` resolves each field from `all`, then the named endpoint, then the custom endpoint entry, keeping titleEndpoint and titleModel as one choice from the first layer that sets either. Config overrides merged `endpoints.custom` by exact name while the runtime serves names through `normalizeEndpointName`, so an override `ollama` survived beside the YAML `Ollama` and split the endpoint between two baseURLs and keys. The merge key now folds the same way (the YAML spelling is kept), merge-key issues, issue attribution and secret preservation use the same identity, and the effective config serves `modelSpecs.addedEndpoints`, `modelSpecs.list[].preset.endpoint` and `endpoints.agents.allowedProviders` in served names without repeats. A stored document that already names one endpoint in two spellings is combined at merge in document order, so requests keep the host and key of the first item instead of moving to the YAML entry; omit-to-keep secret preservation reads the same combined entry. A new write naming both spellings is rejected as a duplicate. An agent saved as `Ollama` now runs on the served `ollama`: the model catalog lookup (`resolveModelCatalogKey`) falls back to the served name, and `initializeAgent` folds the provider before the allowedProviders check and provider setup. * 🏷️ fix: Report Per-Field endpoints.all Title Resolution in the Admin Config Meta resolveTitleConfig resolves endpoints.all title settings one field at a time, so GET /api/admin/config/meta now reports rules.titleResolution as 'field'. meta.spec ties the reported value to resolveTitleConfig: with endpoints.all = { streamRate: 1 } and openAI.titleModel = 'x', the rule is 'field' exactly when the endpoint's titleModel survives. * 🧪 test: Expect Segments on the Folded duplicate_merge_key Write Issue Admin config write issues carry segments since #17322; the folded Ollama/ollama duplicate test now asserts them. * 🏷️ fix: Match Folded Custom Endpoint Names in Admin Config Change Ops The changes endpoint from dev matched entry keys exactly, while the config merge, merge-key issues and secret preservation fold `Ollama`/`ollama` into one custom endpoint. An upsertEntry `ollama` over a stored `Ollama` copied the stored key, appended a second entry and failed as duplicate_merge_key; removeEntry `ollama` left a stored `Ollama` in place; a rename onto another spelling passed entry_exists; and the librechat.yaml entry check missed `ollama` against the YAML `Ollama`. - data-schemas: `getConfigEntryIdentity` folds a key by its override path; `getConfigEntryMatcher` backs upsertEntry, removeEntry, rename, written-path attribution and the stored-counterpart lookup; issue locations use the same identity. A rename of an entry stored in two spellings moves the one entry the runtime merge combines (`combineFoldedConfigEntries`). - api: the YAML-entry rename guard and the per-batch duplicate check compare entries by the same identity. - Tests: unit coverage for each op across spellings, and handler integration tests against MongoDB for upsert with secret preservation (single and two-spelling documents), removal, entry_exists, inherited_entry and duplicate changes in one batch. |
||
|
|
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. |
||
|
|
8fab21d882
|
🧬 fix: Skip Re-Embedding Legacy File Search Files After Upgrade (#17206)
* fix: Skip Re-Embedding Legacy File Search Files an Agent Already Holds Files embedded before per-namespace tracking carry no embeddedEntities, so lazy provisioning treated them as unembedded and embedded them a second time on the first search after upgrading, duplicating every passage. A legacy record in the agent's own file_search resources was embedded for it, so trust its embedded flag there instead of re-queueing it. * fix: Adopt Legacy Search Embeddings Only for Their Sole Holder Trusting the embedded flag for every legacy File Search file left an agent that inherited one querying a namespace without its vectors. Legacy files held by no other agent now record the active agent as their namespace, a one-time write, and are not embedded again; a file another agent also holds keeps the per-namespace re-embed. Adds an e2e scenario that reshapes an uploaded agent file into the v0.8.7 record and checks that search queries it without a second embed. * test: Cover Legacy Search Files Shared With Another Agent * test: Read the Stored File Id in Legacy Search Scenarios * fix: Pin Legacy Search Adoption to Loaded Records and Wire Every Agent Init file_id is not unique, so adoption now matches each record by its owner and tenant as well, and only rewrites the records priming loaded. The added conversation and client agent initializations receive the dependency too, so their sole-holder legacy files are not embedded a second time. * fix: Adopt Each Legacy Search Record in One Conditional Write * fix: Count a Concurrent Same-Agent Adoption as Adopted * fix: Run Legacy Search Adoption Beside the Liveness Probe and Fall Back on Failure * fix: Keep Committed Legacy Search Adoptions When a Sibling Write Fails * fix: Confirm Legacy Search Embeddings With RAG Before Adopting Them Inferring the embedding agent from current File Search holders could adopt a file for an agent whose namespace held none of its vectors, for example after the agent that embedded it was deleted. Priming now asks RAG for one chunk of each legacy file under the agent's entity_id and records the namespace only on a hit; a miss or an unreachable RAG keeps the file queued for embedding. The data-schemas method no longer scans agents and matches untenanted records as untenanted. The fake RAG server answers these presence checks from the embeds it stores. * fix: Require the Entity's Own Chunks and Keep Confirmed Vectors RAG also returns chunks owned by the requesting user, so a presence check now counts only chunks recorded under the agent itself. Once vectors are confirmed, the turn skips the re-embed even if recording the namespace fails. * fix: Bound the Legacy Search Check and Keep the Fake RAG Query Shape The RAG presence check now times out (fileConfig.legacySearchProbeTimeoutMs, 5s by default) and falls back to embedding, so a stalled RAG cannot hang priming. The fake RAG server records presence checks in their own list and keeps the file_search query records it already returned. * fix: Check Any Unrecorded Namespace Before Embedding a Search File A file another agent embedded first lists only that agent, so the agent whose older vectors went unrecorded skipped the check and embedded a second copy. Priming now asks RAG for every agent File Search file that records no embedding for the active agent, and recording adds the namespace to the ones already there. * fix: Ask RAG for Several Chunks So a User Copy Cannot Hide the Agent's RAG ranks chunks across every owner of a file_id and, once the top one is authorized, returns them all. A copy of an agent file embedded for the requesting user could rank first with k: 1 and hide the agent's own chunks, so the presence check now asks for ten and checks every owner. * fix: Confirm Setup Embeddings in Shared-File Runs and Log Safely The run-file host primes an agent's setup files on its own, so it now receives the RAG presence check and the namespace recorder too; without them a shared-file run could embed a legacy setup file a second time. Failed checks are logged with getSafeErrorMetadata rather than the raw error, which carries the vector store's response body. |
||
|
|
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> |
||
|
|
5fc4371c6a
|
🪦 refactor: Remove Dead Legacy API Modules and Root Tooling (#17114) | ||
|
|
b2bcbf9380
|
🧯 feat: Recover Conversations Whose Attachments Keep Failing (#16965)
* 🧯 feat: Recover Conversations Whose Attachments Keep Failing Once a branch carries a problem attachment, every turn resends it and fails the same way. A failed response whose branch carries files now offers "Retry without files" (re-asks the failed turn with no files as a new version) and, when earlier turns carry files, "Branch without files" (a copy up to the last good answer with every upload and code output left out, with the failed message restored to the composer). File-shaped errors say so in the card. The edit view shows a user message's files as removable chips; "Update & rerun" sends only the kept files and Save is disabled after a removal. Fork is offered on a failed turn and gains a "Leave out files" option, backed by a new `excludeFiles` fork option that drops `files`, `attachments` and the conversation's `files` from the copy. Bedrock rejects a request whose documents share a name, and history resends every earlier document, so repeated names are now numbered before formatting. * 🧯 fix: Cover Steered Files, Hand Off the Whole Failed Turn, Name Replayed Documents Once - Excluding files from a fork also strips attachments steered into a response (`content[].files` on steer parts), which replay like uploads, and the decision lives in `forkFileScope` in packages/api. - The recovery card counts steered attachments as files, and reads the specific code inside a generic `error` envelope, so a rate limit is not offered files as the fix. - "Branch without files" hands the failed turn to the copy's composer the way a message is put back for editing: text through the in-memory handoff, quotes, manual skills and the reasoning override through their compose-time atoms. - Document names are deduplicated over the formatted payload after the steer stamp, so replayed steer documents are numbered too. - Fork stays withheld on a failed response, whose copy would carry the error as an ordinary answer; the card's branch action copies up to the turn before. - Remove-file buttons are natively disabled while the editor is locked. * 🧯 fix: Keep Search Sources, Scope Root Retries, Skip Legacy Rate Limits - A fork without files keeps metadata-only attachments (search sources, file search results) and drops only file-backed ones; the recovery card likewise counts only file-backed attachments as files. - A turn sent at the root takes none of the conversation's file refs: its siblings' uploads (an edited first message, or one retried without its files) no longer come back through the unanchored-continuation fallback. - Rows that carry a legacy LangChain model, key or rate-limit code are not offered files as the fix. * 🧯 fix: Align File Exclusion With Replay's File Shapes, Skip Assistants, Verify the Copy - Shared `messageCarriesFiles` (with `isFileContentPart`, `hasContentPartFiles`, `isFileAttachment`) in data-provider names every shape historical replay reads a file by: uploads, file-backed attachments, attached `files` on any content part, and `image_file`, `file` or direct `file_id` locators. The fork drops all of them and the recovery card detects all of them. - Assistants conversations get no recovery actions: their upstream thread keeps every attachment, and those endpoints offer no fork either. - "Branch without files" checks the returned copy; a server that ignored `excludeFiles` gets an error toast instead of a false recovery. * 🧯 fix: Type Replay's Provider-Native File Locators for the Part Predicates |
||
|
|
3a32d8b0d3
|
🏝️ fix: Let a No-Workspace Turn Carry a Remembered Approval Mode (#16763)
* 🏝️ fix: Let a No-Workspace Turn Carry a Remembered Approval Mode
A conversation set to run without attached workspaces failed every turn with
"The selected code approval mode is not permitted by the current policy" when
the reader had picked Accept edits or Full access for a workspace earlier.
With no attached target, the server validated the requested mode against an
empty policy that only allows ask. A turn with no attached target now accepts
any known mode, resolves it to ask for the run, and keeps the conversation's
stored mode instead of overwriting or unsetting it. Unknown values are still
rejected, and any attached target, including a subagent's, keeps the strict
check.
The composer treated an explicit no-workspace chat as still running on the
agent's default machine, so it kept offering and submitting the remembered
mode. It now offers no attached mode there, and the submit path sends ask
whenever the turn resolves to run without a workspace.
* fix: Leave an Unset Approval Mode Unset on a No-Workspace Turn
A turn without an attached target seeded the conversation's approval mode
from the request when the row stored none. A current client sends the gated
ask there, so the first no-workspace turn of a new chat wrote ask and
replaced the remembered pick the composer would otherwise keep offering.
Such a turn now only carries forward a mode the conversation already stores;
a stored mode still comes only from a turn that validated it against its
attached targets.
* fix: Gate the Approval Menu on the Resolved Workspace Mode and the Saved Conversation
The composer hid attached approval modes only for a chat that recorded a
no-workspace decision, while useCodeWorkspace also resolves one for a saved
chat with no recorded decision and for a draft still choosing. The approval
menu, the queued-turn snapshot, and the submit path now read the mode the
composer resolved, so the control matches what the turn sends.
A no-workspace turn kept the mode of the row admission loaded, but a turn
sent with overrideConvoId is saved under another conversation; the stored
mode is now read only when that row is the conversation being saved.
* fix: Preserve the Saved Conversation's Approval Mode Through a No-Workspace Turn
A no-workspace turn chose what to record from the row admission loaded, but
a turn sent with overrideConvoId is saved under another conversation while
its unsets are still computed from that loaded row, so either the source
row's mode was copied onto the target or the target's own mode was unset.
Such a turn now records no mode and declares codeApprovalMode preserved:
the conversation write skips it when computing unsets, so the stored mode of
whichever conversation the turn is saved under stays as it is, and a chat
that stores none keeps offering the remembered pick. Turns with attached
targets record exactly the mode they validated, as before.
|
||
|
|
301f9ac634
|
🚕 feat: Add Per-Call Subagent Machine Selection (#16757)
* 🧭 feat: Let a Parent Choose Its Subagent's Code Machine Per Call A parent agent can now pass optional `machine` / `workspace` arguments on a subagent call to pick where the child runs, using the host-argument extension point added to @librechat/agents. - Each lazy child declares enums built only from machines it may reach: admitted in the conversation's sealed codeWorkspaces, on its default or allowlist, in the requesting principal's tenant-scoped list, and served by a ready worker. A child the conversation pinned to a machine offers only that machine; a child with no reachable machine declares nothing. - On use, a request-scoped routing session in packages/api re-validates the choice against the current request and live worker status and refuses an invalid one with a typed, model-visible error instead of falling back. A routed child is pinned to the chosen machine at every routing site, overriding parent inheritance. - Omitted arguments keep inherit-by-default routing, extended so a child follows the machine a per-call-routed parent runs on (passing through agents without code). A subagent keeps one machine for the whole request. - A child whose default workspace is unavailable stays guarded unless it has per-call choices; then it stays callable and its description asks the parent to pick a listed machine. - Routed children keep their tool context per execution for tool loading, provisioning and artifact handling. - Paused-approval bindings, the attached-machine policy hook, skill-file priming and tool-output references account for per-call choices. The declarations are gated on the installed SDK exporting SubagentHostArgumentError, so this change is inert until LibreChat depends on an @librechat/agents release that includes it. * 🧭 fix: Reserve Default Routes Early and Route a Routed Subagent's Graph Members - Reserve a subagent's default machine when it is placed, as initializeAgent will resolve it (including parent inheritance), so a concurrent call cannot claim another machine during initialization. - Graph members spawned by a per-call-routed subagent follow its machine when they may, unless they already initialized on their own route this request. * 🧭 fix: Settle Concurrent Inherited Routes and Register Routed Graph Members - Re-read a subagent's inherited route after resolving targets, so two concurrent calls from differently routed parents settle on one machine. - Attribute a workspace-only conflict to the workspace argument. - Register graph members a routed subagent initialized, so each gets the attached-machine policy of the machine it actually runs on. * 🧭 fix: Re-read Inherited Routes After Resolving Subagent Targets - Re-read a subagent's inherited route after the target resolution await, so two concurrent omitted-machine calls from differently routed parents settle on one machine. - Attribute a workspace-only conflict to the workspace argument. * 🧪 test: Prove a Routed Graph Member Takes Its Machine's Policy Through createRun - Register a resolved child's graph members inline in the lazy resolver instead of through an exported generic helper whose test did not typecheck. - Drive the check through createRun's real PreToolUse hook: a member routed to a deny machine flips from its metadata machine's allow to deny once its parent resolves. * 🧭 fix: Hold a Lazily Loaded Graph Member's Default Machine While It Initializes - Pass a graph member's code flags when it initializes on its default route, so the routing session reserves that machine before the asynchronous initialization instead of only after it, and a concurrent call cannot place the same agent on another machine meanwhile. * 🧭 fix: Validate the Approval Mode Against Every Machine a Subagent May Use - Collect each agent's default attached route and each attached machine a parent may route it to per call, and validate the requested approval mode against that set in createRun and both client checks. - A child whose default is unavailable but whose per-call machine permits accept edits no longer fails run creation; full access still requires every such machine to permit it. * 🧭 fix: Admit, Prime, and Cancel Per-Call Subagent Routes Conservatively - Build scheduled pause admission from every attached machine a parent may route an agent to, so a permissive default does not hide a per-call machine that asks. - Walk lazy graph-member metadata when collecting execution routes, so historical skill files are primed for every machine such a member may run on. - Stop placing a canceled call after its target resolution resolves, so it never claims a machine for an execution that will not initialize. * 🧭 fix: Release Unused Route Claims and Scope Per-Call Machines to Their Run - Hold a subagent's route claim per placement: a failed or canceled initialization gives the machine back unless another execution still holds it, and a claim is permanent once a child on it attaches. - Fold an agent's default route into its per-call choice digest, so each agent contributes at most one paused-approval binding target. - Use only an agent's route policies for pause admission when it has them, so a missing default does not make a decided route look asking. - Drop a routable child's provisional attached-machine membership when it resolves off attached machines. - Offer and accept no attached machine per call while run files are shared, since shared children must run on managed code. * 🧭 fix: Give Back a Route When Its Placement Verification Fails - Release a placement's hold when attach finds the child initialized on a different machine than the one it was routed to, so a retry that follows the unavailable-machine guidance may name another machine. * 🧭 fix: Commit a Lazy Child's Routes Only When Its Whole Resolution Succeeds - Keep the routes a lazy child and its routed graph members hold pending through the child's entire resolution (settleExecution), committing them on success and giving them back on failure or cancellation unless another execution still holds them. - Placements outside any call (shared graph members) still commit when they attach. * 🧭 fix: Drop a Failed Lazy Resolution's Config from the Graph Cache - When a lazy child's graph resolution fails or is canceled after its config was cached for graph reuse, remove that entry with its route, so a later graph never reuses a config for a machine the child gave back. * 🧭 fix: Follow a Routed Agent Through Self-Spawned Runs and Scope Routed Member Configs - A call whose parent run was never placed (an allowSelf spawn reuses its routed inputs) inherits the routed claim of its parent agent, which keeps one machine per request. - Never share a graph member initialized for a routed parent's execution through the graph-member cache, so a failed resolution leaves no config behind for a route it gave back. - Race lazy target discovery with the request signal. * 🧭 fix: Pass a Machine On Through Self-Spawned Runs of Agents Without Code - Record the machine each agent without stateful code passes on, and let a call from that agent's unplaced run (an allowSelf spawn) follow it when the agent passed on exactly one machine this request. * 🧭 fix: Keep a Pass-Through Route Only When Its Resolution Succeeds - Record the machine an agent without code passes on with the rest of its call's routing state: kept when the resolution deciding it succeeds, dropped when it fails, so a self-spawn never follows a failed attempt. * 🧭 fix: Settle a Lazy Child's Routing State at the SDK Handoff - Wrap the run's whole lazy resolution, through the inputs handed to the SDK, in the descriptor's settle hook, so a cancel after the host resolver returns still gives the call's routes back. - Roll back the per-agent tool context a pending placement set (restoring the entry it replaced) when its resolution fails, so a retry on another machine seeds its own context. - Drop a failed call's shared config from the graph cache through the same settle hook. * 🧭 fix: Keep Per-Agent Tool Contexts on Live Placements and Queue Target Probes - Track every pending placement that uses an agent's per-agent tool context: a committed one sets it, a failed one hands it to a surviving placement, and only the last failure restores the earlier entry. - Let an unplaced run of an agent (an allowSelf spawn) defer to the routed run of the same agent that encloses it when looking up tool contexts. - Queue live target probes at eight in flight, below the shared status poller's ceiling, so concurrent descriptors never misreport a healthy machine as unavailable. * 🧭 refactor: Load Routed Graph Members Through a packages/api Service - Move the routed graph-member load (shared reuse, skip list, view check, execution identity, failure policy) into createRoutedGraphMemberLoader; the initializer only injects its dependencies. - Thread the request and call signals into target resolution so queued probes are skipped once canceled. - Probe nothing in shared-file runs, where every per-call target is attached and unusable. - Retire pending tool-context ownership when a committed placement installs the per-agent entry. * 🧭 fix: Share a Lazy Child's Config with Later Graphs Only After It Commits - Publish a default-placed lazy child's config to the shared graph cache from the settle hook's commit, so no concurrent graph can borrow a config whose route may still be given back. - Resolve a child's own appearance in its graph to the child config itself. |
||
|
|
3c90cde7d8
|
🔗 feat: use LibreChat prompt groups as agent instructions (#16686)
* 🔗 feat(agents): use LibreChat prompt groups as agent instructions
Agents can link a prompt group revision or Production as their instructions. The link resolves at the start of each turn through a cached resolver. The cache clears on promote and delete. Editors without VIEW on the group see a restricted placeholder.
* fix: remove duplicate logger import from agent initialization tests
* fix: honor prompt management capabilities for linked agent instructions
* test: seed prompt manager capabilities in authorization fixtures
* fix: clear acknowledged linked prompt edits before version restore
* test: adapt merged chain coverage to prompt-aware payload helper
---------
Co-authored-by: Lia <lia@librechat.ai>
|
||
|
|
0e3c9088f6
|
🫰 feat: Configure Tool Approval Modes Per Agent (#16707)
* 🫰 feat: Configure Tool Approval Modes Per Agent
* fix: Fence Remembered Tool Approval Authority
* fix: Unify Tool Approval Execution Invariants
* fix: Revalidate Learned Approval at MCP Invocation
* fix: Preserve One-Time MCP Review at Invocation
* fix: Execute Reviewed Calls on Templated MCP Connections
* fix: Scope Approval Witnesses to Executing Agents
* fix: Retain Approval Bindings for Hook-Rewritten Inputs
* fix: Pin Review Authority and Retire Settled Tool Calls
* fix: Fingerprint Effective MCP Request Headers
* fix: Preserve Routing Around Renewable MCP Token Fragments
* fix: Bind Tool Consent to OAuth Credential Generations
* test: Keep Mobile Approval Save Outside Drawer Escape Race
* fix: Fence OAuth Consent at MCP Transport Retries
* fix: Let Shared Agent Viewers Reset Personal Consent
* fix: Preserve Renewed Consent Across Reset Races
* fix: Resolve Verified Aliases for Personal Tool Reset
* fix: Fence Renewed OAuth Consent and Credential Review
* fix: Require Foreground Execution for Review-Only MCP Calls
* fix: Pin Invocation Ownership and Stable MCP Consent
* fix: Fence Superseded Tool Consent Completion Writes
* fix: Scope Consent Epochs to Effective MCP Authentication
* fix: Scope Approval Admission to Reachable Agent Tools
* fix: Preserve Approval Epochs for Runtime-Detected OAuth
* fix: Address Tool Approval Review Findings
* fix: Preserve Captured Consent When Tool Approval Is Inherited
* fix: Preserve Approval Admission Through Lazy Metadata
* fix: Fence Programmatic Reviews and Unresolved Lazy Approval Keys
* fix: Account for Normalized and Skill-Contributed Lazy Tools
* fix: Scope Lazy Approval to Selected Tool Spellings and Servers
* fix: Honor Disabled MCP Capability During Lazy Approval Admission
* test: Preserve Approval Merge Regressions After Rebase
* fix: Preserve One-Time Review During Non-OAuth Grant Outages
* fix: Retain One-Time Consent Across Resume Recovery
* fix: Preserve Reviewed Consent Through Transport Outages
* fix: Preserve Case-Variant Lazy Approval Hook Admission
---------
Co-authored-by: Lia <lia@librechat.ai>
|
||
|
|
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> |
||
|
|
fb1dd57a9b
|
🔓 feat: Remember Tool Approvals Per Conversation (#16557)
* feat: Remember Tool Approvals Per Conversation Adds an opt-in "Always allow" choice to the tool approval card. When endpoints.agents.toolApproval.allowAlways is true, the server marks eligible paused calls with allow_always; approving with scope "session" stores that exact tool name on the conversation, and later runs in the same conversation fold the stored names into the policy as exact-name allow entries. The server enforces every step: the resume route rejects a session scope the pause did not offer, eligibility is rechecked against the live policy before storing, the list is written only through an owner-scoped bounded method, and generic saves and imports cannot set or clear it. Admin deny and ask rules and programmatic hooks still win, stored names are ignored under dontAsk or when the flag is off, and native code tools stay under the code approval picker. The flag defaults to false, so existing deployments keep prompting. * fix: Share the Effective Approval Policy and Persist Allows After Resume Fences Offering, resume re-check, scheduled admission and createRun now read one policy from buildEffectiveToolApprovalPolicy: endpoint rules healed against MCP alias spellings, then the conversation's remembered tools. A call held by a healed ask rule is no longer offered "Always allow", and a scheduled fire whose known tools are all remembered is no longer rejected as pause capable. The remembered-tools cap and name length cap move to toolApproval.allowAlwaysMaxTools and allowAlwaysMaxToolNameLength (defaults 64 and 256). The card stops offering the choice for new tools once the cap is reached instead of silently approving once. The resume route stores remembered tools only after the schedule and project context fences pass; a storage failure still approves the call once. * fix: Offer Always Allow Only When It Will Hold Offer allow_always only when storing the name would auto-approve the next identical call on the run's own path: every MCP spelling of the tool passes the healed static policy and no programmatic or plugin approval hook can apply to it (the pause payload does not record which hook asked). Remembered names now expand to every alias spelling of the same tool, and a deny or ask on any spelling keeps the tool ineligible. A table-driven spec walks the invariant through the real hook wiring. * fix: Recheck Approval Hooks Before Remembering a Resumed Approval The resume-time eligibility recheck now applies the same programmatic and plugin PreToolUse hook check as marking, with a hook context built from the resume request and the live plugin hook source. A hook registered after the pause turns the choice into a one-time approval: nothing is stored and the resume continues. Document that toolApproval.allowAlways should be enabled only once every replica supports it, since older replicas ignore the choice. * fix: Judge Always Allow Offers Against the Run's Live Aliases and Active Cap * fix: Charge Only New Tool Names Against the Remembered Approval Cap * fix: Recheck Remembered Approvals Against the Paused Run's Aliases * chore: Sort Imports in Agent Run After Rebase |
||
|
|
de7755b4ca
|
🕊️ fix: Keep Attachment History From Locking Conversations (#16690)
* 🕊️ fix: Keep Attachment History From Locking Conversations
* test: Correct Attachment Regression Fixtures
* fix: Preserve Current Attachment Admission During Steering
* fix: Release Historical Attachment Counts After Failed Steering
---------
Co-authored-by: Lia <lia@librechat.ai>
|
||
|
|
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> |
||
|
|
e1e1d1b19d |
🎒 feat: Carry Project Context Across Conversations (#15684)
* 🎒 feat: Carry Project Context Across Conversations
* fix: fail a project attach whose upload hold cannot be released and keep file deletes independent of project cleanup
- Attaching a project file now fails, with nothing attached, when the file's
temporary upload hold cannot be released, instead of attaching a file that
can still expire.
- A failed project cleanup after a file delete is logged rather than failing a
delete that already happened, and a user-wide delete clears that user's
project references without reading every file first.
- Both resize handles share the orientation-aware grip, so a primary handle in
a vertical group renders a rotated grip like the alternate one.
* fix: treat an empty tenant id as no tenant in the project file picker
* fix: attach nothing when a project file is deleted while the attach is in flight
* fix: localize project file association failures instead of showing server text
* test: expect a localized reason for a rejected project file association
* fix: scope project file listing to the caller's tenant and name the file limit when attaching an existing file
- Listing a project's attached files now returns not found when the project
belongs to another tenant, matching the available-file listing and the
chat context resolver.
- Choosing an existing file for a full project now names the project file
limit instead of the generic attach error, like the upload path.
* fix: treat an empty tenant id as no tenant in every project tenant check
A caller whose tenant id is an empty string was refused its own tenantless
project when listing attached or available files, because the handlers
compared '' with null. The project handlers and the chat context resolver now
share one comparison that treats an empty tenant id as no tenant, the rule the
project file queries already follow.
* test: wait for the workspace layout swap and the mobile drawer before acting in the long-metadata spec
The desktop title was measured while the phone layout could still be the one
rendered, and the sidebar row menu was opened before the mobile drawer
committed its open state, which closes a menu opened ahead of it. The spec
now waits for the workspace's phone-only sidebar toggle to leave and for the
drawer to drop inert, the same drawer signal the agents helpers use.
* fix: keep the agent context fingerprint of a turn outside any project unchanged
Every turn now passes a project context key into the agent context
fingerprint, and a turn outside any project passed the no-project sentinel,
which changed the digest of every existing no-project checkpoint. An agent
event conversation written before this change then cold-started and reloaded
its history on its next event. The fingerprint now hashes the no-project key
as absent, so those checkpoints keep matching.
* test: load the long-metadata spec at phone width before driving the mobile drawer
The spec crossed back from desktop to phone width without a reload, which
leaves the drawer on the desktop toggle path whose delayed focus handoff to
the close button dismissed the row menu roughly 200ms after it opened. The
spec now reloads at phone width, as a phone arrives, and waits for the
drawer's own focus handoff before opening the menu.
(cherry picked from commit
|
||
|
|
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
|
||
|
|
3c08a7dd04
|
📦 chore: bump @librechat/agents SDK to v3.9.6 (#16354)
* 📦 chore: bump `@librechat/agents` SDK to v3.9.5 * 🐛 fix: Preserve Fading Tier State With Agents SDK v3.9.5 * 📦 chore: bump `@librechat/agents` SDK to v3.9.6 --------- Co-authored-by: Lia <lia@librechat.ai> |
||
|
|
e6929f5ca0
|
🪴 fix: Surface Persistent Memory Before First Save (#16301)
* fix: Surface Persistent Memory Before First Save * fix: Distinguish Unreadable Memory From Empty Memory --------- Co-authored-by: Lia <lia@librechat.ai> |
||
|
|
5f4a07f40b
|
⚡ perf: Exclude Agent Version History From Default getAgent Reads (#16070)
* ⚡ perf: Exclude Agent Version History From Default `getAgent` Reads
getAgent now defaults its projection to { versions: 0 }; loadAgent/loadAddedAgent
and canAccessAgentFromBody use getAgentWithVersionCount so the version count stays
exact without transferring the unbounded versions array on every chat request.
Callers that need history (v1 update/revert handlers) request it explicitly.
* fix: tighten agent version projection types
* fix: type projected agent version counts
* fix: type default agent projection
* style: format agent projection overload
* fix: expose projected agent return type
|
||
|
|
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. |
||
|
|
9633edcb88
|
🗣️ fix: Keep Provider Error Text on Unclassified Agent Failures (#16034)
* 🗣️ fix: Keep Provider Error Text on Unclassified Agent Failures
An upstream failure LangChain does not classify discarded the provider's own
message and answered with the generic upstream sentence plus a status, so a
gateway or privacy-proxy rejection lost the only account of what happened.
The provider text now rides along in the persisted payload as `message`,
withheld only where a content policy inspects the traffic — the same condition
`getUserFacingProviderError` and `getUserFacingRequestError` already decide by.
* fix: Harden Provider Error Detail Retention
---------
Co-authored-by: Danny Avila <danny@librechat.ai>
|
||
|
|
ed95a9b802
|
🍯 fix: Stop Approval Pauses From Unsealing Code Environments (#15963)
* fix: Preserve Code Environments Across Approval Pauses 🧷 * test: Match Agent Request Conversation Identity 🪪 |
||
|
|
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 🧲 |
||
|
|
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> |
||
|
|
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> |
||
|
|
4216de41c2
|
🚛 fix: Move Sealed Chats to New Code Environments (#15902)
* 🧭 fix: Let a Sealed Chat Follow Its Agent to a New Machine
A conversation's code-environment decision is sealed on its first turn, but the
environment an agent uses stays editable. Pointing an agent at a different
attached machine left every chat sealed to the old one with no valid move: the
client showed an unusable workspace chooser, and any other selection was
rejected by the server as locked. Forking copied the stale seal.
The owner can now move such a chat explicitly. The composer names the machine
the chat used and the one its agent uses now, and moving it goes through an
owner-scoped endpoint that compare-and-swaps the persisted decision after
validating the new workspace against the live worker. A move never switches the
workspace of an environment the decision already covers, never upgrades a chat
that continues without an attached environment, and is refused while a
generation is in flight.
A saved chat also no longer auto-selects a sole workspace for an environment its
decision never covered, which submitted a selection the server always rejected.
* fix: Hold Moves Through Terminal Saves and Move Every Target at Once
A terminal claim marks a generation complete before its response save lands,
and that save still writes the decision the run started with, so a move is now
refused until terminalPersistencePending clears.
The API advertises codeEnvironmentMoveVersion, and the client offers a move only
when it is present, so a new client never exposes an endpoint an older API lacks.
The move menu picks one workspace per new environment, with a sole workspace
preselected, and a single confirm sends the complete target set in one request,
so a partial move can no longer leave a half-migrated decision. A new machine
that advertises no workspace shows its unavailable state instead of an empty
section, and the confirm stays disabled.
* fix: Keep Runs From Rewriting Moved Decisions and Gate Moves by Policy
Every agent turn used to persist the decision it started with, so a run from any
ingress that settled after a move could write the old decision back: the chat
controller reads the conversation before its generation job exists, and
Responses API runs never enroll one. Runs now persist a decision only for a
conversation that does not store one yet, and a legacy row records only the mode
it inferred, so no admission or persistence order can revert a move.
Moves are now an operator setting, statefulCodeSessions.conversationMoves.enabled,
off by default. The API advertises codeEnvironmentMoveVersion and accepts moves
only where the effective policy enables them.
A saved chat carrying attached selections no longer auto-selects a sole workspace
even when selection-less decisions are not advertised, because the server seals
those selections either way.
* fix: Fence Moves Across Remote Runs and Let Moves Drop Unused Machines
A Responses API run is keyed by its response id, so the conversation stream
alone could not show it still working on a chat. A move is now refused while any
generation that can still act for the conversation exists, using the same
conversation-scoped enumeration conversation deletion drains.
A move now validates every workspace it persists, not only the added ones, so a
successful move never hands back a decision whose kept workspace is gone.
A chat sealed to machines its agents no longer all use could not be sent or
moved: the client trimmed the unused selection and the server rejected the
trimmed set as locked. A saved chat now treats that seal as unresolvable, offers
a move that drops the unused machine, and the server accepts drop-only moves.
* fix: Own the Decision Fallback in TypeScript and Settle Move Caches
The fields a run may persist when it never resolved a decision were chosen by a
branch in AgentClient; resolvePersistableCodeEnvironmentDecision now owns that
fallback too, under the same never-overwrite rule, and the CJS method only wires
the request into it.
Workspace choices made in the move menu belong to the chat they were made in, so
another relocatable chat targeting the same machine starts undecided.
A successful move cancels conversation, pinned, and list reads already in flight
before writing the moved decision, so a response from before the move cannot
restore the replaced decision in the cache.
|
||
|
|
e95e696d70
|
🧾 fix: Count the Tool Results a Tool-Limit Stop Retains (#15893)
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
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
* 🧾 fix: Count the Tool Results a Tool-Limit Stop Retains Context snapshots reach the client only through the SDK's pre-invoke `ON_CONTEXT_USAGE`, so the results of the tools a call requests are never in that call's snapshot — the next call's snapshot carries them as kept-message context. A run that stops at the tool-call limit makes no next call, so the tool result it retains lives in the response and in no snapshot: the gauge reported `(budget − remaining) + completedOutputTokens` and left the retained result out of used tokens and out of the tool-call share until the following turn. The save path now counts those results with the run's own tokenizer and persists them as `retainedToolTokens`, a second post-snapshot delta alongside `completedOutputTokens` rather than a number folded into the provider-reconciled `messageTokens`. `resolveRetainedToolTokens` owns the rule that only a tool-limit stop retains anything, and the snapshot handler records where its content ended so the count starts at the right boundary. Counting had to avoid `Tokenizer.getTokenCount`, whose fallbacks would have put a guess inside exact accounting: above 4 KiB it returns byte length, several times the real count on ordinary text, and it estimates from character length while an encoding loads. `countExactTokens` tokenizes in bounded slices cut on code-point boundaries and returns nothing at all when the encoding is cold, so an uncountable result withdraws the figure instead of inflating it. The client adds the field to used tokens, subtracts it from the runway headroom and widens the tool-call share, in the live snapshot after finalization and in the persisted blob after a reload. * 🧹 style: Wrap the Retained-Counter Assertion as Prettier Requires * 🧮 fix: Address the Review of the Retained-Tool Count Three findings from the first round, each a real defect in how the figure was produced rather than a style point. The boundary was a content index recorded mid-run, but completion reshapes the array — skill cards are unshifted onto the front and `hide_sequential_outputs` replaces it with a filtered one — so a saved index no longer means the same position. The snapshot now records the tool-call ids it already accounts for, and the save path counts the results of the calls missing from that set: ids survive every reshape, and a filtered-away call is correctly left out. Counting in 4 KiB slices was not exact either: a BPE merge spanning a seam is charged twice, measured at ~1 token per slice, and the field exists precisely to be an exact addend. `countExactTokens` now tokenizes the whole input — ~60 ms/MB, paid once at the end of a stopped turn — and refuses content past 8 MiB rather than estimating it. The counter takes its exact-count function instead of reaching for the tokenizer singleton, so `resolveRetainedToolTokens` owns the default (the run's own encoding) and a caller or test can supply another. That also removes the mock of global state from the specs. `compactionReclaim` now includes the retained result in the total it subtracts the kept exchange from. `latestExchangeTokens` already counts that result on the other side, so leaving it out subtracted content the total never carried and understated the savings — to zero on a large final result. * 🧯 fix: Bound One Turn's Retained-Result Tokenization The tokenizer refuses a single result past 8 MiB, but a final call that requested several tools in parallel would pay that bound once per result. The counter now holds a budget for the whole turn and withdraws its figure past it, so the save path cannot be made to tokenize an unbounded pile of output. * 🎚️ feat: Configure the Retained-Result Tokenization Budget The exact count the gauge adds costs ~60 ms/MB of retained tool output, and the ceiling on that work was hard-coded in two places. It is now one lever: `endpoints.agents.maxRetainedToolCountChars`, defaulting to the 8 MiB that reproduces today's behavior, shared by the schema and the save path through `DEFAULT_MAX_RETAINED_TOOL_COUNT_CHARS`. Deployments whose tools legitimately return more can raise it; slower hardware can lower it, or set `0` to withhold the figure entirely. `Tokenizer.countExactTokens` no longer carries a bound of its own — the caller owns the budget — and `resolveRetainedToolTokens` passes the configured value to the counter, which spends it across all of a final call's parallel results. --------- Co-authored-by: Danny Avila <danny@librechat.ai> |
||
|
|
91e00bbe6e
|
🧷 fix: Mark a Failed Compaction So Its Rerun Controls Stay Withheld (#15883)
* 🧷 fix: Mark a Failed Compaction So Its Rerun Controls Stay Withheld A manual compaction that failed with an error part carried no marker: the server stamped `initiatedBy: 'user'` only on a summary that produced text and returned early once an error part existed. On a branch ending in a user message, the resulting turn had no marker and a user parent, so the hover row kept Edit, Regenerate and Continue — and using one answered that user message instead of retrying the compaction. `markCompactionOutcome` now marks whichever part carries the outcome, summary or error, and `isUserInitiatedCompaction` reads both. The marking moved from `api/server/controllers/agents/client.js` into `packages/api`, where the behavior belongs; the controller keeps the call. * 🏷️ refactor: Type the compaction spec helpers with SummaryContentPart * 🧯 fix: Record a Marked Failure When a Compaction Produces Nothing A compaction run that produced neither a summary nor an error part threw COMPACTION_FAILED out of `sendCompletion`. The turn was then saved by `saveErrorTurn`, which writes only top-level `text`/`error` and no content, so the row carried no compaction marker: on a user leaf the hover row kept Regenerate, and using it answered that user message. `markCompactionOutcome` now records the typed failure as a marked error content part instead, so the turn streams and persists like every other failed compaction. A cancelled run still fails as a typed error, leaving the abort path to own the turn. `saveErrorTurn` marks the compaction rows it still writes for failures that are rethrown rather than recorded as content. Verified end to end by two new mock scenarios that run Compact context against a summarizer returning nothing, live and after a reload. * 🧪 test: Run the Empty-Compaction Scenarios Against a Real Compaction * 🧱 refactor: Resolve Failed-Turn Compaction Content in packages/api `saveErrorTurn` decided in CJS whether a failed row carries compaction identity. The decision moves to `resolveFailedTurnContent` in `packages/api`, which returns the content fields a failed turn is persisted with — the marked failure for a compaction, nothing for any other turn — and `request.js` spreads the result. * 🧹 fix: Keep an Unusable Summary Out of a Failed Compaction's Turn History loading accepts any nonempty summary as the conversation's checkpoint (`BaseClient.findSummaryContentBlock` ignores `failed`), so a compaction that streamed partial text before failing would have persisted that truncated text beside its recorded failure and replaced the history it failed to summarize. The fallback now drops the unusable summary, leaving the typed failure as the turn's whole outcome. The empty-summarizer scenarios switch the shared fixture summarizer to blank output, so the reset moves to `afterEach` and runs even when the helper throws before its caller's `finally`. |
||
|
|
f6335cb9d7
|
💰 fix: Bill Stopped Agent Turns From Provider Usage (#15889)
* 💰 fix: Record Token Usage for Stopped Agent Turns The agents Stop route only signals the abort; the run's cleanup skipped recordCollectedUsage on an aborted signal, trusting an abort middleware that is mounted only on the assistants abort routes. Stopped and error-aborted agent turns therefore wrote no transactions and never debited the balance. The run now records its collected usage on every exit, labelling a stopped turn's transactions with context 'abort'. The owner of the run charges, so a cross-replica Stop is still billed exactly once. * 💰 fix: Make the Run the Single Charger for a Stopped Turn The legacy assistants-mounted abort route still billed a non-assistants job — provider usage via spendCollectedUsage, or a text-count fallback — on top of what the run records on exit, and its array clear ran only after its own awaited write, so the two could race even on one replica. The route now only stops and persists; the run records its usage once, labelled through resolveRunUsageContext in packages/api. * 💰 fix: Keep the Text-Count Fallback From Re-Billing Recorded Usage BaseClient falls back to text-count billing whenever the recorded usage has no positive output count, so a stopped call that reported input tokens and no output was debited by recordCollectedUsage and then charged its estimated prompt again. AgentClient.recordTokenUsage now returns early once provider usage was recorded (hasRecordedProviderUsage in packages/api); an all-zero report still falls through to the estimate. * 💰 refactor: Lift Fallback Token Billing Into packages/api recordFallbackTokenUsage owns the whole fallback operation — the recorded-usage guard, the estimate spend, the reasoning row and the error boundary — taking spendTokens as an injected dependency. AgentClient.recordTokenUsage only builds the transaction metadata from the client and calls it. * 💰 fix: Label Fallback Billing From the Run's Stop State BaseClient invokes the estimate fallback without a context, so the sole row for an initial turn stopped before any provider usage was labelled 'message'. recordTokenUsage now defaults the context from the run's own abort signal. * 💰 refactor: Default the Fallback Billing Label in packages/api recordFallbackTokenUsage takes the run's raw abort state and derives the transaction label itself; AgentClient.recordTokenUsage passes the signal through and no longer chooses the context. * 💰 fix: Guard Fallback Billing on the Collected Primary Entries The stream aggregate recordCollectedUsage returns takes its input from the first primary call only, so a later cancelled call that reported input alone was billed yet invisible to the fallback guard, which then charged the estimated prompt again. recordFallbackTokenUsage now also consults the collected entries themselves (hasRecordedPrimaryUsage), ignoring summarization, subagent and sequential usage; AgentClient passes its collected entries through. |
||
|
|
74fa60cee1
|
🔎 fix: Enforce WEB_SEARCH Role Permission on Agents (#15875)
* 🔎 fix: Enforce WEB_SEARCH Role Permission on Agents Squash of #15822 onto dev, preserving authorship: - 🔎 fix: Enforce WEB_SEARCH Role Permission on Agents - 🧪 test: Cover the Runtime Tool Loader's Web Search Gate - 🔒 fix: Gate Web Search on the OpenAI-Compatible Embedder Surface - 🩹 fix: Authorize Web Search by the Execution Context's User - 📝 docs: Note the Grant Memo's One-Subject-Per-Request Assumption - 🧹 fix: Deny Web Search Before an Endpoint Default Can Grant It - 🙈 fix: Withhold the Web Search Model Parameter From a Denied Role - 🧱 fix: Strip Provider-Native Search an Endpoint Re-Enables After Denial - 🔌 fix: Close the OpenRouter Plugin Path and Stop Pruning Hidden Parameters * 🧭 fix: Gate Provider-Native Web Search on the Built Config The web search role gate ran before the provider builder and only when the agent's stored `web_search` was not `false`, so an endpoint's `addParams` re-enabled native search for a denied role, and every OpenAI-compatible and Responses request read the role whether or not search was in play. The gate now reads the builder's output: when it carries a native search tool or OpenRouter's `web` plugin, the `WEB_SEARCH` grant is resolved and the search stripped on denial. The routes that reach `initializeAgent` with `runtime` and no `req` pass a lazy `resolveWebSearchGrant` that joins their request-memoized grants, forwarded through agent discovery to handoffs and subagents. The embedder surface wires it whenever `getRoleByName` is supplied, independent of `appConfig`. --------- Co-authored-by: TomasPalsson <tomas2212042710@gmail.com> |
||
|
|
1163045cef
|
🖋️ feat: Seal Code Environment Choices Per Conversation (#15868)
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
* feat: lock code environments per conversation * style: Sort code environment imports * fix: Harden code environment decisions * fix: Preserve code environment rollout compatibility * fix: Harden code environment boundaries * refactor: Centralize code environment policy * test: Restore partial disconnect policy mock * fix: Close code environment edge paths * fix: Preserve implicit stateful code routes * fix: Stabilize implicit code routing * test: Align remote workspace contract * chore: Sort code route import |
||
|
|
19eb24921e
|
🔠 feat: Render Safe Upstream Model Errors (#15837)
* ✨ feat: Surface Upstream Model Errors * 🧪 test: Cover Upstream Error Rendering * 🛡️ fix: Harden Upstream Error Fallbacks * 🛡️ fix: Defer Upstream Error Fallbacks |
||
|
|
7a83b8f5d2
|
📟 feat: Record Safe Upstream Model Failures (#15800)
* ✨ feat: Add Upstream Model Error Observability * ♻️ refactor: Move Terminal Error Policy to TypeScript * 🛡️ fix: Preserve Agent Cancellation Semantics |
||
|
|
f25242df98
|
🦘 feat: Share Run-Scoped Files With Subagents (#15848)
* feat: add run-scoped file sharing for subagents Delegate current-message files through authorized execution catalogs and publish selected immutable code-output versions through the existing file pipeline. Requires the companion agents SDK context adapter before the dependency can be released and pinned. * fix: preserve child tool artifacts and verify file-sharing lifecycle Keep citations and other non-sandbox artifacts on their existing delivery path while retaining private code outputs and inspected images until publication. Cover native and text delivery, nested and sibling authorization, concurrent runs, cancellation cleanup, and checkpoint recovery through the browser harness. * test: align file-sharing fixtures and integration cleanup * test: repair LibreOffice conversion fixtures * test: verify deployment skill bytes across checkout formats * fix: align subagent file budgets and refresh boundaries * chore: update agents SDK to 3.8.6 * refactor: move code output processing into API workspace * fix: enforce shared file budgets for parents and teams * fix: declare the shared file encoder interface |
||
|
|
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 |
||
|
|
03a42d6c7e
|
🎒 fix: Carry Subagent Identity Past Streaming (#15795)
* fix: resolve saved subagent display identity * fix: persist explicit subagent execution identity |
||
|
|
a8087ce454
|
🏕️ feat: Select Attached Code Workspaces (#15768)
* feat: Select Attached Code Workspaces * fix: Preserve Workspace Boundaries Across Agent Graphs * fix: Validate Lazy Agent Workspace Bindings Before Persistence * fix: Include Handoff Environments in Workspace Selection * fix: Close Workspace Admission and Remote Ingress Gaps * fix: Preserve Workspace Selection In Chat Runtime Envelopes * fix: Authorize Deployment Workspace Status And Match Readiness * fix: Preserve Ephemeral Chats And Pin Runtime Worker Identity * test: Complete Deployment Pairing Fixtures |
||
|
|
ba12eaa418
|
⛔ fix: Bind Tool Approvals to Generation Scope (#15724)
* fix: bind tool approvals to generation scope * fix: gate generation scope on replay lifecycle support * chore: add npmrc for npm v12 support, fix xlsx tarball dl * chore: bump agents sdk to v3.8.3 * fix: require scoped approval replay support |
||
|
|
cdc3339a78
|
🪬 fix: Fence Agent Checkpoint Ownership and Cleanup Recovery (#15680)
* 🔒 fix: Isolate Checkpoint Cleanup by Generation Ownership * 🔒 fix: Harden Checkpoint Cleanup Ownership * 🔒 fix: Retain Checkpoint Cleanup Evidence * 🔒 fix: Persist checkpoint cleanup receipts * 🔒 fix: Bound checkpoint cleanup receipt lifecycle * fix: Bind checkpoint cleanup to durable ownership and deletion intent * fix: Bind event actor checkpoint storage to authenticated owners * fix: Resolve exact actor checkpoint ownership before lifecycle cleanup * fix: Preserve actor storage compatibility with durable ownership and prune work * fix: Defer checkpoint erasure until conversation deletion commits * fix: Reclaim orphan actor ownership and batch deletion lookups * fix: bind actor checkpoint ownership to payload rows * fix: isolate actor readers and await account persistence * fix: gate owned suspensions and drain complete account state * fix: unify checkpoint deletion lifecycle and storage authority * fix: Replay checkpoint deletion from durable owner state * fix: retain checkpoint cleanup identity before topology loss * fix: complete checkpoint catalog capture and retirement lifecycle |
||
|
|
6f05678bfc
|
🧐 feat: Restore Interactive Tool Approval Review (#15717)
* 🧐 feat: Review Pending Tool Actions in the Composer (#15714) * feat: add interactive approval review to the composer * fix: Harden interactive approval boundaries * fix: Bound every approval display label * test: exercise composer approval review in BYOM acceptance * fix: reveal all directional approval controls * fix: canonicalize code approval targets across replicas * style: sort resumable approval test imports * test: Exercise Coexisting Approval Surfaces * Revert "🧐 feat: Review Pending Tool Actions in the Composer (#15714)" This reverts commit 5f79ded9553405b697e837e1976a70accbfc3fc3. * Reapply "🧐 feat: Review Pending Tool Actions in the Composer (#15714)" This reverts commit 52c7d9c7453da0168338bcf79494927f561a92a0. * chore: bump agents sdk to v3.8.2 |
||
|
|
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 |
||
|
|
4b3a6eaf0e
|
🪧 feat: Surface Conversation Code Approval Modes (#15703)
* feat: Add conversation code approval modes * refactor: Reuse shared code approval types * fix: Scope approval selector to stateful agents * fix: harden code approval state propagation * fix: fail closed during approval discovery * test: cover approval mode acceptance * test: use visible approval mode label * test: drive approval menu by keyboard * test: expose accept edits in BYOM acceptance * fix: read approval mode atomically on send * fix: align code modes with endpoint policy * fix: initialize code limiters at startup |
||
|
|
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
|
||
|
|
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 `
|