Commit graph

1747 commits

Author SHA1 Message Date
Danny Avila
34938ebcba
📮 fix: Count Undelivered Background Results as Outstanding (#16343)
* 📮 fix: Count Undelivered Background Results as Outstanding

* fix: Reconcile delivered tasks, discard exactly, and count pending subagent results

* fix: Settle manually claimed remote deliveries and keep pending controls while wake-ups drain

* fix: Report dead-lettered deliveries as failed and read subagent wake-ups from the durable store

* fix: List restored dead letters and retire deliveries on local durable claims
2026-09-24 23:16:17 -04:00
Danny Avila
c6282fa888
🧷 fix: Wait for Long Dispatch Turns Before Giving Up Background Code Results (#16345)
* 🐢 fix: Back Off Waiting Completion Wake-ups and Deliver Them When Ready

* fix: Signal every readiness path and make the completion wait cap configurable

* 🧷 fix: Wait for Long Dispatch Turns Before Giving Up Background Code Results

* fix: Mark held completion deliveries instead of pipeline expedite, and announce store-won approval expiry

* fix: Keep code tasks protected and wait without a fixed cutoff

* fix: Scope settle expedites to the resumed conversation and close the remaining signal gaps

* style: Format the settlement waiter

* fix: Announce a won approval expiry once and release subagent wake-up registrations

* fix: Outlast terminal persistence before giving up an unanchored code result

* fix: Anchor code results the moment their dispatch turn settles

* fix: Scope harvest epoch pinning to the owning stream

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-24 23:15:50 -04:00
lia-by-librechat[bot]
dd21e7fb6d
📣 fix: Surface MCP Credential Failures During Tool Loading (#16323)
* 📣 fix: Surface MCP Credential Failures During Tool Loading

* fix: address MCP credential propagation review

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-24 22:53:31 -04:00
lia-by-librechat[bot]
5862b3b7d1
🛍️ fix: Discover Managed Agents in Marketplace Search (#16324)
* 🛍️ fix: Discover Managed Agents in Marketplace Search

* 🛍️ fix: Reject Invalid Agent List Permissions Before Bypass

* 🛍️ fix: Scope Managed Agent Discovery and Avatar Refresh

* 🛍️ fix: Bound Managed Avatar Cache to Signed URL Lifetime

* 🛍️ fix: Invalidate Tenant Avatar Cache After Upload

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-24 22:48:56 -04:00
Danny Avila
7238be3e5e
⚡ fix: Deliver Waiting Completion Wake-ups the Moment They Are Ready (#16339)
* 🐢 fix: Back Off Waiting Completion Wake-ups and Deliver Them When Ready

* fix: Signal every readiness path and make the completion wait cap configurable

* fix: Mark held completion deliveries instead of pipeline expedite, and announce store-won approval expiry

* fix: Scope settle expedites to the resumed conversation and close the remaining signal gaps

* fix: Announce a won approval expiry once and release subagent wake-up registrations

* 🧪 ci: Count System Instructions in Mock Model Usage (#16350)

The e2e fake model reported input tokens for the chat messages alone, because the SDK hands a test override model the pruned messages without the systemRunnable pipe. Once #16301 gave every memory-enabled chat a system prompt, the calibrated context snapshot put used tokens below the instructions and the gauge dropped its Messages row. Count input over the complete prompt, as a real provider bills it.

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-24 22:28:28 -04:00
Danny Avila
3788fe05d9
🐢 fix: Back Off Waiting Completion Wake-ups and Keep Their Trace Out of Requests (#16349) 2026-09-24 21:36:10 -04:00
lia-by-librechat[bot]
ffd3d1e139
🔕 perf: Back Off Idle Durable Agent Recovery Polls (#16303)
* 🔕 perf: Back Off Idle Durable Agent Recovery Polls

* 🎛️ style: Format Queued-Turn Recovery Test

* fix: Preserve Durable Recovery Wakeups and Discovery Invariants

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-24 09:36:51 -04:00
lia-by-librechat[bot]
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>
2026-09-24 08:43:36 -04:00
lia-by-librechat[bot]
02492bdb6c
🏚️ feat: Recover Coding Chats With Missing Workspaces (#16273)
* 🏚️ feat: Recover Coding Chats With Missing Workspaces

* fix: Revalidate Workspace Recovery and Preserve V1 Usage

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-24 06:03:23 -04:00
Danny Avila
f13b0eaef4
🚚 chore: Point Repository and Image References at LibreChat-AI (#16005)
Some checks failed
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Codegraph E2E Votes / vote (full suite) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Client build recovery regression (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
Docker Dev Images Build / publish (push) Waiting to run
Sync Helm Chart Tags / Ignore non-main push (push) Waiting to run
Sync Helm Chart Tags / Sync chart tags (push) Waiting to run
Publish `@librechat/client` to NPM / pack (push) Has been cancelled
Publish `librechat-data-provider` to NPM / pack (push) Has been cancelled
Publish `@librechat/data-schemas` to NPM / pack (push) Has been cancelled
Publish `@librechat/client` to NPM / publish-npm (push) Has been cancelled
Publish `librechat-data-provider` to NPM / publish-npm (push) Has been cancelled
Publish `@librechat/data-schemas` to NPM / publish-npm (push) Has been cancelled
Update package repository and bugs URLs, GitHub links in docs, templates and comments, and image references (compose files, deployed-update, Helm values and renovate hints) from danny-avila to LibreChat-AI / librechat-ai. Covers the rag-api repository and its images, which moved to the organization. Sponsor links and the sealed star-history chart are unchanged.
2026-09-23 23:08:36 -04:00
lia-by-librechat[bot]
89effb9793
🛝 refactor: Route Packaged Chat Completion Frames Through a Writer (#16267)
* 🛝 refactor: Route Packaged Chat Completion Frames Through a Writer

* style: Match Chat Completion Contract Test Import Order

* fix: Avoid ES2022 Array Methods in Protocol Contract Test

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-24 01:23:42 +00:00
Alexey Korepanov
cb52198b44
✨ feat: Client-Executed Function Tools for the Responses API (#16078)
* Add client side tools

* 🚦 fix: Ask the Model to Call Caller-Executed Tools Alone

* Add client tool continuation replay tests

* Fix clientTools docstring

* fix: return only tools that have been actually applied

* 🔁 fix: Continue a Caller-Executed Tool Exchange Across Requests

* fix: handle null values for tool descriptions and parameters in client tools

* 🧩 fix: Keep the Arguments of Every Tool Call in a Streamed Message

* Fix PR comments

* fix: Preserve client tool handoff across SDK event ordering

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-22 23:09:07 -04:00
lia-by-librechat[bot]
ef89fbd5b3
🎽 fix: Give Each Streamed Tool Call a Stable Outward Index (#16209)
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: give each streamed tool call a stable outward index

* fix: scope tool-call fragments and preserve completed answers

* fix: finalize agent tool-call snapshots without duplicating deltas

* fix: assemble complete tool identities before response publication

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-22 11:00:01 -04:00
lia-by-librechat[bot]
1e2142e52a
🚥 fix: Preserve Insights With Guarded ACL Role Updates (#16170)
* fix: preserve Insights with guarded ACL role updates

* test: settle ACL index builds before opening the transaction

* fix: replace ACL mask partitions with single-operator bit writes

* style: drop the now-unused RoleBits import

* fix: make ACL role replacement one atomic guarded write

* fix: export the permission write retry ceiling

* fix: retry ACL mutations per document and preserve atomic permissions

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-21 23:40:52 -04:00
lia-by-librechat[bot]
e4024052e0
✒️ fix: Persist a Generated Title Before the Turn Ends (#16137)
* ✒️ fix: Persist a Generated Title Before the Turn Ends

* 🧷 fix: Keep the Early Title Save From Rewriting Message References

* 🩹 fix: Carry the Recovered User Message Reference

* 🧵 fix: Reference Every Recovered Message Row

* 🪢 fix: Reference Paused and Resumed Response Rows

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-21 06:40:38 -04:00
Marco Beretta
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
2026-09-20 19:27:21 -04:00
Danny Avila
1e0076376c
🪢 fix: Bind Preserved MCP API Keys to Server Configuration (#16136)
* fix: bind preserved MCP API keys to server configuration

* fix: surface MCP API key rebinding errors

* test: use typed MCP OAuth re-entry error
2026-09-20 12:33:20 -04:00
lia-by-librechat[bot]
16a7e116ef
💌 feat: Authenticate RUM Proxy Exports (#16114)
Co-authored-by: Lia <lia@librechat.ai>
2026-09-20 05:25:26 -04:00
Danny Avila
2df937dd06
🌳 feat: Isolate Attached Workspaces by Conversation (#16107)
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: bind attached workspaces to conversations

* ⬆️ chore: bump agents to 3.8.8
2026-09-19 23:19:26 -04:00
Danny Avila
36efc7b4e2
🧺 fix: Bound Background Completion Batches (#16102)
* 🧺 fix: Coalesce Durable Background Wakeups

* fix: Bound replayed background result claims

* fix: Harden background result coalescing controls

* fix: Reconcile background result claims

* fix: close background batch ownership races

* fix: Keep completion batching atomic and bound serialized metadata

* refactor: Reuse canonical background claim contracts

* fix: Expose serialized claim budget in the persistence contract

* test: Preserve claimed V1 results across later background batches
2026-09-19 21:17:32 -04:00
Danny Avila
8a3ab43965
📬 fix: Persist Background Results Before Parent Rows (#16101)
* 📬 fix: Persist Background Results Before Parent Rows

* fix: Harden durable background result delivery

* fix: Fence durable background completion ownership

* fix: reconcile durable background receipt ownership

* test: align background receipt mocks with contracts

* fix: Fence durable result ownership and recover interrupted cleanup

* fix: Mark independent receipt projections for task-local ownership

* fix: Carry receipt provenance through message patch inputs

* fix: Preserve resumed receipt delivery during mutual claim yielding

* fix: Preserve conversation cleanup for non-receipt owner identities

* fix: Preserve receipt recovery across cleanup and retry exhaustion
2026-09-19 20:26:58 -04:00
GokayAI
f80f0be90e
🔑 fix: Stringify Ban Cache Keys When Redis Is Off (#16039)
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
* 🔑 fix: Stringify Ban Cache Keys When Redis Is Off

Keyv/Mongo throws when checkBan passes a raw ObjectId as the cache key
with Redis disabled, which 500s every social OAuth login.

Fixes #16025

Signed-off-by: GokayAI <60583610+gokay-ai@users.noreply.github.com>

* 🔑 fix: Stringify Violation Log Keys and Cover Bans With Real Keyv

logViolation keyed its violation and ban logs by the raw
`req.user.id ?? req.user._id`, the same shape checkBan used, so a lean
user document would hit the same keyv 5.6 `key.startsWith` TypeError on
the namespaced violation stores and record its ban under an ObjectId.

The new spec drives checkBan and logViolation through real namespaced
Keyv instances (Mongo-backed ban store, in-memory violation logs) with
an ObjectId-only OAuth user: an unbanned user passes, and a ban logged
from one address is enforced for the same user from another.

* 🎯 refactor: Stringify Only the ObjectId Fallback for Ban Keys

The id is converted once, where a non-string can enter: the lean
document's `_id` fallback. `req.user.id` is already a string on every
path that sets it (the JWT strategies, Mongoose's `id` virtual, the 2FA
limiter's temp-token id), and the email lookup already stringifies, so
`getBanCacheKey` and that line go back to their dev form.

---------

Signed-off-by: GokayAI <60583610+gokay-ai@users.noreply.github.com>
Co-authored-by: Danny Avila <danny@librechat.ai>
2026-09-19 15:52:06 -04:00
Danny Avila
aacf1de9da
🗂️ fix: Keep a Running Attachment Chat in the Sidebar (#16104)
* 🗂️ fix: Keep a Running Attachment Chat in the Sidebar

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

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

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

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

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

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

save.spec.ts drives the real data-schemas methods against an in-memory
MongoDB: the seed creates an empty row without reading messages, the
message save appends to it without a second lookup, an existing chat and
a subagent thread are left alone, a temporary chat keeps its retention,
and a failed lookup settles instead of rejecting.
2026-09-19 15:51:02 -04:00
Danny Avila
13c74c9574
⛽ feat: Negotiate Background Command Timeouts (#16100)
* ⏳ feat: Negotiate BYOM Background Command Timeouts

* ⏱️ fix: Preserve Foreground Programmatic Timeout
2026-09-19 15:01:41 -04:00
lia-by-librechat[bot]
1080f90bed
🎱 fix: Stop Sealing a Code Environment Decision a Chat Never Made (#16056)
* fix: Stop Sealing a Code Environment Decision a Chat Never Made

Switching an existing chat to a coding agent left the composer unable to
send. The chat had no workspace to select, Send stayed disabled, and the
workspace chip was a read-only status with a recovery hint.

Both layers treated "no decision recorded" as "decided to run without an
attached environment". `readPersistedDecision` documented that a stored
conversation always carries a decision and inferred `without_attached`
whenever `codeEnvironmentMode` and `codeWorkspaces` were both absent,
which is the ordinary state of a chat whose turns never involved a
code-capable agent. `resolveConversationCodeEnvironmentDecision` then
sealed that inference, so the first workspace its owner picked came back
as `locked`. The client mirrored the same premise: `locked` was any saved
chat, so `useCodeWorkspace` withheld agent defaults, a remembered
selection, and a sole workspace, and `CodeWorkspaceMenu` rendered its
non-interactive locked branch.

Only a recorded decision is sealed now. A conversation holding neither
field is undecided, so its first coding turn establishes the decision,
and `resolvePersistableCodeEnvironmentDecision` records that decision
with its selections; writing the mode alone would leave `attached`
without the selections the next turn validates. On the client the same
predicate drives `locked`, and the selection defaults that already
applied to a new chat now apply to any chat that has not decided.

An explicit `without_attached` stays sealed, a legacy row still infers
`attached` from the selections it stores, and a sealed decision is still
replaced only by its owner's move.

* fix: Record the first code environment decision on an existing chat

A saved chat that holds no decision may record the one a run establishes,
but every caller persists through `saveConvo`, which carries those fields
only in `$setOnInsert`. On a row that already exists the write was dropped,
so the choice never survived a reload and a later turn could resolve a
different workspace.

`saveConvo` now fills a whole decision onto a row that holds none, by
compare-and-set on that absence: a writer that decided first keeps its
decision, a chat that already holds one is untouched, and bare selections
never seed a row.

* fix: Record the decision a failed turn of a saved chat ran under

`saveErrorTurn` built its conversation fields only when it was seeding a new
row, so an existing chat kept the stored error turn without the decision that
turn ran under: a retry could then pick a different workspace than the failure
already recorded. The validated decision now travels on both branches, where
the conditional write in `saveConvo` keeps it from replacing a stored one.

* refactor: Resolve the error turn's decision fields in `packages/api`

The error-turn save derived its own decision fields, putting persistence
policy in a CJS controller where `/api` is meant to hold wiring only. It now
calls `resolvePersistableCodeEnvironmentDecision`, the resolver the streaming
saves already use, so one rule decides what a turn may record: a chat that
holds a decision keeps it and receives no decision fields at all.

* fix: Keep the legacy code environment lock until the protocol is advertised

The composer unlocked a saved chat that holds no decision without consulting
`codeEnvironmentDecisionVersion`, so during the rollout window it could attach
an agent default and submit it to a replica that still reads a field-less row
as a sealed `without_attached` and rejects the turn as `locked`.

The unlock now waits for the deployment to advertise the protocol, which makes
the hook identical to its previous behavior while the flag is unset. Nothing is
lost by waiting: the unmade decision is only reported once that flag is on.

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-19 13:13:24 -04:00
lia-by-librechat[bot]
9acf9f0ac8
🫗 fix: Roll Back Incomplete Skill Archive Imports (#16052)
* 🫗 fix: Roll Back Incomplete Skill Archive Imports

A .zip or .skill import created the skill first and persisted its bundled
files one by one, keeping the skill and answering 201 when a file failed
validation, a size limit, storage, or its database row. The client never
read the internal `_importSummary`, so it showed "Skill created" and
navigated to a skill that silently lacked the resources SKILL.md names.

Import is now atomic: any failed bundled file rolls back the skill, its
file rows, the ACL grant, and the blobs already written to storage, and
the request answers 422 `skill_import_incomplete` with the failed paths
and reasons. The upload dialog stays open and lists them.

* fix: Localize Import Failure Reasons and Report Every Lost File

Addresses the first review round on the archive import rollback.

Failure reasons are now stable codes (`invalid_path`, `file_too_large`,
`archive_too_large`, `archive_entry_changed`, `persistence_failed`) that
the client localizes, so a non-English locale no longer sees English text
and storage or driver messages stay in the server log.

The decompression budget stops the scan mid-archive, and the entries it
never reached were missing from the response, telling the user they had
seen the whole failure set. Those paths are now reported too.

Rollback deletes stored blobs only once `deleteSkill` confirms the skill
is gone; otherwise the blobs stay and the request answers 500
`skill_import_rollback_failed`, because a surviving skill pointing at
deleted files is worse than unreferenced storage.

The failure list scrolls instead of overflowing the dialog, and a
response that resolves after the dialog was dismissed no longer
repopulates it for the next session.

* fix: Ignore Late Skill Import Successes

* fix: Make Skill Import Rollback Retryable

* fix: Propagate Incomplete Skill Cleanup

* fix: Settle Rollback Blob Cleanup

* test: Type Partial Cleanup Fixture

* fix: Preserve Settled Skill Cleanup Steps

* fix: Export Skill Cleanup Step Type

* fix: Reconcile Partially Deleted Skills

* fix: Reconcile Skill Rollback Caches

* style: format cleanup reconciliation changes

* fix: complete skill rollback cleanup

* chore: leave generated locale catalogs unchanged

* fix: preserve synced skill blob cleanup

* test: type synced blob cleanup mock

* fix: Validate Archive Paths and Bound Rollback Cleanup

---------

Co-authored-by: Lia <lia@librechat.ai>
Co-authored-by: Danny Avila <danny@librechat.ai>
2026-09-19 12:41:30 -04:00
Danny Avila
c0affede00
🎟️ fix: Preserve BYOM Tool Calls Through Capacity Windows (#16060)
* ⏳ fix: Keep BYOM tools queued across capacity windows

* ⏳ fix: Configure the admission budget and refresh queued credentials

Addresses the Codex review on #16060:

- Add `limits.maxQueueWaitMs` to the code environment config schema so a
  deployment can shorten or disable the five-minute admission budget from
  `librechat.yaml`; omission keeps the merged behavior, `0` surfaces the
  first capacity expiry to the model. Resolved through
  `resolveAttachedWorkspaceQueueWaitMs` and passed by ToolService, matching
  how `maxCommandTimeoutMs` already flows.
- Accept an auth-header supplier in `executeWorkspaceTool` and mint it per
  admission attempt, so a call queued past the Code API token TTL presents
  fresh credentials instead of failing permanently with 401. The attached
  Bash tool and the workspace file operations now pass suppliers.
- Recheck the deadline after a clamped wait and throw the saved rejection
  rather than opening an admission window that could still be admitted
  once the budget is spent.

* fix: Complete workspace admission wiring and caller regressions

* fix: Share protected edit retry budgets and schema limits

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-19 09:03:06 -04:00
lia-by-librechat[bot]
94fed5bcd5
🥡 fix: Delete Storage and Embeddings With Owned Agent Files (#16007)
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
The agent tool-resource branch of DELETE /files removed a file's association
from the agent and answered 200 without reaching processDeleteRequest, so the
bytes on disk and the RAG chunks of a file the caller owned survived the delete.
A replaced File Search document kept answering from its old chunks (#15930).

An attached file now goes through the full delete pass, but only when nothing
else holds it: a file the caller does not own, and a file any other
(agent, tool_resource) pair still references, are unlinked and left whole.
Nothing is unlinked until the destroy it depends on has succeeded.

- packages/api/src/files/deletion.ts: deleteAgentResourceFiles owns the
  operation with its db methods and delete pass injected.
- packages/data-schemas: getSharedResourceFileIds answers the last-reference
  question, excluding the pair being removed by the agent's _id.
- Local/crud.js: unlinkFile propagates non-ENOENT, so a file whose bytes
  survive is no longer reported as deleted.

Co-authored-by: Mohammed Alshyakh <mohmedmm@users.noreply.github.com>
2026-09-17 02:59:25 +00:00
Artyom Bogachenko
12d78909d3
👛 fix: Drop Unread Credentials From MCP Domain Validation (#16035)
Some checks failed
Docker Dev Images Build / publish (push) Has been cancelled
Sync Helm Chart Tags / Ignore non-main push (push) Has been cancelled
Sync Helm Chart Tags / Sync chart tags (push) Has been cancelled
* fix: Resolve live OpenID bearer before the MCP early domain gate

* fix: Drop unread credentials from the MCP early domain gate

The early domain gate resolves the whole server config through
`processMCPEnv`, but decides from the URL alone. A credential placeholder in
any other field therefore raised `OpenIDReauthRequiredError` from a stale
request-time OpenID snapshot, before the connection path could refresh that
bearer, and the tool was dropped from the agent's toolset.

`buildMCPDomainValidationConfig` narrows the config to what the decision reads,
so the gate needs no live credential. A URL placeholder still fails closed, and
the argument is never mutated, so direct-bearer recovery keeps the placeholder
it knows how to refresh.

Replaces the per-tool `upstreamTokenProvider` call the gate would otherwise
make (1 + N per request per server) and covers every credential-bearing field,
not only `Authorization`.

Co-authored-by: Artyom Bogachenko <SpectralOne@users.noreply.github.com>

---------

Co-authored-by: Lia <lia@librechat.ai>
Co-authored-by: Artyom Bogachenko <SpectralOne@users.noreply.github.com>
2026-09-16 22:13:49 -04:00
lia-by-librechat[bot]
2452f499a8
🗼 fix: Serialize MCP OAuth Token Refresh Across Replicas (#15993)
Some checks failed
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
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
Frontend Unit Tests / Client build recovery regression (push) Has been cancelled
Frontend Unit Tests / Codegraph select (push) Has been cancelled
Frontend Unit Tests / Build packages (push) Has been cancelled
Sync Locize Translations & Create Translation PR / Sync Translation Keys with Locize (push) Has been cancelled
Frontend Unit Tests / TypeScript type checks (client) (push) Has been cancelled
Frontend Unit Tests / Tests: @librechat/client (push) Has been cancelled
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Has been cancelled
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Has been cancelled
Frontend Unit Tests / Vite build verification (push) Has been cancelled
Sync Locize Translations & Create Translation PR / Create Translation PR on Version Published (push) Has been cancelled
* fix: Serialize MCP OAuth token refresh across replicas

`MCPTokenStorage.inflightRefreshes` coalesces refresh-token redemptions
inside one Node process. Behind a load balancer without session affinity,
one user's concurrent requests land on different replicas, each reads the
same not-yet-rotated refresh token and redeems it. RFC 9700 servers treat
the second redemption as replay and revoke the whole grant family, so the
user is asked to authorize the MCP server again.

`forceRefreshTokens` now takes a cross-replica refresh flight before
redeeming, using the same `FlowStateManager.acquireLease` primitive the
OAuth teardown fence uses under a distinct key. A replica that waited for
the flight adopts the tokens the holder rotated instead of redeeming
again; when the flight is still held after the wait window it falls back
to the unfenced redemption every earlier release performed.

* fix: Redeem unfenced when the refresh flight lease store fails

* fix: Fence MCP refresh waiters instead of redeeming unfenced

A waiter that could not take the cross-replica refresh flight fell through to
an unfenced redemption after 10s, while the holder's own stale abort does not
fire until 60s. A refresh taking 11 to 60 seconds therefore still let two
replicas redeem one refresh token, the replay this fence exists to prevent.

The waiter now polls until it either adopts the tokens the holder rotated or
acquires the flight, and fails as MCPTokenRefreshUnavailableError rather than
redeeming beside a live holder. `getTokens` callers defer connection recovery
on that error, and the stored credential is left intact for a later attempt.

The flight is keyed by the stored credential (tenant, user, server name)
rather than the caller's OAuth binding digest, so a rolling config change
cannot hand two replicas different locks over one stored token. The wait is
an operator lever, `oauthRefreshWaitTimeout`, clamped to half the stale
window. An adoption read that fails no longer gives up the held flight.

* fix: Annotate derived refresh-flight constants for isolatedDeclarations

* fix: Recapture the credential generation a peer published on adoption

* fix: Hold the MCP refresh flight until redemption settles

Four corrections to the cross-replica refresh flight.

The flight lease equalled the window that aborts a stalled redemption, on
the claim that an expired flight could never belong to a redemption still
able to reach the token endpoint. Aborting proves no such thing: the
request may have been processed with its response lost, and a stalled
event loop can delay the abort past its own deadline. The lease now
outlives the abort, so a peer cannot redeem a credential the provider has
already rotated. A live replica still releases on settle, so the margin is
paid only by one that died holding the flight.

The credential snapshot was taken after the first failed acquisition, so a
holder that stored and released in that gap was snapshotted post-rotation:
the next attempt saw an unchanged record and redeemed the credential it
should have adopted. It is taken before the first attempt now.

`oauthRefreshWaitTimeout` accepted zero while the runtime mapped every
non-positive value to the default, so the config validated and then
behaved contrary to its value. Zero is rejected at load.

Adoption announced a second credential change through
`handleOAuthRefreshSuccess`, whose `onOAuthCredentialsChanged` advances
authorization state after persistence this replica did not perform. That
retired the generation recaptured beside it and fenced the build against
its own tool publication. Adoption now updates the local token-flow cache
and recaptures, without announcing.

* fix: Check every held MCP refresh flight for a peer's rotation

Four corrections, two of them consequences of moving the credential
observation ahead of the first lease attempt.

That move created a storage read inside `beginRefreshFlight`, and its
failure reached a handler written for a lease-store outage, so a transient
read error became an unfenced redemption beside a live peer. The flight
now handles its own reads: losing the observation costs adoption and
nothing else, and only the lease store failing may redeem unfenced.

The observation was also never compared when the first acquisition
succeeded. A peer that rotated and released before this replica contended
left an acquisition that looked uncontended, and its fresh credential was
redeemed a second time. Every acquisition now runs one rotation check,
which also collapses two code paths into one.

`getTokens` already loads the refresh record to decide a refresh is
needed, so it is passed on as the observation baseline instead of read
again, and the read taken under the flight is reused as the credential
redeemed. Two reads on a latency-counted path where there were three.

`runSilentRefresh` collapsed contention into null, sending the 401 path to
interactive OAuth, so a slow peer prompted the user to authorize a server
whose credential was about to be valid. The retryable outcome now travels
through the silent-refresh layers and the connection defers, matched by
name as well as identity because these errors cross the package boundary.

* chore: Regenerate the Agents OpenAPI spec for repositoryInstructions

The drift check added by #15928 fails on dev: #16008 added
`repositoryInstructions` to the agent schema without regenerating the
committed spec, so every branch merging dev inherits the failure. This is
the remedy the check itself prescribes and carries no hand-written change.
Drop this commit if dev regenerates first.

* fix: preserve MCP refresh outcomes across replica boundaries

* fix: keep MCP adoption fenced through publication

* fix: anchor MCP refresh adoption to rejected credentials

* fix: Complete OAuth Adoption Adapters and Isolate Legacy Flow Readers

* fix: Preserve OAuth Request Identity Through Recovery and Discovery

* fix: Fence OAuth Adoption Against All Credential Writers

* fix: Gate Coordinated OAuth Rollout and Preserve Unauthenticated Identity

* fix: Preserve OAuth Coalescing Across the Staged Rollout

* style: Sort OAuth Timeout Constant Import

* fix: Invalidate Both OAuth Token Flow Protocols on Rotation

* test: Complete the Rollback Token Flow Fixture

---------

Co-authored-by: Lia <lia@librechat.ai>
Co-authored-by: Danny Avila <danny@librechat.ai>
2026-09-16 21:58:23 -04:00
Marco Beretta
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>
2026-09-16 21:32:41 -04:00
lia-by-librechat[bot]
9e83b10545
📭 fix: Deliver Attachment Text Until a File Tool Holds It (#16027)
* 📭 fix: Deliver Attachment Text Until a File Tool Holds It

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

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

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

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-16 15:46:35 -04:00
Dustin Healy
44af4d3789
📖 fix: Verify Agents OpenAPI contracts and disable external reporting (#16028) 2026-09-16 15:17:56 -04:00
Atef Bellaaj
69f0dd2a12
🔌 feat: OpenAPI spec and docs for the public Agents API (#15928)
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
* 🔌 feat: OpenAPI spec and docs for the public Agents API

* 🔧 fix: address review on Agents API OpenAPI spec and docs:

- adapter: mark JSON request bodies as required
- openapi.js: move gate, config read and spec serving into packages/api
  as an injected router factory; leave /api as wiring only
- docs: compute URLs in-browser and use a relative servers url so docs
  work under a base path (e.g. /chat)
- build: copy the generated spec into dist so the multi-stage image ships it
- agents: reuse the enforced list envelope for the docs so the AgentList
  schema cannot drift from the runtime cursor and strictness

* 🔧 fix: align Agents API OpenAPI contract with enforced runtime

Second review round on the public Agents API spec. Three cases where the
published contract described something the server does not do, so generated
clients would fail against the live API:

- Upload form: document the `purpose` field (enum: file_search, execute_code,
  context) that POST /agents/{id}/files actually requires, instead of the
  internal-only `tool_resource`; requests following the old form were rejected
  with 400 because `purpose` was absent.
- Auth: drop the `apiKeyBearer` scheme from the management and skill endpoints.
  They gate on OIDC/M2M via requireAgentManagementAuth and deliberately reject
  the API-key fallback; the API key belongs to the out-of-scope
  OpenAI-compatible endpoints and returns when those are documented.
- Skill update: document the 409 conflict PATCH /skills/{id} returns on a stale
  expectedVersion. The agent update path collapses its internal 409 to 400, so
  it correctly keeps no 409.

* 🔧 fix: serve docs on experimental server and document the 401

Third review round on the public Agents API spec.

- Experimental server: mount routes.openapi in api/server/experimental.js before its /api 404 handler. Without it, npm run backend:experimental returns 404 for /api/docs and /api/openapi.json even when openapi.enabled is true, because that server never mounted the router.
- Auth failure: document the 401 that requireAgentManagementAuth returns on a missing, expired, malformed, or unbound token. Its body is { "error": "Unauthorized" }, a flatter shape than the management error schema, so add a dedicated UnauthorizedError schema and a shared 401 response to the agent and skill contracts rather than reusing the standard error schema.

* 🔧 fix: document skill-update, auth-conflict, upload-limit, and watch-copy gaps

* 🔧 fix: added error shapes for permission denied and internal server errors in API responses docs

* fix: cover the auth-layer 500 shape and pin the account-deletion code

* fix: update OpenApiRouterDeps documentation and simplify request handling in isEnabled function

* 🔧 fix: gate the Swagger asset mount behind the OpenAPI toggle

* 🔧 fix: accept the malformed-JSON 400 envelope in the contract

* fix: accept the tenant-isolation 403 envelope in the contract

* fix: add description for content property in SkillFileUpdateRequest to clarify byte limit
2026-09-16 13:50:05 -04:00
Danny Avila
299dbc6075
📖 Load Repository Instructions for Attached Workspaces (#16008)
* Load authorized workspace repository instructions into agent context

* Unify repository instruction loading across agent ingresses

* Await cancellation regression assertion directly

* Annotate the shared instruction loader for declaration builds

* Expose repository read budget and inject the host-owned cache
2026-09-16 09:00:35 -04:00
lia-by-librechat[bot]
be54587d14
🪒 fix: Strip Cache-Bust Suffixes From Every Local File Read (#15991)
* 🧼 fix: Strip Cache-Bust Query Before Local Vision Encode

Reused code-interpreter images persist filepath with a ?v= suffix.
prepareImagesLocal now strips it before disk encode, matching crud/share.

Co-authored-by: Zsanz3 <Zsanz3@users.noreply.github.com>

* 🧪 test: Isolate prepareImagesLocal query-strip coverage

Mock sharp and resize so the local vision-encode test does not load
the rest of the file-strategy graph.

Co-authored-by: Zsanz3 <Zsanz3@users.noreply.github.com>

* 🪒 fix: Strip Cache-Bust Suffixes From Every Local File Read

Reused code-interpreter outputs persist a `?v=<timestamp>` suffix on the file
document's filepath, and local storage resolves that field into a filesystem path.
prepareImagesLocal already handled it after the cherry-picked commits; getLocalFileStream
did not, so every download-stream consumer (the download route, provisioning, agent and
skill file reads) still hit ENOENT for a regenerated image.

Move the strip into one documented helper and call it from all three local read paths.

* 🧱 refactor: Move Cache-Bust Stripping Into the Storage Package

`/api` holds wiring, not behavior, so `stripCacheBust` moves out of a new CJS helper and
into `packages/api/src/storage/path.ts`, beside `resolveDownloadPath` — the function that
already decides what a stored filepath means to a download. Its doc comment now states why
the two differ: a remote strategy's query string can carry a presigned signature, so only
the local paths may strip.

The local storage modules keep just the call into it. Semantics are covered by the storage
package's own test; the `/api` specs pin the wiring.

Addresses the Codex P1 finding on 5f8dbf3cf.

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Zsanz3 <Zsanz3@users.noreply.github.com>
Co-authored-by: Lia <lia@librechat.ai>
2026-09-16 08:28:32 -04:00
Danny Avila
4d08bcf203
⛓️ fix: Bind Programmatic Bash to Selected Workspaces (#15992)
* fix: Enable programmatic Bash in selected attached workspaces

* Centralize project PTC construction and preserve recognized capabilities

* Prevent stale list refreshes from restoring removed pins
2026-09-16 07:46:16 -04:00
lia-by-librechat[bot]
35d5a70b21
🧦 fix: Restore OpenID Refresh After the Session Store TTL Expires (#15983)
* 🧦 fix: Restore OpenID Refresh After the Session Store TTL Expires

express-session raises `failed to load session` only when the store holds no
record for the session id. #15655 treated that as terminal, so a refresh whose
cookie refresh token was still valid ended in 401 OPENID_SESSION_MISSING once
the OpenID session store TTL (15 minutes by default) elapsed before the IdP
access token (~1 hour with Entra ID).

Reload the persisted record through one tolerant helper: an absent record is an
empty session, not a session that advanced past this result, so publication
seeds a new record. Store outages still propagate, and logout still fails a
retired refresh token through its durable revoked publication flight.

* 🧪 test: Pin the logout fence around the tolerated session reload

Tolerating an absent session record leaves the durable revoked publication
flight as the only thing between a logged-out refresh token and a resurrected
session, so cover both of its checks with an expired record: the tombstone read
that precedes the reload, and the completion that follows it.

Drop a needless optional chain in publishResolvedSessionTokens, whose `req`
parameter is not optional.

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-15 23:54:42 -04:00
Danny Avila
ed95a9b802
🍯 fix: Stop Approval Pauses From Unsealing Code Environments (#15963)
* fix: Preserve Code Environments Across Approval Pauses 🧷

* test: Match Agent Request Conversation Identity 🪪
2026-09-15 12:30:37 -04:00
Danny Avila
21a9edbe74
🪪 feat: Pass Schedule Identity to MCP Token Providers (#15962)
* feat: carry schedule context into MCP token providers

* fix: restore scheduled token context after approval pauses

* fix: make scheduled identity boundaries explicit

* test: keep owner-drain leases live through CI delays
2026-09-15 10:46:13 -04:00
Danny Avila
dea7346d72
🧷 feat: Carry Ask User Answers Past Compaction (#15944)
* 🧷 feat: Carry Ask User Answers Past Compaction

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

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

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

* 🧷 feat: Carry Ask User Answers Past Compaction

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

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

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

* 🧷 refactor: Read The Warm Branch Inside The Module

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

* 🧷 fix: Complete The Branch Behind A Summary Cut

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

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

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

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

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

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

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

* 🧷 refactor: Apply The Answers Block Inside The Module

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

* fix: Apply Retained Answers After Summary Replay 🧷

* perf: Count Retained Context Exactly Within Its Budget 🧮

* fix: Preserve Retained Counts Across Checkpoint Recounts 🧾

* fix: Isolate Retained Context Counting and Provenance 🧵

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

* fix: Use Workspace-Compatible Array Traversal 🧭

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* feat: use declared attached project actions

* Complete named action definitions and approval previews

* Sort named environment imports

* Sort native environment fixture imports

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* fix: Preserve attachment reachability across handoffs and late steers

* test: Type the untrusted attachment reference fixture

---------

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

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

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

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

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

* fix: canonicalize input_audio format from MIME type

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

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

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

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

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

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

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

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

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

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

* fix: reject unsupported provider audio during upload

---------

Co-authored-by: Renato Garita Figueiredo <renato.garitafigueiredo@uni-osnabrueck.de>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-14 16:38:51 -04:00
Danny Avila
b1f6f6df2f
👯 fix: Reject Duplicate Tool Approval Identities (#15933)
* fix: Reject aliased tool approval identities

* fix: Keep approval validation in TypeScript

* style: Format approval validation
2026-09-14 15:08:26 -04:00
Marco Beretta
f077e8c967
🗯️ fix: Give Failed Turns Actionable Guidance (#15896)
* 🧯 refactor: State Failed Turns in Copy a Reader Can Act On

Every client-facing error code now has authored copy, so no failed turn renders
raw JSON, an unresolved `com_error_*` key, or a provider message cut at 512
characters. `client/src/components/Messages/Content/Error.tsx` becomes a module
directory: a dispatcher resolving `json.code ?? json.type`, a registry splitting
one-sentence copy from payload-aware renderers, and shared parts that resolve the
provider, model, user-key ownership and compaction capability behind the failure.

Message-limit violations persist `resetAt`/`retryAfterSeconds`, so the row counts
down to the window's reset instead of naming a window length alone.

* 📸 chore: pin before/after error copy screenshots for the pull request

* 🧹 chore: drop the pinned pull request screenshots from the tree

* 🔻 style: Trail the error disclosure chevron after its label

* ⏱️ refactor: Derive Limiter Resets in packages/api, Stamp Key Expiry as ISO

The message limiter's reset fallback and retry arithmetic move out of the
CJS middleware into `getRateLimitReset` in packages/api, which both the
message and agent-event handlers now call, so /api keeps only the wiring.

`checkUserKeyExpiry` persists `expiredAt` with `toISOString()` instead of
the server's `toLocaleString()`, which a client in another locale could
parse with day and month swapped.

* 🪪 fix: Attribute Failed Turns to the Row, Agent and Payload That Failed

Error content parts render through `Part` without their message, so their
copy named the conversation's current endpoint and model rather than the
ones that failed. The chat, flat-thread and search row renderers now supply
the row's identity through `ErrorSourceProvider`, and the dispatcher reads
it whenever no row is passed directly.

A saved agent's row carries the `agents` endpoint and the agent id as its
model, so identity, key ownership and the key dialog resolve against the
agent's own provider and model; an endpoint named by the payload (an
expired key) outranks both. The agent builder is only suggested where the
side panel would offer it: agents configured, builder not disabled, USE and
CREATE held, and an EDIT grant or administrator role.

Also in the renderers:
- structured refusals read Anthropic's `stop_details.explanation`
- provider bodies nesting their message under `error` keep that message
- upstream model failures name the provider when it is known
- `INVALID_USER_KEY` offers the key dialog on a user-provided endpoint
- an oversized message is never told to compact the conversation
- the countdown is bounded by the limiter's window, not a fixed day, and its
  ticking text is hidden from the assertive live region
- an expiry persisted in a server locale is shown as written
- search rows that failed render through the dispatcher, not as markdown
- the payload type is an explicit JSON value type

* 🧪 chore: Seed Real Refusal, Legacy Expiry and Nested Provider Error Shapes

The gallery's refusal case used a string `info` no producer writes; it now
carries Anthropic's stop metadata and a Bedrock content filter. It also
seeds an expiry stamped in a server locale, an unreadable key on a
user-provided endpoint, and a provider body nesting its message under
`error`, and removes whatever it inserted when a write fails.

* 🧵 fix: Keep the Reason From a Provider Body Embedded in Failed-Run Text

A failed run persists a provider error as `<base message>: <SDK message>`,
and Anthropic's SDK message embeds the response body, so the persisted text
reads `…request: 400 {"type":"error","error":{"message":…}}`. The
fallback renderer dropped that body and kept only the prefix, losing the
reason. It now swaps the body for the message it carries.

* 🔀 fix: Resolve Handoff Agents, URL-Owned Credentials and Nested Error Codes

An error part after an `AGENT_UPDATE` belongs to the agent the run was
handed to. `ErrorSourceProvider` now records where a row's handoffs sit,
and an error part resolves the agent active at its own `partIndex`; search
and shared rows give error parts that position too. A handoff the agents
map cannot resolve names no provider instead of the agent that handed off.

A user-provided base URL makes the reader's own record hold the key as
well, so key failures on such an endpoint offer the key dialog. `NO_BASE_URL`
and `INVALID_BASE_URL`, which only a user-provided URL produces, render
through the same renderer with named copy and an add or update action.

OpenAI-compatible bodies nest `code` and `type` under `error`; when the top
level names neither, the dispatcher reads the envelope, so a nested
`invalid_api_key` reaches the key renderer.

* 🕰️ fix: Keep Unknown Key Ownership Generic, Measure Resets From the Row

A shared link's viewer has no endpoint configuration, so whether the reader
or the deployment owns a key is unknown; key copy there read that as
deployment-owned and told the viewer to ask an administrator. Ownership is
now undefined without a configuration, and the copy stays generic.

The countdown's window bound used this device's clock, so a device running
behind the server could drop a valid reset. The window now runs from the
row's own timestamp, which the server stamped alongside `resetAt`.

* 🗜️ fix: Suggest Compaction Only Where the Compact Action Is Offered

Manual compaction is only reachable from the context usage popover, which
`interface.contextUsage: false` removes. Context errors on such a deployment
suggested compacting anyway; they now fall back to the standard next steps.

* 🧭 fix: Keep Row Identity Authoritative and Every Generation Charge Visible

A row's own endpoint and model now stand even where it lacks them, so a
restored failure no longer borrows whatever the conversation selected since;
only an error rendered with no row reads the conversation, and an agents row
with no stored agent id (the live row of a turn that just failed) still
resolves the conversation's agent.

Also:
- a token-balance row lists every generation instead of the first 20
- search rows re-render when their `error` flag changes
- `AUTH_CROSS_ORIGIN`, added since this branch began, renders the login
  page's copy and has a gallery case, so the seed's completeness check runs;
  a table test now fails for any enum member without authored copy
- upstream model failures keep the provider-neutral sentence the server
  persists as their text, which the e2e suite reads the row by

* 🪞 fix: Resolve Ephemeral Agent Ids and Keep an Agents Row's Model Name

An agents row whose model is a model name, as an ephemeral agent's is,
lost both its provider and its model whenever no saved agent resolved.
Agent ids now resolve the way sibling headers resolve them: a saved agent
through the map without the parallel `____N` suffix, an ephemeral agent
through the endpoint and model its id encodes. A row that still resolves
nothing keeps the model name it recorded; an agent id is never shown.

* 🛤️ fix: Attribute Lane Errors to Their Agent, Count Live Retries Relatively

A parallel run stamps each part with the agent of its lane, and an error
part in one lane was attributed to whichever handoff last preceded it. The
row now records error parts' own agents alongside its handoff positions,
and an error part's own agent comes first.

A live countdown subtracted this device's clock from the server's
`resetAt`, so a device running fast could report the limit already over.
`retryAfterSeconds` is now counted from the row's own timestamp, which the
device stamps on a live row and the server on a restored one.

Search results read a cached startup config but have no compact control, so
compaction guidance now also requires the chat surface.

* 🧷 fix: Resolve an Agents Row From Its Own Model, Never the Current Agent

An agents row that stored a model name, as an ephemeral agent's does, fell
back to the conversation's current agent when no saved agent resolved, so
switching the conversation to a saved agent later rewrote who produced the
old failure. The fallback served no real row: the client's live placeholder
for an agents turn stores the conversation's agent id as `model`, as
persisted rows do. The row's `model` now decides on its own — a saved or
encoded ephemeral id resolves, a model name is kept, and the `ephemeral`
placeholder names nothing; only an error with no row reads the conversation.

---------

Co-authored-by: Danny Avila <danny@librechat.ai>
2026-09-14 10:37:22 -04:00
Danny Avila
345cf8877f
🍵 fix: Support Renewable MCP Credentials for Schedules (#15908)
* fix(schedules): forward renewable MCP credentials

* fix(schedules): require unattended MCP credentials

* fix(schedules): resolve MCP credentials during execution

* refactor(schedules): inject unattended credentials

* fix(schedules): scope renewable credential resolution

* fix: isolate lazy scheduled OBO credentials across MCP lifecycle

* fix: preserve MCP cancellation and retryable credential lookup

* fix: bind MCP cancellation to the owning run signal

* test: supply flow manager in OBO cancellation regression

* fix: preserve MCP cancellation across exchange and API ingress

* style: sort MCP manager imports

* fix: propagate cancellation through agent discovery

* test: preserve agent discovery edge literals

* fix: propagate agent initialization cancellation

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

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

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

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

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

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

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

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

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

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

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

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

* 🔁 fix: Strip Unusable Summaries From Responses API Continuations

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

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

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

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

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

---------

Co-authored-by: Danny Avila <danny@librechat.ai>
2026-09-14 10:22:47 -04:00
Danny Avila
7e05c4848a
👑 fix: Elect a Single Expired-File Sweeper (#15909)
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: elect one expired-file sweeper

* fix: unify clustered sweep ownership

* fix: retain clustered sweep fallback

* fix: use normalized Redis sweep ownership

* fix: reconcile sweep startup and concurrent leader ownership
2026-09-14 02:05:52 -04:00
Danny Avila
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.
2026-09-14 00:58:08 -04:00