Commit graph

2454 commits

Author SHA1 Message Date
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
Ravi Kumar L
e32e9f3222
⬆️ chore: bump agents to 3.8.7 (#15947) 2026-09-14 18:45:52 -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
JOJO
7fe9a45894
🧵 ci: Keep a Floor of Two Jest Workers in CI (#15819)
Some checks are pending
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
`maxWorkers: '50%'` resolves to a single worker on the 2-vCPU GitHub-hosted
runners that private repositories get, and Jest then runs in band. Any test
file that leaves a handle open (a listening `http.Server`, a timer, a DB
connection) keeps the main process alive after "Ran all test suites" until the
job's `timeout-minutes` cancels it, so a run with every test passing still
fails. Public runners have 4 vCPUs, where `'50%'` is already two workers and
the leaked handle dies with the worker process.

Move the worker count into `config/jest.workers.cjs`, shared by all six
workspace configs: local runs keep `'50%'`, CI uses `max(2, floor(cpus / 2))`.
On 4-vCPU runners the value is unchanged; on 2-vCPU runners Jest now uses
worker processes the same way it does upstream.

Co-authored-by: Danny Avila <danny@librechat.ai>
2026-09-14 00:32:20 -04:00
Danny Avila
854645ffc0
🔁 feat: Retry OpenID Discovery After Startup Failures (#15899)
* fix: retry OpenID discovery after startup failures

* fix: keep OpenID background retries resilient

* refactor: move OpenID retry policy into API package

* 🔁 feat: Expose OpenID Discovery Retries Through Registration Config

* 🧭 refactor: Own OpenID Discovery Registration and Defaults in TypeScript

---------

Co-authored-by: insoln <insoln@ya.ru>
2026-09-13 23:16:26 -04:00
Marco Beretta
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>
2026-09-13 22:20:25 -04:00
Marco Beretta
8e6e6f062d
🪧 fix: Emit the Configured-Footer Answer With the HTML Shell (#15886)
* 🪧 fix: Emit the Configured-Footer Answer With the HTML Shell

The chat surface lays out against whether the deployment configured a footer
(customFooter, privacy policy, terms of service). The client answered that from
localStorage — whatever the last resolved `/api/config` recorded — so the answer
was a guess on a first-ever visit and could be stale for a deployment whose
configuration changed.

The backend already knows when it serves client/dist/index.html, so it says so
there: `injectConfiguredFooterBootstrap` writes `hasConfiguredFooter` into
`window.__LIBRECHAT_CONFIG__` ahead of the app's own scripts, once at boot from
the base app config, and the client reads it on its first render instead of
remembering the last answer. The `configured-footer` storage atom is gone.

Client and server share one predicate (`hasConfiguredFooter` in
librechat-data-provider) so the two cannot disagree, and the shell injection is
generalized (`injectBootstrapConfig`), with the query-devtools flag now going
through it.

* 🧷 fix: Keep Bootstrap Values Literal and State the Shell's Contract

`injectBootstrapConfig` passed its script as a replacement string, so a `$&`,
`$1` or `$'` inside an injected value was expanded by `String.replace` instead
of reaching the client. Both insertion points take a replacement function now,
and the spec reads its values back off the global through an explicit result
type rather than an unchecked dictionary.

The shell answers from the deployment's own configuration, which a per-tenant,
role or user override of `interface.privacyPolicy` or `termsOfService` can
disagree with — `/api/config` resolves the caller's and the client prefers it.
That contract was overstated in three comments ("a deployment-lifetime fact",
"the same one the config will give"); they now say what the answer is and what
resolves the rest. Two scenarios cover the disagreement end to end: a document
served without the answer, and a policy link only this caller's config carries.
2026-09-13 21:53:54 -04:00
Marco Beretta
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`.
2026-09-13 21:53:29 -04:00
Danny Avila
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.
2026-09-13 21:51:05 -04:00
Danny Avila
696bcb6c1e
🏦 fix: Reserve Credits for In-Flight Requests (#15879)
* 💳 fix: Reserve Balance for In-Flight Requests

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

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

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

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

* 🪪 fix: Resolve Each User to One Balance Record

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

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

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

* 🔁 fix: Renew Balance Reservations While Their Request Runs

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

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

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

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

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

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

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

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

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

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

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

* 🧹 fix: Prune Expired Reservations in One Write

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

* ⏱️ fix: Renew Reservations From Their Stored Expiry

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

Expired holds are pruned as one bulk write of per-hold fenced updates, so a
hold that changed after the read is skipped while the rest are removed, and
the admission no longer spends a retry on the whole prune.
2026-09-13 12:53:19 -04:00
Danny Avila
9cf33cc8be
🧿 fix: Bind Login Flows to the Browser That Started Them (#15880)
* 🧿 fix: Bind Login Flows to the Browser That Started Them

Social OAuth logins (Google, Facebook, GitHub, Discord, Apple) now store a random state in an HttpOnly cookie scoped to the callback path and only exchange the returned code when the callback carries that state. Apple's form_post callback uses a SameSite=None cookie, and passport-apple's own fixed state no longer bypasses the store.

Local login, temp-token 2FA verification and admin local login reject requests a browser sent from another origin (Sec-Fetch-Site, falling back to Origin vs Host), trusting DOMAIN_CLIENT and DOMAIN_SERVER. Requests without browser fetch metadata, such as server-side callers, pass unchanged.

The sessionless OAuth callbacks drop failureMessage, which wrote to req.session and turned any rejected callback into a 500.

* 🧿 fix: Configure Login State Cookies and Localize Origin Rejections

- OAuth state cookies take secureCookie and maxAgeMs from the caller; registration.oauthStateTtlMs in librechat.yaml sets the lifetime (default 10 minutes).
- Secure deployments use a __Host- cookie at Path=/ so a sibling subdomain cannot plant a state.
- The cookie keeps up to three pending states, so logins started in separate tabs all complete, and an unmatched callback no longer discards them.
- passport-apple's preset state is dropped by deferStateToStore in packages/api.
- The Origin fallback compares scheme and host against the request itself.
- The same-origin rejection carries ErrorTypes.AUTH_CROSS_ORIGIN, which the login and 2FA screens show as a localized message.

* 🧿 refactor: Sign Login State Against a Per-Browser Binding

- The OAuth state store keeps a random per-browser binding in a __Host- cookie (reused across flows) and signs each state as issuedAt.nonce.HMAC(JWT_SECRET, provider, binding, issuedAt, nonce). Nothing is stored per flow, so any number of tabs complete, each state expires on its own clock, and concurrent starts no longer overwrite each other.
- The experimental server entrypoint passes its app config to configureSocialLogins.
- The same-origin guard also trusts an explicitly configured ADMIN_PANEL_URL.

* 🧿 fix: Keep Separate Bindings for Racing First Logins

A browser without a login-state binding now gets one under a cookie name with a random suffix, so two tabs that start their first login at once each keep their own binding. Later starts reuse an existing binding, and a callback is accepted when its state was signed for any binding the browser presents.

* 🧿 fix: Sanitize Request-Derived Values in the Cross-Site Rejection Log

The same-origin guard logged the request Origin and path verbatim. A non-browser client fully controls the Origin header, and the console transport uses a printf format that does not escape control characters, so a crafted value could forge log lines. Strip ASCII control characters (CR, LF, NUL and the rest) before logging, matching the pattern apiNotFound already uses.
2026-09-13 11:47:29 -04:00
Danny Avila
e43fed2ed4
🚄 perf: Linearize Conversation Import Lineage (#15881)
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: Resolve Large Conversation Import Lineage in Linear Time

Parent lookups, timestamp ordering, skipped-ancestor resolution and
citation linking during conversation import each rescanned the batch or
the text per message, so a large export spent minutes on the request.
They now run in a single pass, lifted into packages/api as
createChatGptLineage, linkChatGptCitations and orderMessageLineage.
Fork cloning and branch collection use id maps for the same lookups.

* 🧬 refactor: Lift Fork Clone Lineage Into packages/api

cloneLineage assigns clone ids, re-links parents and orders timestamps,
and getAllMessagesUpToParent moves over whole with its id map, so
fork.js only supplies the id generator and persists the clones.
2026-09-13 03:48:22 -04:00
Danny Avila
424d559b5e
🫂 fix: Scope People Picker Searches to Permitted Types (#15878)
* 🧭 fix: Resolve People Picker Search Types Once

The people picker access check and the principal search handler each parsed
the requested principal types on their own: the check honored both `type`
and `types`, while the search read only `types` and treated an absent or
unrecognized filter as every type. Searches now use the types the access
check resolved, so a request without a usable filter covers only the types
the role can view, and the Entra ID lookup follows the same set.

Moves the access check into packages/api as createPeoplePickerAccess.

* 🧭 refactor: Move Principal Search Handler into packages/api

Lifts the search-principals handler into createPrincipalSearch with its
database and Microsoft Graph calls injected, leaving the controller as
wiring. The people picker access check now takes a plain permissions
shape instead of the stored role document.

* 🧭 refactor: Type Principal Search Requests Without Stored User Documents

The exported request type now names the query, headers and the few user
fields the handlers read, instead of extending ServerRequest and its IUser.
2026-09-13 02:48:27 -04:00
Danny Avila
e18606e5ce
🚀 v0.8.8-rc3 (#15859)
Some checks failed
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
* 🚀 chore: prepare v0.8.8

* 🚀 chore: prepare v0.8.8-rc3

* docs: mention Agent workspace defaults
2026-09-13 02:17:48 -04:00
Danny Avila
3f2e4777cb
🛬 fix: Land MCP OAuth Callbacks on Waiting Connections (#15876)
* 🪪 fix: Adopt MCP OAuth Callback Tokens Without Re-Prompting or Losing the Lease

A chat request loading OAuth tokens joins the `mcp_get_tokens` flow a catalog
discovery left behind and polls it. The OAuth callback deletes that entry when
it stores the new tokens, so the poll ends with "Flow state not found", the
factory reports the tokens missing, drops the `mcp_oauth` flow the callback
just completed, and starts a second interactive flow. Once tokens arrive, the
connection leases the publication generation it captured before the wait; the
callback's publication moved it, so the connection is torn down as it connects
and the agent fails with AGENT_EXPECTED_MCP_TOOLS_UNAVAILABLE.

`createFlowWithHandler` now serves a completed result at once, monitors only
pending attempts and retained failures, and replaces a failure nobody retains;
a waiter whose flow disappears gets `FlowStateNotFoundError`. The factory
treats that as a credential change: it re-reads storage once, after letting
the connection build re-capture its generation. The authorization transaction
and a silent refresh attach the generation they publish to the tokens they
release, and a build adopts that generation for credentials obtained after
its capture.

* 🪪 fix: Claim Flow Attempts Atomically and Lease Under the Stored Generation

A connection now adopts a carried publication generation only while it is the
generation currently stored, instead of comparing the token's exchange time to
its capture, so a callback that exchanged before the build began and published
after it is still adopted and a retired generation still leaves the fence in
place. Installing a flow attempt is an atomic compare-and-set against the
attempt the caller observed, on Redis and on the default in-memory store, so
concurrent replacements of a failed attempt, or concurrent creations of an
absent one, run one handler while the rest join it. An aborted caller is
rejected before a cached result is served, and a joiner that aborts leaves the
shared flow to its owner and the other waiters.

* 🪪 fix: Return Generation-Tagged Callback Tokens and Route Flow Claims Through the Cluster Executor

The authorization transaction now returns the same generation-tagged tokens it
releases to the OAuth completion and the pending token waiters, so the callback
route's tool-flow completion carries the published generation to the connection
waiting on it. The Action OAuth and index-sync flow managers pass the
cluster-aware Redis script executor, so their flow claims and guarded
settlements route through slot-master selection and READONLY recovery instead
of the raw client.
2026-09-13 01:46:41 -04:00
Danny Avila
17c7b30631
💤 fix: Preserve Dormant Workspace Bindings (#15877)
* fix: Preserve Disabled Workspace Bindings

* fix: Resolve Restored Workspace State
2026-09-13 01:46:16 -04:00
Danny Avila
f43301f818
🔭 feat: Conversation Trace Viewer (#15869)
* 🔭 feat: Conversation Trace Viewer

Adds a trace view for a user's own conversations: a summary, a pinned
waterfall overview with interval focus, a hierarchical record ledger and
a record inspector, opened from the chat header (or the mobile overflow
menu) and read through a provider-neutral seam with Langfuse as the
first reader.

- interface.traceViewer (enabled, showInputOutput, maxRecords,
  maxContentLength, requestsPerMinute), off by default
- /api/traces/:conversationId availability, records and record routes,
  re-proving conversation ownership and narrowing the Langfuse session
  to traces the user's own sampled responses produced
- Langfuse reader over the v2 Observations API with cursor paging, time
  bounds, typed failures and server-side input/output withholding
- forks no longer copy the source messages' trace sampling record

* 🛂 fix: Address Trace Viewer Review Round 1

- interface.traceViewer.requestTimeoutMs bounds each Langfuse round trip
- availability is one existence query across every sampled response
  instead of the oldest one, run alongside the ownership check
- tree items report their position among visible siblings
- point-in-time Langfuse events read as completed, not running
- reads prefer the project holding the most responses when a tenant
  connection arrived mid-conversation

* 🎯 fix: Leave Focus With a Navigation That Closes the Trace

* 🧭 fix: Keep Trace Reads on One Project and Cancel Abandoned Reads

- page cursors and record details stay on the project that served the
  first page; pages report an opaque sourceId
- Open in Langfuse only appears when the linked project served every
  loaded page (the session link now reports its destinationId)
- client and server abort Langfuse reads when the viewer closes or the
  client disconnects
- reads never wait on the central project lookup, which the request
  timeout does not govern
- the cost total is withheld when any model call with usage is unpriced

* 🕰️ fix: Refresh Trace Pages After a Turn, Honor Clock Settings, Show Refresh Failures

- a settled run invalidates the cached trace pages, so reopening shows
  the new turn instead of pages fresh for another 30 seconds
- trace durations and clock times format in the app language and the
  user's 12/24-hour setting, as message timestamps do
- a failed refresh with every page loaded surfaces an alert and a retry

* 🔐 fix: Only Server-Authored Responses Grant Trace Access

- the message-create route and imports strip langfuseSampled and
  langfuseDestinationIds, and trace reference queries ignore client-authored
  rows (isUserSubmitted) and user turns, so a forged row cannot claim a trace
- the Langfuse reader receives its destination resolver and HTTP client
  from the route instead of defaulting to process-global ones
- availability asks the client to check again while central's project id
  is still resolving, instead of caching a false answer
- listRecords tries the next readable project when legacy responses left
  the first one empty
- a settled run also invalidates cached record details
- running is read from a record's status, not a missing end time

* 🏢 fix: Scope Trace Reads to the Tenant and Reach Every Project Holding a Turn

- ownership and both trace reference queries carry the requester's tenant
  (tenantless is its own scope), so a duplicate user and conversation id in
  another tenant cannot grant or supply trace references
- a read visits, page by page, every project that could hold a turn no
  earlier project provably holds, so legacy turns in another project stay
  reachable after a newer destination ranks first
- the trace read limiter takes its store from the route
- transient availability failures retry instead of hiding the control

* 🛟 fix: Fail Over Between Projects, Refresh One Page, Search Visible Labels

- a fresh read fails over to another project holding the same turns when the
  preferred one fails; the cursor carries the failed sources so later pages
  keep the rebuilt plan, and detail reads fail over the same way
- destinations for one project collapse into one source
- the trace read limiter keys each user within their tenant
- refresh and a settled run keep only the newest page before refetching, so
  older pages are not replayed through the limiter; retry repeats the read
  that failed
- search matches the localized kind and status labels a row shows

* 🧭 fix: Read the Newest Turn First, Report Failures Behind Empty Projects, Fit Trimmed Views

Rank trace sources by the newest sampled response they could hold before coverage and preference, so a conversation that moved projects shows its latest turn first.

Throw a list failure when a failed project could hold a turn that no answering project provably holds, instead of rendering an empty trace. Detail reads keep probing projects after an empty answer, skip ones whose turns an answering project provably holds, and surface a failure that could hide the record.

Refresh and settled runs trim the cache to the newest page; the viewer now fits a focused interval to the remaining records or clears it, and drops a selection whose record left with the older pages.

* 🧵 fix: Page Traces by Turn, Include Failed Runs, Keep the Active Row Mounted

List reads now page by turn segments instead of whole projects. A segment is the newest unread turn and up to 49 older consecutive turns one project could hold. The request filters Langfuse to those turns' run and title traces, so pages stay newest first when a conversation's responses alternate between projects. Legacy turns without destination ids are asked of the other projects in the segment. A project that failed for newer turns is retried when it alone holds older turns. A page whose rows all fail the observation schema is an upstream failure, not an empty trace.

A failed turn's error row now stores the sampling fields of the run that failed, plus langfuseRunId when that run was created, so the trace viewer and feedback scores follow the run's trace. langfuseRunId is stripped from client message writes and imports, dropped by forks, and hidden from client message projections.

The ledger keeps its active tree item mounted while virtualization scrolls it out of the window, so aria-activedescendant always names a rendered row.

* 🕰️ fix: Merge Multi-Project Trace Pages by Start Time, Keep Literal Content

A segment that reads more than one project now runs every read before returning. A read that fills the record budget cuts the page at the oldest start time all reads loaded, and the continuation carries that start time as an inclusive bound instead of a Langfuse cursor. Every project continues from the same point, so a newer turn held by another project is never left behind an older one, and failover works on any page. A page drawn from several projects no longer names a single source. A continuation that would repeat its own bound fails instead of looping.

Input and output that are literally the strings {} or null are kept; only an empty object or JSON null value is dropped.

* 🔎 fix: Read Each Trace Segment From a Project Shown to Hold It

Recorded destination ids say where a trace was eligible to go, not where it landed. A list read now looks up the turns more than one readable project could hold before choosing where to read them. Each project, preferred first, is asked which of those traces it holds a root observation for, and each turn is read from the preferred project that holds it, or from the preferred eligible one while a run's root is not exported yet. Turns only one project could hold need no lookup.

Segments are consecutive turns from one project, paged by that project's own Langfuse cursor. Records that share a start time page correctly, and the page budget bounds a single read. A failed project is dropped for the request. A turn only it could hold raises its failure at the turn's own place in page order, instead of leaving an empty or partial trace. Cursors carry the segment's trace-set hash and start over when the segment changed or Langfuse rejects them. Detail reads ask every project until the record turns up.

The trace summary withholds its cost total when any generation has no cost, with or without usage.

* 🧷 fix: Evidence per Trace, Continuations Without Replays, Stable Turn Order

A turn's run and title run are exported separately, so each trace id is looked up and read from a project shown to hold it. A trace no project shows (a title run the turn never had, or a run whose root is not exported yet) joins an adjacent segment whose project could hold it. Only a run that a failed project alone could hold raises that failure.

A continuation now stays on its project. Its failure is returned as is, and a cursor the segment no longer matches, or one Langfuse rejects, returns invalid_request instead of replaying the segment's first page. The viewer answers invalid_request on an older page by reloading from the newest page, with a message saying the trace changed.

Sampled responses sort by createdAt then _id, so responses saved in the same millisecond keep one order across page requests.

* 🪪 fix: Scope Trace Reads to the Exporting User, Order Split Title Runs

Trace ids derive from message ids, which a request can influence, so a colliding id must not return someone else's trace. Every Langfuse list, probe and detail read now also filters by userId: the requester's internal id, plus the configured langfuse.trace.userIdField value when set. The server stamps that id on the trace at export. The handler passes the requesting user into the trace query.

When a turn's run and title run sit in different projects, the probes' root start times decide which is read first, so a title generated after the response is not left behind Load older. Cursors name the trace a segment starts at within its turn.

The failed-turn trace lookup moves into packages/api as getFailedTurnTraceFields. The agent controller only passes the error row id, the run id and whether the run was created.

* 🔒 fix: Authorize Trace Reads by the Internal User Id Only

A configured langfuse.trace.userIdField can export a non-unique value (name, username) or one that repeats across tenants (email, provider ids) as the trace userId, so it cannot prove who a trace belongs to. Reads now require the internal user id alone. A deployment that exports another field reports no trace and logs why once, instead of trusting that value.

A failed read of a title run that a probe found in that project now raises its failure instead of dropping the title. The page contract now states that pages are ordered by turn and a turn's records may continue on the next page.

* 📚 fix: Page Sampled Responses With the Trace, Share Ingress Stripping

List reads load sampled response references a segment at a time: up to 50 ending at the cursor's turn, plus one older response that names the next page. Pages of a long conversation no longer rematerialize every sampled response. getConversationTraceRefs gains through and limit, anchored by createdAt and _id.

The message-create route and conversation imports strip trace sampling fields through withoutTraceRefs instead of their own field lists. A userIdField the exporter ignores counts as the internal id. A root lookup whose cursor repeats fails that project instead of paging forever.

In the viewer, Refresh also rereads the open record's detail, and closing the inspector after a filter removed every row returns focus to the search field.

* ⏱️ fix: One Round Trip per Trace Reference Read, Detail Reads Scoped to Their Turn

Cursors carry the anchor response's order key (creation time, then _id). The bounded sampled-response read then runs alongside the first-message lookup, with no anchor lookup ahead of it. A key that no longer names its response returns nothing, and the reader answers the cursor as changed.

Detail reads take the turn the list attributed the record to (?message=). They load only that sampled response instead of the conversation's whole history, and ask Langfuse within that turn's traces. The route rejects a detail read without it, and the client sends it from the listed record.

A list read whose Langfuse cursor repeats now fails instead of handing the next page the same records.

* 🧭 fix: Reject Out-of-range Trace Cursors, Open Any Listed Turn, Mark Copies Unsampled

A page cursor whose base-36 time parses to a number outside the Date range reached Mongoose as an Invalid Date and surfaced as a 500 the viewer retried; it now resumes nothing, which the reader reports as invalid_request so the viewer reloads its newest page.

The detail read capped the message id at the Langfuse record-id bound while the app stores response ids at any length, so a listed turn could refuse to open; message ids only name a stored row and are accepted at any length. Ids that reach a Langfuse filter keep their caps.

Copied and client-authored rows now carry langfuseSampled: false instead of no record, so a feedback score on a fork, import or posted message never recomputes sampling for a trace that was never made.

* 🧪 test: Type a Recordless Row for the Unsampled-copy Spec

An object literal with none of the trace fields fails TypeScript's weak-type check against the helper's all-optional constraint; the spec now passes a typed row that declares the optional field, as every stored message type does.

* 🚰 fix: Release Failed Langfuse Response Bodies

A non-success Langfuse response was turned into a TraceReadError without consuming or cancelling its body, and Node's fetch returns a connection to its pool only once the body is released, so a sustained upstream failure left sockets checked out until garbage collection. The body is now cancelled before the status becomes an error.
2026-09-13 00:56:52 -04:00
Danny Avila
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>
2026-09-12 23:00:10 -04:00
Danny Avila
2e1ccbb0fd
🪂 fix: Release Stalled MCP Catalog Recovery Without Dropping Refreshed Tokens (#15871)
* 🪂 fix: Release Stalled MCP Catalog Recovery Without Dropping Refreshed Tokens

Passive catalog recovery could hang forever when discovery hit an expired
OAuth access token and the refreshed tokens' authorization-fence write
stalled. The shared flight, every request coalesced onto it, and their
process-wide catalog slots waited with it until capacity was exhausted.

- Stop discovery's OAuth token wait at its deadline or abort without
  cancelling the shared token flow, so redeemed tokens still persist.
- Stop recovery waiting on a discovery once its budget plus
  `mcpSettings.catalogRecovery.discoverySettleGraceMs` (default 10s) has
  passed, releasing the flight, its joiners, and their slots with backoff.
- Add `waitUntilDeadline` for waits that must end without cancelling work.

* 🪂 test: Rediscover Once a Released Flight's Refresh Publishes

* 🪂 fix: Hold a Server's Recovery Until Its Released Discovery Settles

* 🪂 fix: Scope Released-Discovery Holds to Observed State Under a Process-Wide Limit

* 🪂 fix: Count Token Work a Discovery Hands Off at Its Deadline
2026-09-12 22:23:49 -04:00
Danny Avila
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
2026-09-12 20:45:00 -04:00
Dustin Healy
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
2026-09-12 20:23:54 -04:00
Dustin Healy
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
2026-09-12 20:23:17 -04:00
Joseph Licata
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
2026-09-12 20:14:22 -04:00
Danny Avila
037b0331f8
📇 fix: Stop an MCP Credential Refresh From Fencing Its Own Catalog Recovery (#15865)
* 📇 fix: Stop an MCP Credential Refresh From Fencing Its Own Catalog Recovery

Passive catalog recovery captures the tool-cache generation before discovering a
cold server and discards the catalog when the stored generation has moved by the
time discovery returns. A silent OAuth refresh inside that same discovery
publishes a rotation of its own and then clears this replica's recovery state,
so the tracker drops the flight as superseded and the generation check rejects
it: the server is listed with no tools, and a concurrent catalog request starts
a second discovery instead of joining the first.

The authorization fence now reaches discovery through recovery's own
dependencies, which report each generation a discovery's refresh publishes. The
tracker adopts that generation while the flight is still running, so the flight
stays current and its outcome carries the generation it produced; a rotation or
clear from any other writer afterwards still supersedes it, and a refresh that
completes after its discovery settled no longer touches that settled state.

* 🪢 fix: Keep a Recovery Flight Joinable Through Its Own Credential Publication

A refresh's authorization fence writes the new shared generation, clears local
recovery state, and only then reports what it wrote. A catalog request that read
the new generation during that span found the flight still keyed to the old
generation, or its slot vacated by the clear, and replaced it with a second
discovery; the original flight was then discarded.

Discovery now runs its publication through a tracker bracket. While a flight's
own publication is in progress the tracker holds any clear for that server and
lets requests for the same config join the flight; when it ends, the flight
adopts the generation it wrote, or applies the held clear if the publication
failed or the flight settled first. The flight is registered before its
discovery starts, so a publication can never precede its own registration.

* ⏳ fix: Bound and Count What a Recovery Flight Holds During Its Own Publication

A recovery flight held every clear for its key and admitted any request for its
server for as long as its own credential publication stayed open. A clear from
another writer collapsed into the fence's own clear and was dropped on adoption,
leaving a backoff or reauthorization decision in place after a teardown; a
publication stalled in an unbounded storage write kept every later request
joined to the stalled flight; and a joiner that had already read a foreign
generation could keep tools under an older adopted generation when the final
generation read failed.

An open publication now holds clears and admits joins only while its flight is
in flight and for at most one discovery budget, after which requests take over
as before. The fence clears local recovery once when it completes, so any other
held clear still applies after the flight adopts its generation, and every held
clear applies when the publication fails or the flight settles first. An outcome
under a generation the request never observed stands only when the final shared
generation read confirms it.

* 🧬 fix: Correlate Catalog Recovery Clears With the Generation Their Fence Wrote

Local catalog-recovery clears carried only a user and server, so the tracker
could not tell a flight's own credential publication from any other writer. It
counted clears and bounded its hold with a time window instead, which left a
request that joined before the window expired waiting on a stalled publication,
and let a late fence clear delete the flight that took over after the window.

The authorization fence now hands local recovery the generation it wrote, and a
clear spares state already recorded under that generation; a clear without one
still clears. A flight holds the clears it receives while its own publication is
open, adopts the generation that publication wrote, and then applies each held
clear against it, so its own clear is spared while a teardown or another
publication's clear still applies. Retry-intent cleanup inside the fence is
bounded by the same per-attempt timeout as the generation write, since a leftover
intent only advances the generation again, so the publication itself can no
longer hold its joiners open and no time window is needed.

* 🔏 fix: Confirm an Adopted Catalog Generation for Requests That Read None

A request whose pre-discovery generation reads both failed observed no
generation, so the confirmation rule exempted it. When that request's own
discovery refreshed credentials, adopted the generation its publication wrote,
and another replica rotated past it before a final read that also failed, the
catalog was served without ever being confirmed against shared state.

A flight's own result now records that its generation came from its own
publication, and that mark is never copied into retained state. An outcome
under a generation the request did not read needs final confirmation whenever
the request read a different generation or the generation was adopted; an outcome
whose generation the tracker merely carried over for a request that read nothing
keeps the existing fail-open behavior, so a cache outage still preserves retained
backoff and reauthorization state.

* 🧭 fix: Judge In-Flight Catalog Recovery by the Shared Generation, Not a Tagged Clear

A publication's local clear carries the generation it wrote, and the tracker
deleted any state recorded under a different one. Generations carry no order, so
a refresh that outlived its own flight could clear with an older generation and
delete a flight that had started under a newer rotation from another replica,
discarding a catalog that was still current.

A tagged clear now only signals that the shared generation advanced. A flight
still in flight under a known generation, or publishing its own credential
change, is left to the requests awaiting it, which already confirm their outcome
against the shared generation exactly as they do for a rotation from another
replica. Retained state and flights with no known generation are cleared unless
recorded under the clear's generation, and a clear without a generation still
clears unconditionally. The tracker no longer holds clears during a publication:
the refresh's own clear spares its flight directly, and the flight adopts the
generation it wrote when the publication completes.

The shared-discovery tests compared catalog maps through expect.objectContaining,
which does not compare Map contents; they now assert each request's catalog with
toEqual.

* 🧾 fix: Confirm a Catalog Flight That a Clear for Another Generation Spared

A tagged clear spares a flight still in flight, because an unordered generation
cannot say whether that flight predates the rotation. The spare was not recorded,
so when the request's final shared-generation read timed out, a flight that had
observed its own generation kept a catalog the clear may have superseded: an older
recovery whose refresh published after a replacement flight started could leave
that replacement serving tools no read ever confirmed.

A spared flight now records the generation each such clear carried and settles
against its final generation. A clear for its own generation, including its own
refresh's, changes nothing; any other marks the flight's result unconfirmed, keeps
it out of retained state, and requires every request awaiting it to confirm the
generation against the shared read before using its tools. A spared flight that
finishes with no known generation is discarded, as the clear would have done. A
tagged clear no longer spares retained state recorded under its generation.
2026-09-12 19:50:28 -04:00
Danny Avila
ddd2dd8bf4
🪢 fix: Recover a Failed MCP Server Once When Reinspections Overlap (#15867)
* 🪢 fix: Recover a Failed MCP Server Once When Reinspections Overlap

A server stored as an inspection-failed stub is recovered by the first
request that inspects it successfully, but every request that read the
stub before that write inspected again and wrote again. Each later write
bumped `updatedAt` past the connection made after the earlier one, so the
connection was replaced and a caller still holding it listed no tools. A
request that reached `reinspectServer` after the write hit the
"not in a failed state" guard and reported the server as still
unreachable.

- Share one in-flight reinspection per stored entry and effective
  allowlists in each process; DB entries are keyed per user and tenant.
- Replace the stub only while it is still the inspected stub: a new
  optional `replaceStub` compare-and-set on the in-memory and Redis
  aggregate-key stores (one Lua script), so replicas never overwrite a
  recovery another replica stored.
- Resolve a reinspection that finds the server already recovered to the
  stored config, and move the reinitialize decision into
  `MCPServersRegistry.recoverServerConfig` so `reinitMCPServer` connects
  with the recovered config instead of the stub it read.
- Pin the interleavings in `MCPReinitRecovery.integration.test.ts` against
  a real in-process MCP server, and require every concurrent reinitialize
  flow there to recover with a complete tool list.

* 🪢 fix: Key Shared Reinspections by the Stub They Inspect

A registry re-initialization can replace a failed stub while an older
reinspection of it is still running. The shared flight was keyed by
entry and allowlists only, so a request that read the newer stub joined
the older inspection and inherited its outcome without the newer config
ever being inspected.

`reinspectServer` now reads the entry before joining and keys the flight
by the stub's `updatedAt`. A flight whose compare-and-set loses to a
newer failed stub joins the inspection of that stub instead of reporting
the server unreachable, and a store that leaves the inspected stub in
place rejects rather than joining its own flight.

* 🪢 fix: Settle a Reinspection Against the Entry Stored After It

A reinspection that did not replace its stub only looked at storage when
its compare-and-set lost. Two paths reached a stale outcome:

- An inspection that failed rejected as unreachable even when another
  request had already stored a recovery, for example after capturing the
  stub before a slow allowlist resolution. Allowlists now resolve before
  the entry is read, and a failed inspection settles against the stored
  entry the same way a lost compare-and-set does.
- Returning a recovery that another replica stored left this replica's
  process-local `getAllServerConfigs` memo serving the stub until its TTL.
  Settling on a stored recovery now invalidates this replica's registry
  read caches, as the writing path does.

* 🪢 fix: Decide Reinspection Outcomes From Current Shared State

The Redis aggregate-key store answers `get` from a process-local
snapshot that can lag another replica's write by its TTL. A replica
whose inspection failed read that snapshot while settling, still saw the
stub, and reported the server unreachable although Redis held another
replica's recovery. The same stale read also sent a replica into a
needless inspection of a server another replica had already recovered.

- Add an optional `getCurrent` to the repository interface, implemented
  by the aggregate-key store as a read past its snapshot, and use it for
  the reinspection's first read and for settling.
- Inspect a newer stub within the flight that found it instead of
  joining another flight, so no flight ever waits on a second one.

* 🪢 fix: Join the Flight Already Inspecting a Newer Stub

A flight that lost to a newer failed stub inspected that stub itself even
when another request was already inspecting it. If that redundant
inspection failed transiently, the flight settled against the unchanged
newer stub and rejected its callers while the other flight went on to
store the recovery.

A flight now joins the flight for the newer stub, starting it when none
is pending, but only when the stub is strictly newer by `updatedAt`, so
every wait points forward and flights stay acyclic. A replacement that
is not newer, which only clock skew can produce, is still inspected
within the flight.

* 🪢 fix: Track Reinspection Waits Instead of Ordering Them by Clock

Joining only flights for strictly newer stubs kept waits acyclic by
relying on `updatedAt` order, which replicas with skewed clocks do not
guarantee. A replacement stored with an older timestamp was inspected
redundantly instead of joining the flight already inspecting it, and a
transient failure of that redundant inspection rejected callers the
other flight went on to recover.

Settling flights now record the flight they wait on and join any
in-flight reinspection for the stub they found, unless that flight
already waits on them directly or through others. Only a join that
would close a cycle falls back to inspecting within the settling flight.

* 🪢 refactor: Resolve the Reinitialize Config in packages/api

`reinitMCPServer` still decided in CJS what a failed-inspection config
recovers to and built the `unreachable` response itself. That decision
now lives in `resolveMCPReinitializeConfig` in packages/api, which takes
the registry as a dependency and returns either the config to connect
with or the typed result that ends the reinitialization. The CJS service
only passes request data in and returns that result.
2026-09-12 19:50:14 -04:00
Marco Beretta
5b4ec6bfe2
🔎 feat: Filter and Sort the Sidebar Chats List (#15842)
* 🔎 feat: Filter and Sort the Sidebar Chats List

The sidebar could only list every unarchived chat by last activity. Archived chats
lived behind a settings modal, sorting was not exposed at all, and the only filter
was a bookmark dropdown squeezed next to the search field.

A single control beside the Chats heading now carries the status (active or
archived), the sort field and direction, and the bookmark filter, each scoped to
that list alone: Projects, Pinned and Favorites are untouched by it.

* 🧹 fix: Answer Review Round on Sidebar Chat Filters

Rows derive their archive action from `conversation.isArchived`, which the list
projection now carries, instead of from the sidebar's filter mode: the archive view
keeps the unarchived pins beside it, and its previous page's rows outlive a status
switch, so the list mode offered to restore chats that were never archived.

Mutations reconcile the archived list caches they can now reach — rename, pin,
tags, project assignment, shared links — and archiving refetches the archived
query instead of inserting into page one, which dropped the row whenever the
active sort placed it later.

Title grouping keeps the order the server paged, heads each group with the title's
first code point, and the archive's legacy group falls back to `createdAt` the way
the cursor orders it. A failed list request renders an error with Retry rather
than "No chats yet", the status setter sanitizes a malformed stored sort, and
signing into another account no longer inherits the previous one's filters.

* 🧵 fix: Keep Sidebar Cache Writes Inside the Chosen Sort

Title groups are emitted as contiguous runs, so a `#` heading that the server's
order places either side of a letter no longer merges and drags a row across the
cursor boundary the next page continues from.

The live cache writers only reproduce newest-first, which is the one order they can
place a row in without the server's keyset. A title, created-at or ascending variant
now takes the field update in place and is refetched instead of having rows moved to
or seeded at the front of page one.

Archive and restore refetch every loaded page of the lists they touch — the archive
preserves `updatedAt`, so a restored chat can belong on a later active page — while
inactive variants are left stale rather than eagerly refetched. Archiving everything
still refetches them all, because every cached list is wrong afterwards. Renaming or
deleting a bookmark now rewrites the sidebar's selected tags, which otherwise kept
filtering by a name no menu could uncheck.

* 🗂️ fix: Treat the Archived List as a Live Conversation Cache

* 🔍 fix: Refetch List Variants Whose Membership the Client Cannot Decide

A cached search result is evaluated by the server, so a newly created row may or may
not belong in it. Skipping those variants left a mounted search list missing a row
it should show — forking from an archived search result being the case that exposed
it. The insert decision is now three-valued: insert into a variant whose membership
and order the client can reproduce, skip one the row provably does not belong to,
and refetch anything undecidable.

Forks, duplicates and imports inherit the source's archive state, so their
invalidations cover the archived list too, and the delete path reads `chatProjectId`
from archived caches as well.

* 🔎 fix: Reconcile Searched List Variants on Every Write

* 📣 fix: Announce Archive and Restore From the App Live Region

* 🧹 fix: Drop Unmounted Lists on Archive-All and Fill a Missing Archive State

Archive-all refetched every loaded page of every cached list, mounted or not, so a
session that had visited several sort, bookmark or search combinations paid a burst of
requests for lists nobody was looking at. Mounted variants still refetch all pages;
the rest are dropped, which reconciles them more thoroughly than a refetch and costs
nothing until something mounts them.

A row's own `isArchived` decides whether its menu offers Archive or Restore, and this
branch is what adds that field to the list projection — so mid-rollout, an archived
row from an older backend would offer Archive and submit a no-op. The list query now
fills a missing value from what the variant asked for, leaving an explicit one alone.

* 🧭 fix: Give Callers One Way to Reconcile Both Conversation Lists

Callers that cannot say what changed — a stream recovered after a disconnect, a
schedule whose run moved a chat, a project that took its chats' fields with it — were
invalidating the active list by hand, so a mounted archive kept a row the server had
already changed. `invalidateConversationLists` reaches both prefixes and is now the
only way those paths reconcile; `findConversationListQueries` shares its key list, so
adding a prefix is one edit rather than a sweep.

* 🔤 fix: Follow the Server Order, Index the Created Sort, and Tell the Truth When Empty

* 🎯 fix: Identify the Open Chat When a Restore Resolves

A restore leaves the chat open, so its success callback writes the new archive state
into the active conversation — but the callback captured that conversation when the
menu item was clicked. Open another chat before the request lands and the identity
check still matched the captured row, replacing the conversation the user had just
opened while the URL kept pointing at it.

The write is now a functional update that compares `conversationId` against current
state, so a stale callback leaves the open chat alone. Reading the conversation value
is no longer needed either, which also stops every row's menu from re-rendering on
conversation updates.

* 🧷 fix: Recheck the Open Route When an Archive Resolves
2026-09-12 15:56:10 -04:00
Danny Avila
5a2c4a0435
🔐 fix: Stop an MCP Credential Refresh From Fencing Its Own Connection (#15863)
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
A durable user connection captures the tool-cache publication generation before
resolving credentials, so a rotation from another replica fences the catalog it
publishes. A silent OAuth refresh performed while that same connection is being
built publishes a rotation of its own, and the build then fails the lease check
it just invalidated: the connection holding the newest credentials is torn down
and the tool call that triggered it errors with "Publication lease is no longer
current".

invalidateCachedTools now reports the generation it wrote, the authorization
publication carries it back to its caller, and a connection build adopts what
its own refresh published. A foreign rotation still moves the stored generation
past that value, so the fence keeps failing the build it was meant to fail.
2026-09-12 12:39:47 -04:00
Hao
bd08a363c4
🔣 fix: Encode Images From Storage Keys (#15851)
* fix: Prefer storage keys for image encoding

* fix: Sanitize assistant image errors

* fix: Sanitize agent image storage errors

* fix: Move blob image encoding into API package

* fix: Complete image encoder TypeScript migration

* fix: Keep request-boundary error logs diagnosable

getSafeErrorMetadata reduces an error to { type: 'Error' } and an optional
status. That is the right bound where an error may echo submitted content, and
it stays in place at getS3FileStream, getAzureFileStream and
getFirebaseFileStream, where a signed URL reaches the log.

Applied at ResumableAgentController's initialization catch and the chatV1
generic branch it blinded the whole route: a missing key, an agent that fails to
load and a database error all logged as { type: 'Error' }, with no message,
name, code or stack.

getSafeErrorText keeps the error's own description and stack, reduces every URL
to its origin so an object path and signature cannot ride along, and strips
bearer credentials. It returns text so the two handlers log it inside the
message and pass no winston metadata, which is what stops an SDK error's own
enumerable properties (request.url, config, response.headers) from being
promoted onto the record.

---------

Co-authored-by: Danny Avila <danny@librechat.ai>
2026-09-12 12:39:26 -04:00
Danny Avila
f3e2bf22a7
🧲 fix: Match Directory Users to Existing Principals (#15855)
* fix: Preserve Directory Identity Ownership

* fix: Fail Closed on Identity Conflicts

* fix: Resolve Existing Sharing Principals Safely
2026-09-12 07:36:22 -04:00
Danny Avila
1d45f5bd40
🏡 feat: Remember Agent Workspace Defaults (#15843)
* 🧭 feat: Remember Attached Workspace Choices

* Guard Workspace Defaults Across Navigation and Version Restore

* Order Workspace Preference Imports

* fix: Harden agent workspace defaults

* fix: Type workspace validation schema

* test: Cover safe execution projections

* fix: Bind workspace defaults to attached environments

* fix: Preserve unchanged workspace bindings

* fix: Scope workspace preferences to active agents

* fix: Preserve workspace selection state

* test: Target workspace discovery status

* fix: Keep workspace reset available

* fix: Resolve workspace defaults per environment

* fix: Collect per-environment workspace defaults

* fix: Reconcile Deleted Agent Graph Caches

* fix: Reject Stale Workspace Bindings
2026-09-12 05:45:16 -04:00
Danny Avila
8f13845da5
📿 fix: Inspect Stored File Locators Per Message (#15841)
Some checks are pending
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Codegraph E2E Votes / vote (full suite) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Client build recovery regression (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
Sync Locize Translations & Create Translation PR / Sync Translation Keys with Locize (push) Waiting to run
Sync Locize Translations & Create Translation PR / Create Translation PR on Version Published (push) Blocked by required conditions
* fix: inspect stored file locators per message

* fix: declare traversal diagnostics for isolated declaration builds

* refactor: inject locator traversal reporting from application callers

* fix: propagate traversal diagnostics across protected entry points

* fix: complete middleware reporters and hydration message counts
2026-09-11 16:47:48 -04:00
Marco Beretta
e2f5772961
🧮 feat: Surface Retained Tool-Message Context Usage (#15796)
Some checks are pending
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
* feat: surface retained tool-message context usage

* fix: correct post-snapshot context accounting and lockfile registry

Adjudicated the review findings on the retained tool-message context work:

- package-lock.json resolved four entries (@librechat/agents, call-bind-apply-helpers,
  es-object-atoms, get-intrinsic) from a private mirror, breaking `npm ci` outside
  that network. Restored the public registry hosts; the integrity hashes already
  match the public tarballs.
- `finalizeUsage` migrated every usage atom except `subagentUsageFamily` before
  dropping the temporary `new` key, so a first-turn subagent total vanished when
  the conversation id was assigned.
- The runway projection divided the pre-invoke `remainingContextTokens` by per-call
  growth, ignoring the output generated after that snapshot, and the compaction hint
  subtracted a post-call exchange from a pre-call message total. Both now apply the
  post-snapshot output, so each side is measured at the same point in time.
- The estimate path rendered its tool-call share as a peer row although it is a
  subset of Input/Output/Estimated, so the visible rows summed past `usedTokens`.
  It is now an indented subtotal; the counted rows stay provider-accurate.
- The Totals block presented conversation-wide session subagent usage beside
  branch-scoped rows; it is now labeled all-branches.
- Rewrote the truncated `rgb-series-8` rationale as one comment on the series block.

* fix: keep subset accounting whole across cache, legacy snapshots, and custom themes

Adjudicated the second review round on the retained tool-message context work.
One cause per finding, each measured on the same basis as what it is compared to:

- The all-branches subagent subtotal summed input+output only, so a cached
  subagent call was under-reported and a fully cached call with no output
  disappeared from the row while the Cache read/write rows above still counted
  its traffic. It now sums every normalized bucket.
- `collectAnchorSeries` read an absent `remainingContextTokens` as zero and
  recorded that snapshot as having spent its entire budget, which distorted the
  growth delta feeding the runway projection. A snapshot saved in the older
  shape now derives its used total from the breakdown, exactly as the render
  path's `baseUsed` does, and one that carries neither basis is skipped. Each
  reading is tagged with its basis and the projection compares only readings of
  the same basis instead of reporting the difference between two measurements.
- `resolveTheme` filled an omitted `rgb-series-8` from the bundled base, so a
  stored or environment theme that paints its own seven-slot scale got
  LibreChat's indigo on surfaces it never checked: 2.41:1 against that theme's
  meter track, under the 3:1 mark floor the scale claims. An owned scale now
  derives the slot from the theme's own neutral text — 11.5:1 on the same
  reference theme — and naming `rgb-series-8` still opts out.
- Ordered the `--series-*` declarations in the light block by slot.

* fix: keep cached shares out of the peer rows and track resolved text for slot 8

Third round on the retained tool-message context work, correcting the two
variants of invariants this PR already fixed elsewhere rather than patching
them locally:

- The snapshot path rendered the reconciling call's Cached and Cache write
  shares as peer rows with window percentages, although reconciliation already
  counted those tokens inside the segments above. A fully cached prompt showed
  its tokens twice and the visible rows summed past the meter. They now render
  as an indented subtotal, the same treatment the estimate path's tool-call
  share received. The existing test claimed this invariant in its name but only
  asserted the rows exist, so it now asserts they are not peers.
- The `rgb-series-8` fallback required the theme to name its own text, so a
  theme that repaints the scale and its surfaces while inheriting LibreChat's
  text colours still received the bundled indigo. It now derives from the
  RESOLVED secondary text, so the stop tracks whatever the theme reads its body
  copy against whether it names one or inherits ours.

* fix: settle the subagent share with its run and measure both reclaim sides alike

Fourth round on the retained tool-message context work:

- The subagent share was committed on arrival while the usage it is a subset of
  stayed pending, so a run that ended with no salvageable response left its
  tokens in the Totals after `resetLive` discarded them from every rollup, and a
  resume re-folded the same events into the cumulative figure. It now
  accumulates in `pendingSubagentUsageFamily` beside the pending usage and
  settles with it: committed by `flushPendingInto` when the response keeps its
  usage, dropped by `resetLive` otherwise, migrated with the conversation id.
  The view merges committed and in-flight shares, so the live row is unchanged.
- `latestExchangeTokens` subtracted a summarizing turn's whole response,
  including the summarization completion the backend folds into `tokenCount`
  while the snapshot holds it in `breakdown.summaryTokens` rather than
  `messageTokens`. The reclaim hint was understated by the summary and could
  reach zero after a long one; the summary block's size is now excluded from the
  tail's contribution when that turn compacted.
- `sumBranch` exposed the tail's char estimate and tool share even when the tail
  carried a `tokenCount`, so a resumed partial response stayed in the message
  total while its tool traffic was dropped from the Tool calls split. Both tail
  figures are now zero for a counted tail, which also stops the estimate path
  subtracting an estimate that was never summed.

* chore: drop the lockfile churn the base branch already carries

The SDK bump this PR set out to make landed on dev as 3.8.5, so the branch no
longer changes any package.json and its lockfile edits (the 3.8.4 entry plus the
transitive call-bind-apply-helpers/es-object-atoms/get-intrinsic bumps that
install pulled in) are churn against the base.

* fix: give the eighth series slot a value every bundled theme can carry

The base branch grew high-contrast palettes that must declare every registry
token, and a test that a series slot can carry `text-on-status` at the 3:1 mark
floor, because a slot also fills a badge chip under that glyph. Slot 8 failed
both: the high-contrast palettes could not name a token that did not exist when
they were written, and the dark indigo #8c98e6 carried white at 2.71:1.

Dark slot 8 is muted to #8082be, which reads 3.66:1 under the status label and
still clears 3.66:1 on every series surface. The high-contrast palettes take
their own neutral text as slot 8 — the same stop `resolveTheme` derives for a
third-party theme that paints its own scale — because seven saturated hues is
all either canvas affords at their stated CVD separation; it is distinguished
by lightness at 21:1 on the canvas instead of by hue.

* test: exercise the context split through the mock harness

Nine scenarios of the acceptance contract, one tagged Playwright test each,
driving the real application: a tool round-trip through the e2e MCP server for
the Messages/Tool calls split, its keyboard disclosure of per-tool counts, the
peer rows staying inside the meter and surviving a reload; a real subagent run
for the all-branches total; seeded conversations for the legacy snapshot whose
used figure comes from its breakdown and for the estimate path's nested tool
share; and a stored theme that owns the series scale for the eighth slot's
fallback and its opt-out.

* test: keep the tool and subagent scenarios on the viewports that expose them

* 📌 feat: Unified Pinned Section With Sidebar Drag Interactions (#15057)

* feat: unified pinned section with drag interactions and sidebar polish

- Pinned chats and favorite models/agents/specs render as one interleaved,
  reorderable list persisted via users.pinnedOrder
- Drag conversations onto project rows to file them, onto Chats to unfile,
  and onto the Pinned section to pin (empty section materializes as a drop
  zone during a conversation drag)
- Row-level unpin button on pinned chats matching the favorites' button,
  and the row action menu shares the same hover/focus treatment
- Agent Marketplace entry moved under the New Chat button in the side rail
- Bookmarks trigger sized to the search bar, search focus no longer swaps
  its border color, tag filtering shows a loading state, and opening a
  project shows row-shaped skeletons

* fix: add pinnedOrder to IUser type and sort imports

* fix: pinned drag threshold, unpin focus target, and marketplace link

* fix: surface failed pinned reorders and skip no-op order writes

* fix: address review findings on unified pinned section

Move the pinned-order endpoints into packages/api as TypeScript handlers and
route their URLs through the data-provider endpoint registry. Raise the entry
and key caps so a valid model favorite and an unbounded pin count can both be
persisted.

Keep the marketplace entry reachable from the mobile drawer, which is the only
sidebar surface on small screens. Merge a reorder into the stored order while a
bookmark filter hides part of the list, instead of dropping the hidden keys.
Add Alt+Arrow keyboard reordering with a live-region announcement, restore the
focus handoff when a favorite is removed, and hold the local arrangement until
the stored order catches up. Serialize overlapping order writes and discard the
optimistic value when the first one fails. Derive the tag-filter loading state
from isPreviousData rather than a flag that could stick on.

* fix: release drag while renaming and dedupe repeated favorite keys

A draggable ancestor swallows drag-select inside the rename input, so both the
row's own drag source and the pinned wrapper's release while a title is being
edited.

The favorites payload validator accepts a repeated entry, and two rows keyed
the same would collide in React, point every drag at the first copy, and fail
the order endpoint's uniqueness check. Build the pinned list keyed-unique.

* fix: address PR review bot findings

Make the model favorite key injective. Joining endpoint and model on '::'
collided for components containing the delimiter, so two distinct favorites
keyed the same and the dedupe hid one; the endpoint is now length-prefixed.

Replace the pinned-order entry cap with a total size guard. Pinning has no
membership cap and the sidebar query drains every cursor, so any count limit
rejects a legitimate list rather than bounding anything; what needs bounding is
the user document.

Let only the newest order write touch the cache. An earlier write failing
rolled back over a newer arrangement that was still in flight, leaving the UI
on a stale order while the server held the current one. A confirmed write now
takes the server's answer, and a failed newest write discards the value that
was never accepted.

Persist the favorites array only once the order write succeeds, so a rejected
write cannot leave the two stores disagreeing with the rolled-back display.

* fix: address second round of PR review bot findings

Read favorites membership at write time rather than capturing it at drag end.
A favorite added or removed while the order request was in flight was undone by
writing the older list back; only the relative order now comes from the drag.

Move the pinned-order queue to module scope. The sidebar unmounts whole
sections while a search is active, so a component-local ref let a remounted
hook start a second queue alongside a request that was still running.

Serialize project assignment per conversation. Every drop target owns its own
mutation instance and the write is an unconditional update, so two quick drops
let whichever request reached the database last decide the project.

Read the pinned-order request body null-safely: destructuring a nullish body
threw past the handler into Express's generic error path instead of returning
the intended 400.

* fix: address third round of PR review bot findings

Drop the secondary favorites write. No consumer of the favorites array reads
its order, so mirroring the arrangement there bought nothing while racing the
membership mutations that share that whole-array endpoint; pinnedOrder is the
single source of ordering.

Always merge the committed order into the stored one. The visible list is not
always the whole list, since a bookmark filter hides rows and the pinned query
publishes partial results while draining its cursor, and replacing wholesale
dropped every key it could not see.

Release the local arrangement when the write settles instead of when the stored
order matches it key for key. A pin arriving mid-request made that equality
unreachable, stranding the snapshot and hiding the new row until remount.

Abandon a queued pinned-order write if the signed-in user changed, so a
deferred request cannot write one account's order into another's document.

* fix: address fourth round of PR review bot findings

Guard the pinned-order completion callbacks on the signed-in account. The
pre-send check only covers a write that has not left yet; a response arriving
after a session change would publish one account's order into the next one's
cache, which this query never refetches on its own.

Commit a reorder only when the pinned rows handled the drop. Dragging a pin
onto a project row or into Chats sweeps the pointer across sibling rows, whose
hover handlers shift the order, so a filing action was also saving a move the
user never asked for.

* fix: address fifth round of PR review bot findings

Deselect pinnedOrder at schema level. It is display-only and allowed to grow
large, but every authentication request loads the user document, so it was
adding its whole payload to paths that never read it.

Refuse to reorder until the stored order has loaded. Merging against an absent
order and then cancelling its fetch posted only the visible keys and discarded
saved positions for good.

Prune keys only once the visible list is known to be the whole list. Merging
unconditionally grew the array until the size guard rejected every write, so
completeness now gates compaction rather than the filter flag alone.

Track every renaming row, not just the most recent. RenameForm has no blur
cancellation, so a second form can open while the first is still mounted and
the single key reconnected the first row's drag source under its open input.

Judge drop eligibility by the queued destination. A drag item carries the
project its row had when the drag began, so re-dropping a chat back where it
started while an assignment was queued read as a no-op.

Take mutation ownership from the user atom AuthContext fills on login rather
than the user query, which is still empty in that window, and never treat an
unknown owner as a match.

Restore the pinned section's 30vh cap. Matching the Projects section's 42vh put
84vh of non-shrinking content above Chats and starved it on short viewports.

* fix: address sixth round of PR review bot findings

Gate reordering and pruning on successful fetches rather than attempted ones.
A failed pinned-order GET still reports as fetched, and a failed later page of
the pinned drain still publishes partial data and stops fetching, so both gates
were opening on exactly the states they were meant to exclude.

Scope the post-unpin focus handoff to this section by its own marker. The whole
conversations pane is a labelled region too, and the project lists inside it
render the same row, where unpinning only clears the flag and the row stays
put, so focus was being moved off a row that never went away.

Clear the account tracker when the mutation hook unmounts. The sidebar drops
that section during a search, leaving a stale non-null id that also shadowed
the cache fallback, so a deferred write could pass its owner check after a
session change.

* fix: gate pruning on a delivered favorites list

A favorites fetch that exhausted its retries leaves isLoading false with the
list empty, so an otherwise complete pinned load enabled pruning and dropped
every favorite key from the stored order. useFavorites now exposes the query's
success state and the pruning gate requires it, matching the pinned-order and
pinned-membership sources.

* fix: address eighth round of PR review bot findings

Identify queued assignments by token rather than by destination. Comparing
destination values cannot tell two drops onto the same project apart, so a
B, A, B run let the first B's cleanup discard an entry the still-queued later
drops owned, and the next drop was then judged against a stale project.

Report the rename ending when a row unmounts. A pinned row removed mid-rename,
for instance by unpinning the same chat from the project list that also renders
it, left its key in the renaming set and came back permanently undraggable.

* fix: address ninth round of PR review bot findings

Stand the keyboard reorder down wherever the pointer drag does. Alt/Option plus
an arrow moves the caret word-wise inside a text field, so the shortcut was
moving and saving the whole row out from under an open rename input.

Hold a settled assignment destination until a drag item shows the new project.
The mutation's cache invalidations are not awaited, so a row still reported its
old project for a moment after the write succeeded and a quick drag back to
where it started read as a no-op.

* fix: address tenth round of PR review bot findings

Serialize project assignment inside the mutation instead of at one caller. The
drag targets, the row menu and the project dialog each hold their own instance,
so a queued drop could still overwrite a newer menu write; moving the queue
down covers every surface and lets the drag helper drop its own.

Tie the live snapshot's release to the arrangement that created it. An older
write settling mid-drag cleared the newer arrangement, snapping the rows back
to a stale order while the drag still held its own, so releasing saved an order
the user could no longer see.

* fix: address eleventh round of PR review bot findings

Move assignment destination tracking next to the queue that owns it. Keeping it
in the drag helper meant a menu or dialog move left the drag helper still
reporting its own older destination, with no row left to observe that would
ever clear it, so a later move back was rejected for good.

Resolve a conversation's project from the write the mutation confirmed rather
than from whichever list rendered the row. The same chat appears in the Pinned
section and its expanded project, and those caches refresh independently, so
observing one of them was never a sound way to decide the other had caught up.
The conversation cache is written synchronously on success, which makes the
lazy self-clearing and its settled flag unnecessary.

* fix: cancel an in-flight conversation refetch before confirming an assignment

Navigation invalidates the exact conversation query, so a refetch that read the
old project can be in flight when an assignment resolves and land afterwards,
reverting the move in the cache that now answers where a conversation lives.

* fix: keep queued pinned-order writes attributable across an unmount

Refuse a queued write only when a different account is positively established.
Clearing the identity on unmount stopped stale attributions but stranded work
that belonged to the same account, since the sidebar drops the section that
owns this hook whenever a search is active, and it denied that work its
rollback as well.

Correct the cache from the request rather than from onError. The observer
callbacks do not run once that section unmounts, so an order the server never
accepted could survive on a query that refetches on nothing.

* fix: publish the session identity from the user atom

Queued pinned-order writes were attributed by a tracker that only the pinned
section's hook updated, and the sidebar unmounts that section during a search.
A retained value went stale across a sign-in, and login clears the user query
before the next account's fetch resolves, so a write queued by the previous
account could pass its own check and post on the new account's credentials.

A Recoil atom effect publishes the identity instead: it runs wherever the atom
is set, including sign-out, so attribution comes from the state itself rather
than from a component that happens to be mounted. That makes a signed-out
session foreign to every owner and lets the check be a strict comparison again,
rather than a rule that had to guess when identity was merely unreadable.

* fix: discard reorders that ended on a refused external target

A drop the pinned rows did not handle usually means a reorder, but a project
row or the Chats section refusing one reports the same, so dragging a chat onto
the project it already belongs to was saving the incidental shift its pointer
caused on the way out.

The rows and those targets now report their hovers, so the last one under the
pointer settles it, which also allows for a drag that strays over a project and
returns to reorder after all.

* fix: attribute queued writes to the credentials they will travel with

Publishing the account from React state, whether an effect or a Recoil atom
effect, always lagged the credential change: setUserContext installs the new
Authorization header in one synchronous call, and a write queued by the
previous account and sent in that gap read its own owner back and went out as
the new one. A test against the atom effect showed onSet is deferred too, so
the atom was no better than the effect it replaced.

The header is the thing that decides who the server sees, so ownership is read
from it. The id claim is compared rather than the token, since a silent refresh
rotates the token for the same account and discarding that work would strand
something the user is still entitled to.

Leaves AuthContext and the user atom untouched.

* fix: attribute a reorder to the account that started it

onMutate awaits cancelQueries before the request is built, and the mutation
function was reading the session again afterwards, so credentials turning over
inside that gap sent one account's order as the next. The owner is now recorded
in onMutate's first synchronous statement and carried on the order itself, and
the optimistic write is skipped when the session moved on, since that cache is
shared and showing an order to the wrong account is the same mistake as sending
it.

Record a pinned hover before the guards rather than after. Hovering the dragged
row is a no-op for ordering but still means the pointer is inside the list, so
a drag that wandered onto a project and returned to its own position was being
discarded as a filing action.

* fix: address a further round of PR review bot findings

Mark a hover anywhere in the pinned section as internal. The header and the
padding around the rows are part of the list, so a drag that wandered onto a
project and came back to rest on one of them ran no row hover and was discarded
as a filing action.

Hold off pruning while a favorites write is unsettled. The earlier GET's
success stands through an optimistic removal, so pruning then dropped the
ordering key of a write that had not landed, and a failed one came back without
its saved position.

Declare the reorder shortcut on the elements that take focus. The section's
written hint is skipped by anyone tabbing straight to a row, leaving the only
non-pointer way to reorder undiscoverable.

* fix: reach a real New Chat control, and let the shortcut prop through the memo

The unpin fallback looked for a test id no component carries, so once the last
pinned row unmounted focus fell to the document rather than to New Chat. It now
tries the controls that exist, in sidebar order. The test that covered this had
fabricated the missing id, so it proved nothing.

Convo is memoized on conversation fields and isGenerating alone, so the
shortcut appearing once the pinned order loaded never reached the element that
announces it. The comparator now accounts for it.

* fix: identify OpenID sessions, and see favorites writes from every hook

With OpenID token reuse the bearer is the provider's own id_token, which names
its subject as sub under an issuer and carries no LibreChat id, so every such
session resolved to nobody and two different accounts compared equal. That is
the case the ownership guard exists for, so it read as safe while being exactly
wrong. Sessions are identified by whatever the credential offers now, and an
owner that cannot be identified is foreign to everything including itself.

Count favorites writes across the query client rather than from one observer.
A favorite row runs its own useFavorites, so a removal started there was
invisible to the pinned section and its ordering key could still be pruned.

* fix: close the assignment cache gap, and let a failed drain be retried

The assignment released its pending destination as soon as the request settled,
while the cache write waited on an awaited cancellation in onSuccess. A drag
started in that gap saw neither, fell back to the stale row and refused a valid
drop. The write now happens in the request, before the entry is released, which
also survives the owning component unmounting.

Also clear the pagination guard when the Chats section collapses. A drain that
exhausted its retries leaves the conversations array unchanged, so the guard
barred every later attempt and the remaining chats stayed unreachable for the
session. Reopening the section now tries once more. That guard came from #14860
rather than this branch, so it can be split out if preferred.

* fix: compose the marketplace link, and keep focus on a surviving row

The marketplace control was a raw link with restated appearance classes, and
in restating them it left out the focus ring entirely, so keyboard focus on it
was invisible. It composes through the shared button now, which carries the
ring, the hover fill and the theme timing.

Unpinning from a project list leaves the row in place but removes the pin badge
that had focus, and the pinned-section successor search deliberately returns
nothing there, so focus fell to the document. It moves to the row's own link.

Reconcile the pinned order on window focus and reconnect. It is one shared
per-user record, so a second tab would otherwise show a stale arrangement and
its next reorder would post a full array undoing the other tab's.

* fix: keep a rename from restoring a conversation's other fields

A rename request carries only a title, but its response is the whole
conversation as the server saw it, and writing all of that back restores the
pre-request value of every other field. An assignment confirmed while the
rename was in flight was therefore reverted in the cache that now answers which
project a conversation belongs to, and a drag back to the original project read
as a no-op.

Only the title and its timestamp are taken from the response. Cancelling
queries cannot help here, since this is another mutation's write rather than a
fetch.

* fix: compose the unpin badge through the shared row-action button

The badge restated a reusable icon control's sizing, radius, hover and focus
classes. The client package already had a row-action variant and an icon-xs
size that match it exactly, so it uses those instead of its own copy.

* fix: reconcile before reordering, and scope assignments to their session

A reorder stayed enabled while the order's focus refetch was in flight, so
returning to a tab could cancel that refetch and post the arrangement it was
about to replace. Pruning had the matching gap: the pinned list keeps its data
fresh for five minutes, so a tab whose order had reconciled could prune against
membership that had not, dropping the position of a conversation another tab
pinned. Both now wait for data that is settled and not stale.

Assignments carry the account that started them, like the order writes already
did. Conversation ids are per-user, so a queued one travelling with the next
account's credentials would act on whatever that id names over there, and its
answer would describe one account's conversation to another in a cache that is
not scoped by user.

The row's overflow trigger derives from the shared row-action variant too, so
the two actions in a row stop keeping separate copies of the same recipe.

* fix: reject foreign assignment results, and share the section header

An assignment settling after a session change returned normally, so the success
path still ran: the caller reported success and the response could be applied to
the next account's conversation, since ids repeat across accounts. It rejects
now, so nothing downstream treats it as a result.

The collapsible section header existed as three identical copies, Chats,
Projects and Pinned, and this branch added the third. It moves into the shared
button as a section-header variant and all three compose from it.

* fix: let favorites membership reconcile between tabs

The favorites query disabled focus, reconnect and mount refetches, so a second
tab kept its old list indefinitely. Its pruning gate waits for a fetch, and
none was ever going to happen, so a reorder there could delete the saved
position of a favorite the first tab had added. It reconciles on focus and
reconnect now, like the order it is arranged alongside.

* fix: hold reconciling refetches off while a write is in flight

Enabling focus and reconnect refetches on the order and favorites queries let
one start after onMutate's single cancellation, read the pre-write state and
land after the write, putting the old value back. Both now decline those
refetches while a write for that resource is outstanding, keeping the cross-tab
reconciliation itself.

The check asks the query client at the moment the event fires rather than
reading useIsMutating: that hook only reaches the query's options on the next
render, which is a race against the very event being gated. A test that
dispatches focus mid-write fails without it.

* fix: release abandoned assignments and gate pruning on current membership

An assignment rejected before entering the try block kept its pending entry
forever, so a later session read a destination that was never sent. The
ownership check now sits inside the block that releases it, and it runs again
after the conversation query cancellation resolves, since the session can turn
over while that await is pending.

Pruning the pinned order now requires membership at least as current as the
order it is pruned against. The pinned query holds its data for five minutes
while the order has no such window, so focusing a tab reconciled the order
alone and the next reorder dropped the key of a conversation another tab had
pinned in between.

The assignment spec resets its mocks between tests and gives each test its own
conversation id, so one test's unconsumed mock and leftover queue entries no
longer decide the next test's result.

* fix: address the sixth round of review findings on the pinned section

The section header recipe asked for the shared button variant without a size,
so CVA emitted the default `h-10 px-4` after it and the merge kept it, putting
a 40px control in a 32px header row. The variant opts out of default sizing
through a compound now, since a heading is sized by its own text.

Restore the search field's focus border. Removing it left keyboard focus
signalled only by a background change that hover already uses, so the field
had no distinguishable focus state at all.

An assignment can reach the database before a concurrent rename and still
answer after it, carrying a conversation that predates the rename. Only the
project field is merged into the cached conversation and published to the
active one now, matching what the rename handler already does.

An order refetch that starts mid drag no longer lets the drop post an array
built from the order that refetch is about to replace: the arrangement is held
and written once the fresh order lands. Reorder writes superseded by a newer
arrangement are skipped rather than sent, so holding the shortcut costs two
writes instead of one per intermediate position. The order and favorites
queries reconcile on mount as well, since a sidebar search unmounts the
section and a query with no observer never sees the focus event.

* fix: preserve pinned order until favorites membership catches up

* fix: reconcile pinned membership and preserve auth and focus state

* fix: preserve reconciled keys during active pinned arrangements

* style: sort pinned order regression imports

* fix: reconcile favorite rollbacks before pinned-order pruning

* 🧊 fix: Withhold Rerun Controls on Compaction Turns (#15797)

* 🧊 fix: Withhold Rerun Controls on Compaction Turns

A compaction turn's response parents onto the leaf it summarized, not onto a
user message, so the hover Edit's Rerun replayed an assistant message in the
user slot: the request minted a user message under the existing assistant
leaf's id and ran the turn with empty text, which fails. Editing offered
nothing either, since SUMMARY is not an editable part type.

Edit, Regenerate and Continue are now withheld on a compaction turn, and both
rerun paths refuse a parent that is not user-created, matching the guard
`useChatFunctions.regenerate` already applied.

* 🧭 fix: Gate Rerun Controls on the Replayed Parent Turn

Withholding Edit, Regenerate and Continue on summary-only content also hit an
ordinary turn that auto-summarized and was cancelled before its first answer
token: that response is parented to the user's message and is exactly the turn
a rerun is for. The row now resolves the message it would replay and withholds
the rerun shapes only when a model turn hangs off another model turn, which is
the manual compaction shape. An unresolvable parent withholds nothing.

`isCompactionTurn` is gone with it, and `isCompactedLeaf` keeps its original
body; its docstring now says per part what it always measured per part.

* 🧮 fix: Identify a Compaction Turn by Content and Parent

Gating the rerun controls on parent authorship alone withheld Edit, Regenerate
and Continue from any model turn hanging off another model turn. An imported
conversation chains messages sequentially, so a skipped empty human message
leaves an ordinary reply parented to the previous reply; its stored content is
editable and its controls must stay. It also made every model row resolve its
parent out of the flat message list: 100 full-thread scans while mounting a
200-message conversation.

A manual compaction is now both halves of its shape — summary-only content and
a parent that is not the user's turn — so only such a row consults the thread.
`isSummaryOnlyContent` is the content half, in data-provider next to
`isCompactedLeaf`.

* 🧷 test: Pin the Rerun Refusal on a Chained Model Turn

A rerun replays its parent as the user turn, so a model turn parented onto
another model turn must submit nothing rather than mint a user message under an
existing response's id. Removing the guard makes the case call `ask` once.

* 🧱 fix: Gate the Editor on Content and the Rerun on the Parent

Identifying a compaction turn by content shape missed the ones the server
persists with an error part (a skipped or failed compaction keeps its
explanation instead of a summary), which left Edit, Regenerate and Continue on
a turn where every rerun shape is inert.

The two controls answer two different questions now. A rerun replays the
message's parent as the turn's user message, so Regenerate and Continue go
whenever a model turn hangs off a model turn. The editor goes only when that
turn also has no part to type in: an imported chain's reply is saved directly
and stays editable, while a compaction — summary or error part — would open an
empty editor with one inert Rerun.

`findMessageById` indexes the messages array once per identity, so resolving
the parent no longer scans the thread per row: 100 full-array walks while
mounting a 200-message conversation become one.

* 🏷️ fix: Honor the Server's Compaction Marker on Any Leaf

Compact runs on whatever leaf the branch ends with, so a compaction can hang off
a user message rather than off the answer it summarized. Inferring the turn from
its position alone left the rerun controls on that one: replaying the parent
would answer the user's earlier message again instead of redoing the compaction.

`isUserInitiatedCompaction` reads the marker the server already stamps —
`markCompactionSummary` sets `initiatedBy: 'user'`, and nothing else writes it,
so an automatic summary detour keeps its controls. A marked turn is excluded
from the rerun shapes wherever it hangs.

* 🎨 fix: Ask the Editor What It Can Edit

The hover row had its own idea of an editable part and counted artifact-bearing
text as one, while `EditContentParts` keeps an artifact in its read-only
renderer. A chained model turn whose only content is an artifact therefore still
offered Edit, and opening it gave a read-only artifact, a disabled Save and a
Rerun the guards refuse.

`editableParts.ts` now owns that rule for both: `isEditablePart` is the
editor's own filter, `hasEditablePart` asks it per message. The row resolves it
lazily — the artifact check parses markdown, and only a turn with nothing to
replay needs the answer — so a streaming row never pays for it.

* 🚫 fix: Withhold the Editor's Rerun Instead of Refusing It

Both editors resolved the parent inside the handler and returned when it was not
a user turn, so a chained model turn — an imported thread with no user message
between two replies — kept an enabled Rerun that did nothing, with Ctrl/Cmd+Enter
bound to it.

Each editor resolves that parent at render and withholds the action instead: the
button is gone, the shortcut is inert and `aria-keyshortcuts` no longer advertises
it, while Save keeps writing the edit. An unresolvable parent keeps the action,
matching the hover row.

* 🧹 style: Sort the New Imports in Both Editors

CI's import-sort check failed on the two files the previous commit touched.

* 💬 fix: Report Unsaved Changes When No Rerun Is Offered

A save-only editor still warned about the rerun. An answer's draft is discarded
by the rerun, and multi-part edits must be saved before one, but neither is true
where the action is withheld — a model turn chained onto another model turn — so
the status slot claimed a precondition for something the footer does not offer.

Both statuses are gated on the same `canRerun` the button is: the plain-text
editor reports unsaved changes, and `rerunRequiresSave` cannot hold without a
rerun to require it.

* 🧪 test: Exercise the Compaction Controls in the Browser

Eight mock-harness scenarios drive the real row and the real editors: a
finished, failed, error-part and user-parented compaction withhold Edit,
Regenerate and Continue while Copy stays; a turn that only auto-summarized
keeps all three; a reply chained onto a reply keeps a save-only editor whose
status reports unsaved changes; an artifact-only chained reply loses the
editor; and the context indicator still offers Compact after a failed
compaction.

`SeedMessage` carries `content`, `finish_reason` and `model` so a branch can be
seeded in the shapes the mock model cannot produce — a persisted summary, an
error part, an artifact.

* 🩻 feat: improve agent filter controls for insights (#15807)

* feat(insights): improve agent filter controls

* feat(insights): add search and fixed agent selection controls

* fix(insights): show search before all agents control

* test(e2e): allow steer consumption before arm response

* 🔠 fix: Name Artifact Downloads After Their Titles (#15836)

* fix: Use artifact titles for download filenames

* fix: Match artifact filenames to downloaded content

* fix: Preserve raw artifact extensions and GFM headings

* fix: Download complete artifact files and retain filename provenance

* fix: Distinguish cached artifact exports from originals

* fix: Name unnamed artifact originals by their media type

* fix: Recognize legacy CSV MIME in artifact filenames

* fix: preserve context insights across reloads and configuration changes

* fix: retain primary call details when resuming context snapshots

* fix: preserve resumed output and retained tool-result estimates

* fix: keep resumed output compatible with older clients

---------

Co-authored-by: Ravi Kumar L <upman@users.noreply.github.com>
Co-authored-by: Danny Avila <danny@librechat.ai>
2026-09-11 15:53:29 -04:00
Marco Beretta
e75835e327
📌 feat: Unified Pinned Section With Sidebar Drag Interactions (#15057)
* feat: unified pinned section with drag interactions and sidebar polish

- Pinned chats and favorite models/agents/specs render as one interleaved,
  reorderable list persisted via users.pinnedOrder
- Drag conversations onto project rows to file them, onto Chats to unfile,
  and onto the Pinned section to pin (empty section materializes as a drop
  zone during a conversation drag)
- Row-level unpin button on pinned chats matching the favorites' button,
  and the row action menu shares the same hover/focus treatment
- Agent Marketplace entry moved under the New Chat button in the side rail
- Bookmarks trigger sized to the search bar, search focus no longer swaps
  its border color, tag filtering shows a loading state, and opening a
  project shows row-shaped skeletons

* fix: add pinnedOrder to IUser type and sort imports

* fix: pinned drag threshold, unpin focus target, and marketplace link

* fix: surface failed pinned reorders and skip no-op order writes

* fix: address review findings on unified pinned section

Move the pinned-order endpoints into packages/api as TypeScript handlers and
route their URLs through the data-provider endpoint registry. Raise the entry
and key caps so a valid model favorite and an unbounded pin count can both be
persisted.

Keep the marketplace entry reachable from the mobile drawer, which is the only
sidebar surface on small screens. Merge a reorder into the stored order while a
bookmark filter hides part of the list, instead of dropping the hidden keys.
Add Alt+Arrow keyboard reordering with a live-region announcement, restore the
focus handoff when a favorite is removed, and hold the local arrangement until
the stored order catches up. Serialize overlapping order writes and discard the
optimistic value when the first one fails. Derive the tag-filter loading state
from isPreviousData rather than a flag that could stick on.

* fix: release drag while renaming and dedupe repeated favorite keys

A draggable ancestor swallows drag-select inside the rename input, so both the
row's own drag source and the pinned wrapper's release while a title is being
edited.

The favorites payload validator accepts a repeated entry, and two rows keyed
the same would collide in React, point every drag at the first copy, and fail
the order endpoint's uniqueness check. Build the pinned list keyed-unique.

* fix: address PR review bot findings

Make the model favorite key injective. Joining endpoint and model on '::'
collided for components containing the delimiter, so two distinct favorites
keyed the same and the dedupe hid one; the endpoint is now length-prefixed.

Replace the pinned-order entry cap with a total size guard. Pinning has no
membership cap and the sidebar query drains every cursor, so any count limit
rejects a legitimate list rather than bounding anything; what needs bounding is
the user document.

Let only the newest order write touch the cache. An earlier write failing
rolled back over a newer arrangement that was still in flight, leaving the UI
on a stale order while the server held the current one. A confirmed write now
takes the server's answer, and a failed newest write discards the value that
was never accepted.

Persist the favorites array only once the order write succeeds, so a rejected
write cannot leave the two stores disagreeing with the rolled-back display.

* fix: address second round of PR review bot findings

Read favorites membership at write time rather than capturing it at drag end.
A favorite added or removed while the order request was in flight was undone by
writing the older list back; only the relative order now comes from the drag.

Move the pinned-order queue to module scope. The sidebar unmounts whole
sections while a search is active, so a component-local ref let a remounted
hook start a second queue alongside a request that was still running.

Serialize project assignment per conversation. Every drop target owns its own
mutation instance and the write is an unconditional update, so two quick drops
let whichever request reached the database last decide the project.

Read the pinned-order request body null-safely: destructuring a nullish body
threw past the handler into Express's generic error path instead of returning
the intended 400.

* fix: address third round of PR review bot findings

Drop the secondary favorites write. No consumer of the favorites array reads
its order, so mirroring the arrangement there bought nothing while racing the
membership mutations that share that whole-array endpoint; pinnedOrder is the
single source of ordering.

Always merge the committed order into the stored one. The visible list is not
always the whole list, since a bookmark filter hides rows and the pinned query
publishes partial results while draining its cursor, and replacing wholesale
dropped every key it could not see.

Release the local arrangement when the write settles instead of when the stored
order matches it key for key. A pin arriving mid-request made that equality
unreachable, stranding the snapshot and hiding the new row until remount.

Abandon a queued pinned-order write if the signed-in user changed, so a
deferred request cannot write one account's order into another's document.

* fix: address fourth round of PR review bot findings

Guard the pinned-order completion callbacks on the signed-in account. The
pre-send check only covers a write that has not left yet; a response arriving
after a session change would publish one account's order into the next one's
cache, which this query never refetches on its own.

Commit a reorder only when the pinned rows handled the drop. Dragging a pin
onto a project row or into Chats sweeps the pointer across sibling rows, whose
hover handlers shift the order, so a filing action was also saving a move the
user never asked for.

* fix: address fifth round of PR review bot findings

Deselect pinnedOrder at schema level. It is display-only and allowed to grow
large, but every authentication request loads the user document, so it was
adding its whole payload to paths that never read it.

Refuse to reorder until the stored order has loaded. Merging against an absent
order and then cancelling its fetch posted only the visible keys and discarded
saved positions for good.

Prune keys only once the visible list is known to be the whole list. Merging
unconditionally grew the array until the size guard rejected every write, so
completeness now gates compaction rather than the filter flag alone.

Track every renaming row, not just the most recent. RenameForm has no blur
cancellation, so a second form can open while the first is still mounted and
the single key reconnected the first row's drag source under its open input.

Judge drop eligibility by the queued destination. A drag item carries the
project its row had when the drag began, so re-dropping a chat back where it
started while an assignment was queued read as a no-op.

Take mutation ownership from the user atom AuthContext fills on login rather
than the user query, which is still empty in that window, and never treat an
unknown owner as a match.

Restore the pinned section's 30vh cap. Matching the Projects section's 42vh put
84vh of non-shrinking content above Chats and starved it on short viewports.

* fix: address sixth round of PR review bot findings

Gate reordering and pruning on successful fetches rather than attempted ones.
A failed pinned-order GET still reports as fetched, and a failed later page of
the pinned drain still publishes partial data and stops fetching, so both gates
were opening on exactly the states they were meant to exclude.

Scope the post-unpin focus handoff to this section by its own marker. The whole
conversations pane is a labelled region too, and the project lists inside it
render the same row, where unpinning only clears the flag and the row stays
put, so focus was being moved off a row that never went away.

Clear the account tracker when the mutation hook unmounts. The sidebar drops
that section during a search, leaving a stale non-null id that also shadowed
the cache fallback, so a deferred write could pass its owner check after a
session change.

* fix: gate pruning on a delivered favorites list

A favorites fetch that exhausted its retries leaves isLoading false with the
list empty, so an otherwise complete pinned load enabled pruning and dropped
every favorite key from the stored order. useFavorites now exposes the query's
success state and the pruning gate requires it, matching the pinned-order and
pinned-membership sources.

* fix: address eighth round of PR review bot findings

Identify queued assignments by token rather than by destination. Comparing
destination values cannot tell two drops onto the same project apart, so a
B, A, B run let the first B's cleanup discard an entry the still-queued later
drops owned, and the next drop was then judged against a stale project.

Report the rename ending when a row unmounts. A pinned row removed mid-rename,
for instance by unpinning the same chat from the project list that also renders
it, left its key in the renaming set and came back permanently undraggable.

* fix: address ninth round of PR review bot findings

Stand the keyboard reorder down wherever the pointer drag does. Alt/Option plus
an arrow moves the caret word-wise inside a text field, so the shortcut was
moving and saving the whole row out from under an open rename input.

Hold a settled assignment destination until a drag item shows the new project.
The mutation's cache invalidations are not awaited, so a row still reported its
old project for a moment after the write succeeded and a quick drag back to
where it started read as a no-op.

* fix: address tenth round of PR review bot findings

Serialize project assignment inside the mutation instead of at one caller. The
drag targets, the row menu and the project dialog each hold their own instance,
so a queued drop could still overwrite a newer menu write; moving the queue
down covers every surface and lets the drag helper drop its own.

Tie the live snapshot's release to the arrangement that created it. An older
write settling mid-drag cleared the newer arrangement, snapping the rows back
to a stale order while the drag still held its own, so releasing saved an order
the user could no longer see.

* fix: address eleventh round of PR review bot findings

Move assignment destination tracking next to the queue that owns it. Keeping it
in the drag helper meant a menu or dialog move left the drag helper still
reporting its own older destination, with no row left to observe that would
ever clear it, so a later move back was rejected for good.

Resolve a conversation's project from the write the mutation confirmed rather
than from whichever list rendered the row. The same chat appears in the Pinned
section and its expanded project, and those caches refresh independently, so
observing one of them was never a sound way to decide the other had caught up.
The conversation cache is written synchronously on success, which makes the
lazy self-clearing and its settled flag unnecessary.

* fix: cancel an in-flight conversation refetch before confirming an assignment

Navigation invalidates the exact conversation query, so a refetch that read the
old project can be in flight when an assignment resolves and land afterwards,
reverting the move in the cache that now answers where a conversation lives.

* fix: keep queued pinned-order writes attributable across an unmount

Refuse a queued write only when a different account is positively established.
Clearing the identity on unmount stopped stale attributions but stranded work
that belonged to the same account, since the sidebar drops the section that
owns this hook whenever a search is active, and it denied that work its
rollback as well.

Correct the cache from the request rather than from onError. The observer
callbacks do not run once that section unmounts, so an order the server never
accepted could survive on a query that refetches on nothing.

* fix: publish the session identity from the user atom

Queued pinned-order writes were attributed by a tracker that only the pinned
section's hook updated, and the sidebar unmounts that section during a search.
A retained value went stale across a sign-in, and login clears the user query
before the next account's fetch resolves, so a write queued by the previous
account could pass its own check and post on the new account's credentials.

A Recoil atom effect publishes the identity instead: it runs wherever the atom
is set, including sign-out, so attribution comes from the state itself rather
than from a component that happens to be mounted. That makes a signed-out
session foreign to every owner and lets the check be a strict comparison again,
rather than a rule that had to guess when identity was merely unreadable.

* fix: discard reorders that ended on a refused external target

A drop the pinned rows did not handle usually means a reorder, but a project
row or the Chats section refusing one reports the same, so dragging a chat onto
the project it already belongs to was saving the incidental shift its pointer
caused on the way out.

The rows and those targets now report their hovers, so the last one under the
pointer settles it, which also allows for a drag that strays over a project and
returns to reorder after all.

* fix: attribute queued writes to the credentials they will travel with

Publishing the account from React state, whether an effect or a Recoil atom
effect, always lagged the credential change: setUserContext installs the new
Authorization header in one synchronous call, and a write queued by the
previous account and sent in that gap read its own owner back and went out as
the new one. A test against the atom effect showed onSet is deferred too, so
the atom was no better than the effect it replaced.

The header is the thing that decides who the server sees, so ownership is read
from it. The id claim is compared rather than the token, since a silent refresh
rotates the token for the same account and discarding that work would strand
something the user is still entitled to.

Leaves AuthContext and the user atom untouched.

* fix: attribute a reorder to the account that started it

onMutate awaits cancelQueries before the request is built, and the mutation
function was reading the session again afterwards, so credentials turning over
inside that gap sent one account's order as the next. The owner is now recorded
in onMutate's first synchronous statement and carried on the order itself, and
the optimistic write is skipped when the session moved on, since that cache is
shared and showing an order to the wrong account is the same mistake as sending
it.

Record a pinned hover before the guards rather than after. Hovering the dragged
row is a no-op for ordering but still means the pointer is inside the list, so
a drag that wandered onto a project and returned to its own position was being
discarded as a filing action.

* fix: address a further round of PR review bot findings

Mark a hover anywhere in the pinned section as internal. The header and the
padding around the rows are part of the list, so a drag that wandered onto a
project and came back to rest on one of them ran no row hover and was discarded
as a filing action.

Hold off pruning while a favorites write is unsettled. The earlier GET's
success stands through an optimistic removal, so pruning then dropped the
ordering key of a write that had not landed, and a failed one came back without
its saved position.

Declare the reorder shortcut on the elements that take focus. The section's
written hint is skipped by anyone tabbing straight to a row, leaving the only
non-pointer way to reorder undiscoverable.

* fix: reach a real New Chat control, and let the shortcut prop through the memo

The unpin fallback looked for a test id no component carries, so once the last
pinned row unmounted focus fell to the document rather than to New Chat. It now
tries the controls that exist, in sidebar order. The test that covered this had
fabricated the missing id, so it proved nothing.

Convo is memoized on conversation fields and isGenerating alone, so the
shortcut appearing once the pinned order loaded never reached the element that
announces it. The comparator now accounts for it.

* fix: identify OpenID sessions, and see favorites writes from every hook

With OpenID token reuse the bearer is the provider's own id_token, which names
its subject as sub under an issuer and carries no LibreChat id, so every such
session resolved to nobody and two different accounts compared equal. That is
the case the ownership guard exists for, so it read as safe while being exactly
wrong. Sessions are identified by whatever the credential offers now, and an
owner that cannot be identified is foreign to everything including itself.

Count favorites writes across the query client rather than from one observer.
A favorite row runs its own useFavorites, so a removal started there was
invisible to the pinned section and its ordering key could still be pruned.

* fix: close the assignment cache gap, and let a failed drain be retried

The assignment released its pending destination as soon as the request settled,
while the cache write waited on an awaited cancellation in onSuccess. A drag
started in that gap saw neither, fell back to the stale row and refused a valid
drop. The write now happens in the request, before the entry is released, which
also survives the owning component unmounting.

Also clear the pagination guard when the Chats section collapses. A drain that
exhausted its retries leaves the conversations array unchanged, so the guard
barred every later attempt and the remaining chats stayed unreachable for the
session. Reopening the section now tries once more. That guard came from #14860
rather than this branch, so it can be split out if preferred.

* fix: compose the marketplace link, and keep focus on a surviving row

The marketplace control was a raw link with restated appearance classes, and
in restating them it left out the focus ring entirely, so keyboard focus on it
was invisible. It composes through the shared button now, which carries the
ring, the hover fill and the theme timing.

Unpinning from a project list leaves the row in place but removes the pin badge
that had focus, and the pinned-section successor search deliberately returns
nothing there, so focus fell to the document. It moves to the row's own link.

Reconcile the pinned order on window focus and reconnect. It is one shared
per-user record, so a second tab would otherwise show a stale arrangement and
its next reorder would post a full array undoing the other tab's.

* fix: keep a rename from restoring a conversation's other fields

A rename request carries only a title, but its response is the whole
conversation as the server saw it, and writing all of that back restores the
pre-request value of every other field. An assignment confirmed while the
rename was in flight was therefore reverted in the cache that now answers which
project a conversation belongs to, and a drag back to the original project read
as a no-op.

Only the title and its timestamp are taken from the response. Cancelling
queries cannot help here, since this is another mutation's write rather than a
fetch.

* fix: compose the unpin badge through the shared row-action button

The badge restated a reusable icon control's sizing, radius, hover and focus
classes. The client package already had a row-action variant and an icon-xs
size that match it exactly, so it uses those instead of its own copy.

* fix: reconcile before reordering, and scope assignments to their session

A reorder stayed enabled while the order's focus refetch was in flight, so
returning to a tab could cancel that refetch and post the arrangement it was
about to replace. Pruning had the matching gap: the pinned list keeps its data
fresh for five minutes, so a tab whose order had reconciled could prune against
membership that had not, dropping the position of a conversation another tab
pinned. Both now wait for data that is settled and not stale.

Assignments carry the account that started them, like the order writes already
did. Conversation ids are per-user, so a queued one travelling with the next
account's credentials would act on whatever that id names over there, and its
answer would describe one account's conversation to another in a cache that is
not scoped by user.

The row's overflow trigger derives from the shared row-action variant too, so
the two actions in a row stop keeping separate copies of the same recipe.

* fix: reject foreign assignment results, and share the section header

An assignment settling after a session change returned normally, so the success
path still ran: the caller reported success and the response could be applied to
the next account's conversation, since ids repeat across accounts. It rejects
now, so nothing downstream treats it as a result.

The collapsible section header existed as three identical copies, Chats,
Projects and Pinned, and this branch added the third. It moves into the shared
button as a section-header variant and all three compose from it.

* fix: let favorites membership reconcile between tabs

The favorites query disabled focus, reconnect and mount refetches, so a second
tab kept its old list indefinitely. Its pruning gate waits for a fetch, and
none was ever going to happen, so a reorder there could delete the saved
position of a favorite the first tab had added. It reconciles on focus and
reconnect now, like the order it is arranged alongside.

* fix: hold reconciling refetches off while a write is in flight

Enabling focus and reconnect refetches on the order and favorites queries let
one start after onMutate's single cancellation, read the pre-write state and
land after the write, putting the old value back. Both now decline those
refetches while a write for that resource is outstanding, keeping the cross-tab
reconciliation itself.

The check asks the query client at the moment the event fires rather than
reading useIsMutating: that hook only reaches the query's options on the next
render, which is a race against the very event being gated. A test that
dispatches focus mid-write fails without it.

* fix: release abandoned assignments and gate pruning on current membership

An assignment rejected before entering the try block kept its pending entry
forever, so a later session read a destination that was never sent. The
ownership check now sits inside the block that releases it, and it runs again
after the conversation query cancellation resolves, since the session can turn
over while that await is pending.

Pruning the pinned order now requires membership at least as current as the
order it is pruned against. The pinned query holds its data for five minutes
while the order has no such window, so focusing a tab reconciled the order
alone and the next reorder dropped the key of a conversation another tab had
pinned in between.

The assignment spec resets its mocks between tests and gives each test its own
conversation id, so one test's unconsumed mock and leftover queue entries no
longer decide the next test's result.

* fix: address the sixth round of review findings on the pinned section

The section header recipe asked for the shared button variant without a size,
so CVA emitted the default `h-10 px-4` after it and the merge kept it, putting
a 40px control in a 32px header row. The variant opts out of default sizing
through a compound now, since a heading is sized by its own text.

Restore the search field's focus border. Removing it left keyboard focus
signalled only by a background change that hover already uses, so the field
had no distinguishable focus state at all.

An assignment can reach the database before a concurrent rename and still
answer after it, carrying a conversation that predates the rename. Only the
project field is merged into the cached conversation and published to the
active one now, matching what the rename handler already does.

An order refetch that starts mid drag no longer lets the drop post an array
built from the order that refetch is about to replace: the arrangement is held
and written once the fresh order lands. Reorder writes superseded by a newer
arrangement are skipped rather than sent, so holding the shortcut costs two
writes instead of one per intermediate position. The order and favorites
queries reconcile on mount as well, since a sidebar search unmounts the
section and a query with no observer never sees the focus event.

* fix: preserve pinned order until favorites membership catches up

* fix: reconcile pinned membership and preserve auth and focus state

* fix: preserve reconciled keys during active pinned arrangements

* style: sort pinned order regression imports

* fix: reconcile favorite rollbacks before pinned-order pruning
2026-09-11 10:41:05 -04:00
JOJO
0354db3b57
🔌 fix: Close Leaked HTTP Server in Server Specs (#15821)
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
`csp.spec.js`, `index.spec.js` and `index.metrics.spec.js` boot the real
server with `require('~/server')`; `index.js` calls `app.listen` at module
scope and exports only the app, so the specs never closed the listening
socket. In-band runs (`--runInBand`, or `maxWorkers: '50%'` on a 2-vCPU
runner) then never exit: every test passes and Jest waits on the leaked
server until the workflow timeout.

Capture the server through a spy on `express.application.listen` that
keeps the real implementation, and await `server.close()` in `afterAll`
before stopping MongoMemoryServer.
2026-09-10 15:17:06 -04:00