Commit graph

208 commits

Author SHA1 Message Date
Marco Beretta
caeb786e97
🔀 feat: Show the Conversation Pull Request in the Sidebar List (#16815)
* feat: Show the Conversation Pull Request in the Sidebar List

Add a batch lookup route and a sidebar row mark: the state icon with the CI dot, opening the same card beside the row on hover. The row keeps the conversation's own title.

* fix: Address Review Findings on the Sidebar Pull Request Batch and Row Mark

Cap the whole batch with a configurable deadline, make the row mark a keyboard-reachable button that opens the card on focus, refresh rows when the window regains focus through the shared batch, and show a retryable failure state instead of treating a failed first lookup as no pull request.

* fix: Send Sidebar Pull Request Batches One at a Time

Queue every batch request behind the one before it, so an oversized list or an overlapping flush cannot multiply the server's configured lookup concurrency, and bound how long one request may hold the queue so a request that never answers cannot stop the rest.

* fix: Keep the Batch Request Timeout Above the Server Deadline

Default the client's request timeout to just past the longest batchTimeoutSeconds a deployment may configure, so a queued request never starts while the previous request's server-side lookups are still running.

* fix: Keep Batch Lookups Inside the Concurrency Limit and Per-Entry Failures Per Entry

Share one lookup limiter across every batch request so lookups that outlive a request's deadline keep their slot, answer a missing token only for the conversations that needed it, and point the row at its pull request description only while that text is in the page.

* fix: Bound Batch Reads, Scope Concurrency Per Credential, and Gate the Sidebar on the Batch Version

Start the batch deadline when the request arrives and bound the config and lane reads, count lookup slots per credential, advertise a batch route version and ask only a server that has it, take no row space for an absent mark, show a failed refresh over a cached empty answer, keep a malformed response from stalling the request queue, and repair the lane recording tests that still used a mock removed on dev.

* fix: Move Capability Resolution Into the Package and Harden the Batch Route and Queue

Resolve the pull request startup capabilities in packages/api so the route stays wiring only, bound the config and lane reads by the configured deadline, merge identical lanes before taking limiter slots, fall back to the single route when a replica has no batch route, and dispose the batch queue when the signed-in user changes.

* fix: Abort the Batch Fallback With Its Request So the Queue Never Overlaps It

Give the batch fetcher the request's abort signal and pass it to every single-route call, abort a request that times out or is disposed, and stop the fallback workers from starting more calls once it has.

* fix: Forward the Abort Signal to the Batch POST

Pass the request's abort signal through the batch fetcher, the data-provider call and Axios, so a batch request that times out or is disposed is cancelled instead of continuing beside the next one, and settle a request promptly when it is aborted.

* fix: Close the Pull Request Lookup Follow-Ups and Cancel Abandoned Sidebar Rows
2026-10-07 12:36:57 +02:00
Marco Beretta
14c43138c2
🖥️ feat: Show Lia on the Welcome Screen (#16684)
* feat: Show Lia on the Welcome Screen

Adds the opt-in Show Lia setting (off by default) and the interface.mascot deployment flag (allowed by default). Lia mounts only on the landing page, loads lazily after first paint, stands on the composer's top edge clear of the greeting, reacts to typing, files and theme changes, and speaks through localized bubbles. She is decorative and hidden from assistive technology.

* fix: Keep Lia's Long-Message Reaction Re-Armed and Pointer Reads Per Frame

Deleting a message back under 280 characters now re-arms the long-message reaction, pointer handling reads layout at most once per animation frame, and the ChatView specs stub Lia like their other children.

* test: Open Settings from the Phone Drawer in the Lia Scenarios

The opt-in scenario no longer resets the stored preference on reload, and both Settings scenarios open the account menu from the mobile drawer on phones.

* fix: Measure Lia's Caret Like the Composer and Label Her When Idle

The caret mirror copies direction, alignment, indentation, wrapping and box sizing, so right-to-left and wrapped text measure like the composer. Hovering Lia between activities now says she is hanging out instead of showing nothing.

* fix: Wave Off Assistants Sends and Keep Lia's Canvas and Bubble Off Welcome Content

* fix: Keep Lia's Speech Bubble Inside Her Stage

* fix: Wrap Long Translations in Lia's Speech Bubble

* fix: Keep Lia's Long-Message Reaction Until It Plays and Pin the Scenario Greeting

* fix: Make Only Lia's Body Clickable So She Fits Beside Long Greetings

* fix: Let Lia Stand Beside the Composer When the Greeting Fills Its Top

* feat: Let Users Drag Lia Around and Keep Her Near the Composer

* test: Cover Picking Lia Up and Setting Her Down on the Composer

* refactor: Keep Lia's Preference Inside Her Feature

* fix: Let Keyboard Users Pet Lia and Move Her With the Arrow Keys

* test: Shift Only the Wall Clock for Lia's Morning Greeting

* test: Measure Lia's Keyboard Walk Both Ways So the Greeting's Width Cannot Pin Her

* fix: Bring Lia Back When a New Chat Opens During Her Farewell

* fix: Start Lia's Reactions on Her Own Clock After a Pause Without Room

* fix: Load Lia Through Stale-Asset Recovery and Skip the Farewell Before She Appears

* feat: Mark the Lia Settings Toggle as Beta
2026-10-06 22:55:30 +02:00
Marco Beretta
ae44437e16
🗂️ feat: Record Lane Git State and Serve Conversation Pull Requests (#16793)
* feat: Record Lane Git State and Serve Conversation Pull Requests

A conversation now stores the branch, head and repository its code lane last reported, written only by the server after a finished bash command and excluded from ordinary reads, generic saves, unset fields and imports. GET /api/convos/:conversationId/pull-request finds the pull request for that branch through an injected GitHub source with a bounded cache, answers null for an absence, and maps failures to stable codes without upstream text. The feature is off unless endpoints.agents.pullRequests is enabled with a token reference.

* fix: Address Review Findings on Pull Request Lookup and Lane Writes

Scope the lookup cache, shared in-flight request and rate limit cooldown to the credential, so one tenant's token never serves another. Ask for open pull requests on their own before falling back to the newest closed one, read every page of check runs up to a bound and never report an incomplete rollup as passing, order lane writes per conversation so an older write cannot land last, and name both required token permissions in the example config.

* fix: Address Second Round Review Findings on Pull Request Lookup

Clear the stored lane when the conversation moves to another workspace or leaves attached execution, so the previous workspace's pull request is never served. Fence the lane write on the time it was reported, so an older report from another replica cannot replace a newer one. Honor GitHub's reset window up to an hour instead of ten minutes, and expose the request timeout, whole lookup timeout and check run page limit as endpoints.agents.pullRequests settings with the previous values as defaults.

* fix: Authorize Pull Request Repositories and Fence Lane Writes

Require an administrator allowlist of repositories before the server token is used, since a worker reports its own repository. Match a pull request to the commit the conversation last ran at, so a reused branch name does not return another pull request. Fence the lane write on the workspace the command ran in, so a write queued before a move cannot bring the old lane back, and record a subagent thread's lane on the visible root conversation. Key the lookup cache and shared request by the recorded commit and the lookup policy, and document the worker flag in the example config.

* fix: Order Lane Reports by a Database Sequence and Tighten Head Matching

Replace wall clock ordering of lane reports with a per conversation counter reserved in the database when the command settles, so replica clock skew cannot reject a newer report. Treat a pull request whose head is behind the recorded commit as no match, and expose the candidate and comparison bounds of the history search as settings. Read the app config and the owner scoped lane together, inject the HTTP transport from the route instead of falling back to a global, skip a report identical to the last one written, and name the Contents permission that commit comparison needs.

* fix: Queue Lane Reports by the Visible Conversation and Read Checks for the Current Head

Order lane report reservations by the conversation the write lands on, so two subagent threads of one conversation share a chain, and write every report instead of skipping a repeat, since another recorder may have changed the lane in between. Read a pull request's detail before its check runs and use the head it reports, so line counts, mergeability and checks describe one commit. Treat an expired temporary chat as gone when reserving, writing and reading the lane, and make the shared cache capacity a setting.

* fix: Fence Lane Reports by Attachment Epoch and Place Recorders Before Reporting

Strip dotted descendants of lane fields from saves and imports, partition the pull request cache per credential, resolve the lane write target when the tool is created, and fence reports with a codeAttachmentEpoch that advances only on an owner move or detach.

* fix: Fence Subagent Lane Reports by the Root Epoch and Cover Forks and Moved Heads

Read the visible root's attachment epoch for a subagent report, gate lane recording on pullRequests.enabled, make the credential partition bound a config field, revalidate the detail head against the recorded commit, and find fork pull requests through the recorded commit.

* fix: Keep the Credential Cache Bound Deployment Wide and Budget Head Revalidation

Apply the largest configured credential bound to the shared cache, count cache hits as use, spend the comparison budget on a moved head, and fix the data-provider config default test.

* fix: Cool Down Headerless Secondary Rate Limits

A 403 whose message names a secondary rate limit now starts the credential cooldown for at least a minute instead of being cached as a ten second failure.
2026-10-06 09:56:22 +02:00
Danny Avila
0fea0240d6
⏳ feat: Reset Balance Allowances Without Rollover (#16781)
* feat: add periodic balance reset without rollover

* fix: synchronize balance policy before periodic reset

* style: preserve context balance class order

* fix: Synchronize Reset Policy Before Granting Allowances

* fix: Apply Current Balance Policy During Admission
2026-10-05 11:44:00 -04:00
Danny Avila
3f442e4dbe
🪶 perf: Load Tool-Call Previews and Fetch Full Parts on Demand (#16753)
* 🧾 perf: Load Tool-Call Previews and Fetch Full Parts on Demand

Long agent conversations shipped every tool output, argument string and
subagent transcript on load, though the cards render collapsed: 12-18 MB
of message JSON per chat, enough to crash iPhone Safari tabs.

A client that adds ?toolPreviews=1 to the conversation load now receives
bounded previews of settled tool calls (start and end of long outputs,
JSON arguments and outputs kept valid with only their longest strings
shortened, exit-status trailers kept whole, subagent transcripts omitted)
with explicit markers and full lengths. Opening a card or a subagent
panel fetches the stored part from a new owner-scoped endpoint,
GET /api/messages/:conversationId/:messageId/parts/:partIndex, cached
under its own React Query key. Clients that do not ask, exports and share
links keep the full payload; bounds are configurable under
toolCallPreviews in librechat.yaml, and a client-authored message that
carries previews is refused rather than saved.

* 🧾 fix: Validate Part Reads in Parallel and Preview Fork Responses

The full-part read now starts beside conversation-access validation
instead of after it, and keeps the active-job fallback the conversation
read has, so a conversation still live before its first save can expand
its previews. Fork, duplicate and shared-link fork responses honor the
preview parameter, so they no longer seed the conversation cache with
the full history. Background-task results whose structure cannot fit a
valid JSON preview go whole, image cards keep their prompts, and the
subagent panel offers a retry when its stored part fails to load.

* 🧾 fix: Key Hydrated Parts by Preview Revision and Call Identity

A fetched part is now cached under the preview's revision and replaces
only the fields the server shortened, so a call whose stored output
changes later (a harvested background result) is fetched again rather
than rolled back. Part lookups carry the run-step and agent identity and
refuse an ambiguous fallback, since provider tool-call ids can repeat
within one response. A subagent that finished without final text has
its transcript omitted like any other settled call, and JSON nested past
a fixed depth falls back to a text preview; a call whose preview fails
is sent whole instead of failing the conversation load.

* 🧾 fix: Release Hydrated Parts With Their History and Bound JSON Work

Full tool-call parts fetched for a conversation are removed when its
message history is released or cleared, so they cannot outlive it under
their own key. The structure-preserving JSON preview now bails out before
cloning when the value has more nodes or strings than could ever fit,
keeps a __proto__ key as ordinary data, and the part endpoint accepts any
safe-integer index instead of an arbitrary ceiling.

* 🧾 fix: Count Property Names Before Cloning a JSON Preview

Property names are never shortened, so the pre-check now adds their
length to its budget and falls back to the text preview before any
cloning when they alone could not fit.

* 🧾 fix: Preview Artifact and Branch Responses and Rehydrate Subagent Prompts

Artifact edits and parallel-response branches merge the message the
server returns into the conversation cache, so both requests now ask
for previews and their routes honor it. The subagent panel reads the
prompt from the stored arguments once they load, and the part endpoint
no longer caps identifier length, so any previewed call can be fetched.

* 🧾 fix: Preview Only Tool Calls That Can Be Fetched Back by Identity

A call without an id has nothing but its position to name it, and the
position can shift on the client, so it is left whole instead of being
previewed. The part endpoint now requires a tool-call id, so an indexed
lookup always confirms the call it returns.

* 🧾 fix: Fetch Parts by Exact Identity and Preview Only Unique Ones

The part endpoint now finds a call by its exact identity (provider id,
run-step id, agent) instead of trusting the client's index, and the
preview pass only shortens calls whose identity is unique in their
message, so every preview names exactly one stored part. Legacy
web-search failures that carry their error phrase mid-output go whole,
since the collapsed card reads that phrase anywhere.

* 🧾 fix: Bound the JSON Fit Walk Before Queueing and Normalize Empty Identities

The structure check now counts an array's or object's children against
the node budget before queueing them, so a very wide value is refused
without building a work list its size. An empty run-step or agent id is
treated as absent by the part lookup, matching how the preview pass and
the client already treat it.

* 🧾 fix: Key Fetched Parts to the Stored Version and Hydrate Search Details

Each preview now carries `previewRevision`, when its message last
changed, and the client keys fetched parts to that plus a fingerprint of
the whole preview, so any change to the stored call is fetched again.
The web-search details card asks for the stored call when it opens, so
its query is never left shortened.

* 🧾 fix: Cache Fetched Parts by Identity and Hold Copy Until Hydrated

The part query key drops the client-side index, which only rides along in the request; the server locates the call by message and exact identity, so a shifted index serves the cached copy instead of downloading it again. Copy controls inside a previewed part are disabled until the stored content arrives, so a slow or failed fetch cannot export shortened text.

* 🧾 fix: Shape Shared Forks With the Recipient's Bounds and Keep JSON Numbers Exact

A shared-link fork resolves the share owner's config for its content checks, but the forked conversation belongs to the requester, so its preview bounds now come from the requester's tenant and role (prepareResultToolCallPreviews). A structure-preserving JSON preview now requires every number in the text to survive a parse and re-serialization as the same value; an integer past 2^53, an out-of-range exponent or an over-precise decimal falls back to the text preview (or the whole output for parsed-output tools) instead of showing a changed value.
2026-10-05 07:42:45 -04:00
Marco Beretta
c6e5f98552
⚙️ fix: Default Running Chat Rename to On (#16769)
interface.runningChatRename now defaults to true, so a running chat or a placeholder-title chat can be renamed without a librechat.yaml override. Set it to false during a rolling upgrade from a version without title ownership.
2026-10-05 06:47:22 -04:00
Danny Avila
82cde522f2
💳 feat: Show Balance in the Context Gauge as Credits, Currency, or Percent (#16762)
* 💳 feat: Show Balance in the Context Gauge as Credits, Currency, or Percent

Move the balance out of the account menu into the composer's context gauge,
below the context window, and add `balance.display` (credits | currency |
percent, default credits) to choose how it reads. Currency reuses
`interface.currency` at 1,000,000 credits per USD; percent shows only the
share of the period's allotment spent.

Settings > Account > Billing renders the same summary from the same hook, so
both surfaces show identical figures, bar and refill timing in every mode.

* 🧭 fix: Normalize the Balance Display Mode and Reuse a Fresh Reading on Hover

Admin overrides reach the client without schema validation, so an unknown
`balance.display` now reads as credits instead of being typed as a mode it is
not. Hovering the gauge mounts the balance reader each time the card opens; a
30 s stale window stops every hover from refetching, while the explicit
refetch after each turn still bypasses it.

* 🩹 fix: Restore Gauge Popover Fixes and Tighten Balance States

The popover extraction was written from a pre-sync read of TokenUsage, so it
dropped dev's viewport caps and scrolling, the hideOnInteractOutside close fix,
the Tailwind v4 outline-hidden rename, and the card's max-w-full; restore them.

Refill copy now says when a refill becomes available rather than promising a
deposit, since one lands only once the interval has passed and a charge would
exhaust the balance. An empty balance reads as fully used even without an
allotment, percent mode without one says usage is unavailable instead of
leaving the figure blank, the balance-only ring takes the balance tone (amber
until empty) and is a meter only once it has a value.

* 🪙 fix: Read a Non-Positive Refill Amount as No Auto-Refill in Settings

The server never refills when the amount is not positive, and the balance
summary already says so; Settings showed its load error instead.

* 💸 fix: Show the Insufficient-Funds Error in the Balance Display Mode

The token-balance error still printed raw credit figures, so `percent` leaked
the numbers it hides and `currency` mixed units with the gauge. It now reads
the same display mode and formatter as the balance summary: credits as before,
money in currency mode, no figures in percent mode.

The auto-refill settings row also renders its own loading and failure states,
since settings search can show it without the balance row beside it.

* 🎚️ fix: Keep Fractional Credits and Drop the Moved Popover's Suppression

Credit amounts keep up to two decimals, so an insufficient-funds message no
longer reads 100.4 against 100.3 as 100 against 100; whole amounts still print
without decimals.

The design-rule backlog may not follow code into a new file, so the extracted
popover uses the standard `transition` utility instead of the arbitrary
`transition-[opacity,transform]` (which also misses Tailwind v4's separate
`translate` and `scale` properties) and its suppression is removed. The
composer geometry spec now reads the classes from `Popover.tsx`, where the
gauge button lives.
2026-10-05 06:46:44 -04:00
lia-by-librechat[bot]
af35fe5439
🪚 chore: Deprecate Agent Chain Authoring (#16745)
* feat: consolidate orchestration into a native tool

* test: complete persisted subagent graph fixture

* fix: keep orchestration pickers inside the modal focus scope

* chore: deprecate agent chain authoring

* fix: preserve runtime-equivalent legacy handoff classification

* test: stabilize orchestration dialog lifecycle coverage

* test: wait for stream completion before final title polling

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-10-04 17:36:13 -04:00
Danny Avila
3e4b01834f
🫗 perf: Release Message Histories of Conversations the User Has Left (#16747)
* 🫗 perf: Release Message Histories of Conversations the User Has Left

Long agent conversations hold 12-18 MB of message JSON each in the React Query cache, and the default 5-minute cacheTime kept every conversation visited in that window. Switching between a few of them on mobile Safari grew the JS heap past 300 MB and crashed the tab.

retainMessages tracks when each per-conversation history loses its last observer and releases it once it has no observers, is not fetching, is not pinned, and is either older than 60 s or beyond the single most recently left conversation. The routed conversation, conversations with a running job, and conversations awaiting an approval decision stay pinned; releases wait while any mutation is pending. Returning to a released conversation refetches its history.

* 🫗 fix: Own History Collection, Configure the Grace, and Pin by Server State

Per-conversation histories get an infinite cacheTime while retention runs, so React Query's own five-minute collection can no longer drop a history a running job still pins; newly seeded histories schedule a pass; the grace and recent count come from interface.historyCacheTtlMs and interface.historyCacheRecent; the approval pin is replaced by the active-jobs set, which already lists jobs paused for a live approval; and Assistants histories stay pinned because deletion reads their thread id from the cache.

* 🫗 fix: Re-arm Collection for Histories Already Counting Down and Recheck Pins Promptly

A history left before retention started still had React Query's five-minute GC timer; a momentary observer now re-arms it under the infinite cacheTime. Histories kept only because they are pinned or fetching are judged again after 5 s instead of a full TTL, so a run that ends releases its transcript promptly.

* 🫗 fix: Exempt Assistants Histories Without Polling and Leave Fetching Histories Alone

Assistants histories are now exempt rather than pinned, so they are kept without a recurring recheck timer. The startup re-arm skips histories with a fetch in flight, since detaching a momentary last observer would cancel the request; settling the fetch re-arms collection on its own.
2026-10-04 15:45:18 -04:00
lia-by-librechat[bot]
0e3c9088f6
🫰 feat: Configure Tool Approval Modes Per Agent (#16707)
* 🫰 feat: Configure Tool Approval Modes Per Agent

* fix: Fence Remembered Tool Approval Authority

* fix: Unify Tool Approval Execution Invariants

* fix: Revalidate Learned Approval at MCP Invocation

* fix: Preserve One-Time MCP Review at Invocation

* fix: Execute Reviewed Calls on Templated MCP Connections

* fix: Scope Approval Witnesses to Executing Agents

* fix: Retain Approval Bindings for Hook-Rewritten Inputs

* fix: Pin Review Authority and Retire Settled Tool Calls

* fix: Fingerprint Effective MCP Request Headers

* fix: Preserve Routing Around Renewable MCP Token Fragments

* fix: Bind Tool Consent to OAuth Credential Generations

* test: Keep Mobile Approval Save Outside Drawer Escape Race

* fix: Fence OAuth Consent at MCP Transport Retries

* fix: Let Shared Agent Viewers Reset Personal Consent

* fix: Preserve Renewed Consent Across Reset Races

* fix: Resolve Verified Aliases for Personal Tool Reset

* fix: Fence Renewed OAuth Consent and Credential Review

* fix: Require Foreground Execution for Review-Only MCP Calls

* fix: Pin Invocation Ownership and Stable MCP Consent

* fix: Fence Superseded Tool Consent Completion Writes

* fix: Scope Consent Epochs to Effective MCP Authentication

* fix: Scope Approval Admission to Reachable Agent Tools

* fix: Preserve Approval Epochs for Runtime-Detected OAuth

* fix: Address Tool Approval Review Findings

* fix: Preserve Captured Consent When Tool Approval Is Inherited

* fix: Preserve Approval Admission Through Lazy Metadata

* fix: Fence Programmatic Reviews and Unresolved Lazy Approval Keys

* fix: Account for Normalized and Skill-Contributed Lazy Tools

* fix: Scope Lazy Approval to Selected Tool Spellings and Servers

* fix: Honor Disabled MCP Capability During Lazy Approval Admission

* test: Preserve Approval Merge Regressions After Rebase

* fix: Preserve One-Time Review During Non-OAuth Grant Outages

* fix: Retain One-Time Consent Across Resume Recovery

* fix: Preserve Reviewed Consent Through Transport Outages

* fix: Preserve Case-Variant Lazy Approval Hook Admission

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-10-04 13:14:48 -04:00
lia-by-librechat[bot]
19092e55bd
🖲️ fix: Enable Running Chat Menus and Preserve Renamed Titles (#16697)
Reconciles current dev while preserving manual title ownership, existing menus, and configuration regressions.

Co-authored-by: Lia <lia@librechat.ai>
2026-10-03 23:17:15 -04:00
Danny Avila
2b4e5b5acd 🎐 perf: Coalesce Ready Background Completions by Default 2026-10-03 17:56:14 -04:00
Marco Beretta
fb1dd57a9b
🔓 feat: Remember Tool Approvals Per Conversation (#16557)
* feat: Remember Tool Approvals Per Conversation

Adds an opt-in "Always allow" choice to the tool approval card. When
endpoints.agents.toolApproval.allowAlways is true, the server marks eligible
paused calls with allow_always; approving with scope "session" stores that
exact tool name on the conversation, and later runs in the same conversation
fold the stored names into the policy as exact-name allow entries.

The server enforces every step: the resume route rejects a session scope the
pause did not offer, eligibility is rechecked against the live policy before
storing, the list is written only through an owner-scoped bounded method, and
generic saves and imports cannot set or clear it. Admin deny and ask rules and
programmatic hooks still win, stored names are ignored under dontAsk or when
the flag is off, and native code tools stay under the code approval picker.
The flag defaults to false, so existing deployments keep prompting.

* fix: Share the Effective Approval Policy and Persist Allows After Resume Fences

Offering, resume re-check, scheduled admission and createRun now read one
policy from buildEffectiveToolApprovalPolicy: endpoint rules healed against
MCP alias spellings, then the conversation's remembered tools. A call held by
a healed ask rule is no longer offered "Always allow", and a scheduled fire
whose known tools are all remembered is no longer rejected as pause capable.

The remembered-tools cap and name length cap move to
toolApproval.allowAlwaysMaxTools and allowAlwaysMaxToolNameLength (defaults
64 and 256). The card stops offering the choice for new tools once the cap is
reached instead of silently approving once.

The resume route stores remembered tools only after the schedule and project
context fences pass; a storage failure still approves the call once.

* fix: Offer Always Allow Only When It Will Hold

Offer allow_always only when storing the name would auto-approve the next
identical call on the run's own path: every MCP spelling of the tool passes
the healed static policy and no programmatic or plugin approval hook can
apply to it (the pause payload does not record which hook asked).

Remembered names now expand to every alias spelling of the same tool, and a
deny or ask on any spelling keeps the tool ineligible. A table-driven spec
walks the invariant through the real hook wiring.

* fix: Recheck Approval Hooks Before Remembering a Resumed Approval

The resume-time eligibility recheck now applies the same programmatic and
plugin PreToolUse hook check as marking, with a hook context built from the
resume request and the live plugin hook source. A hook registered after the
pause turns the choice into a one-time approval: nothing is stored and the
resume continues.

Document that toolApproval.allowAlways should be enabled only once every
replica supports it, since older replicas ignore the choice.

* fix: Judge Always Allow Offers Against the Run's Live Aliases and Active Cap

* fix: Charge Only New Tool Names Against the Remembered Approval Cap

* fix: Recheck Remembered Approvals Against the Paused Run's Aliases

* chore: Sort Imports in Agent Run After Rebase
2026-10-03 11:47:32 +02:00
lia-by-librechat[bot]
4217b9898a
🏋️ fix: Bound Host File Edits Outside the API Event Loop (#16677)
* fix: bound host file edit work outside the API event loop

* fix: reject host edit replies past their monotonic deadline

* fix: preserve bounded host edits and sanitize startup failures

* fix: account permitted full-context edits without redundant scans

* fix: preserve sandbox write cancellation as an abort

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-10-02 20:54:46 -04:00
lia-by-librechat[bot]
0c5e1ce67f
📕 fix: Explain Native Web Search Permission Denials (#16691)
Co-authored-by: Lia <lia@librechat.ai>
2026-10-02 20:11:20 -04:00
Danny Avila
1a8d23e1ed
✅ feat: Default Machine Selection and Linked-Worktree Lanes On (#16678)
* ✅ feat: Default Machine Selection and Linked-Worktree Lanes On

Per-chat machine choice from an agent's saved allowlist and linked-worktree
lane routing were both opt-in, so neither worked until a deployment found and
set its flag. Both are now on unless set to false: machine choice still only
applies to agents with a saved allowlist, and lanes still require a worker
that advertises git_linked_worktree. One helper per flag in data-provider
decides the default for every server reader and the advertised client config.

* feat: Advertise the Code Environment Decision Protocol by Default

Per-chat machine choice needs the conversation decision protocol, which the
client requires before offering allowlisted machines, but the protocol was
only advertised when CODE_ENVIRONMENT_DECISION_VERSION=1. With selection on
by default, authors could save an allowlist the composer never offered.
An unset or blank value now advertises protocol v1; any other value, such as
0, keeps the legacy-safe path.

* fix: Turn Machine Choice Off With the Decision Protocol Opt-Out

CODE_ENVIRONMENT_DECISION_VERSION=0 stopped advertising the protocol but
routing still accepted a non-default machine, so a cached tab or a direct
client could persist a choice during a mixed-version rollout. Machine choice
is recorded through that protocol, so isCodeEnvironmentSelectionEnabled now
requires both, for routing and for the advertised endpoints config. The
protocol resolver moves to code/protocol.ts (re-exported from code/config)
so execution and endpoints can use it without an import cycle.

* style: Format checkout routing regression cases

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-10-02 20:08:35 -04:00
lia-by-librechat[bot]
bb0543fd15
📼 fix: Replay Running Subagent Activity (#16541)
* 📼 fix: Replay Running Subagent Activity

* 📼 fix: Preserve Activity Across Rollouts and Reconnects

* 📼 fix: Backfill Missing Foreground Activity

* 📼 fix: Fence Replay and Drain Admitted Activity

* 📼 fix: Close Subagent Replay Review Gaps

* 📼 fix: Resume Activity After Replay Recovery Expires

* 📼 fix: Use Singular Subagent Omission Copy

* 📼 fix: Preserve Public Replay and Displayed Activity

* 📼 fix: Write Expanded Live Activity Before Queuing

* 📼 fix: Track Disjoint Subagent Replay Coverage

* 📼 fix: Preserve Tool Details and Omission Totals

* 📼 fix: Recover Tool Timing During Replay Backfill

* 📼 fix: Reconcile Covered Replay Timing Metadata

* 📼 fix: Restore Message Phases During Replay Backfill

---------

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

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

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

* 🔏 fix: Protect PII on Denial and Abort Paths

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

* test: cover preliminary private metadata in disconnect fixture

* test: carry preliminary metadata in resume controller fixture

* test: preserve Stop prerequisite identity in tenant fixture

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

* fix: preserve trusted PII placeholders through provider inspection

* fix: coordinate protected turns across Stop and native sharing

* fix: Preserve Private Text Admission and Query Lifecycles

* fix: Track Private Query Effect Dependencies

* fix: Fence Protected Admission and Screenshot Targets

* fix: Share Protected Admission and Preserve Native Token Trust

* test: Wait for Private Message Concurrency Indexes

* fix: Preserve Protected Admission Across Recovery and Titles

* fix: Coordinate Protected Root Admission and Early Stop

---------

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

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

* fix: Preserve Graph Machine Choices And Reference Lifecycles

* fix: Explain Graph Workspace Requirements And Validate Machine Choices

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

* test: Keep Unauthorized Machine Duplication Mocks Isolated

* fix: Preserve Graph Agent Machine Ownership And Explain Requirements

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

* test: Wait For Verified Generation Readiness In Native Canaries
2026-10-02 08:38:14 -04:00
lia-by-librechat[bot]
59b772f132
🥽 feat: Configure Attached Defaults and Honor Skill Read Ranges (#16540)
* feat: configure attached command and read defaults

* fix: separate programmatic timeout defaults from ceilings

* fix: retain attached programmatic schema instructions

* fix: honor explicit skill and sandbox read ranges

* fix: remove duplicate command imports after rebase

* fix: retrieve complete sandbox text before paging

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-10-01 19:57:08 -04:00
Marco Beretta
345a20fe3a
🪟 feat: Undock the Artifacts Pane into Its Own Window (#15911)
* 🪟 feat: Undock the Artifacts Pane into Its Own Window

The artifacts pane could only live in the chat's side panel, so viewing an
artifact meant giving up half the conversation and there was no way to put it on
a second screen. A header action now moves the pane into a separate browser
window and back.

The pane stays in the chat tab's React tree and is portaled into the popup's
document, so artifacts keep streaming into it and docking back is a re-render
rather than a reload. Everything a portal does not carry is mirrored: the host
stylesheets (re-synced for lazy chunks, HMR and CSSOM-only rules), the resolved
theme, a base URL for relative assets, and Sandpack's frame messages, which
would otherwise never reach the listener the opener installed.

* 🪟 fix: Keep the Artifacts Pane Whole When It Changes Windows

Review of the undock change surfaced one cause behind most of its findings: the
pane is a new component instance in every host, so anything a mount decides was
lost or wrongly reset when it moved.

- The code editor buffer now carries the artifact it belongs to, so a remount
  restores unsaved text instead of falling back to the persisted content, and
  the edit the debounce never got to send is handed to the mutation on mount.
  The share hosts take one provider around every branch for the same reason.
- The artifact registry is cleared by the host that owns it: the pane keeps it
  while it only changes windows, and leaving the route wipes it, so no artifact
  follows the user to a shared conversation.
- Fullscreen exits through the document that owns the container, Mermaid pan
  listens where its canvas lives, and Copy reports success only once the write
  resolves, with a toast when it does not.
- Style mirroring compares what a sheet actually contains: rules a page inserts
  through the CSSOM are serialized, and a rewrite the observer saw refreshes its
  clone even when nothing measurable changed.
- A child-activity panel opened while the pane is undocked stays open; the two
  panels are exclusive only while they compete for the side panel.

Adds the scenario suite for the window behaviors (`@scenario:` tagged) plus unit
coverage for the registry lifetime, the panel slot and buffer ownership.

* 🧭 fix: Carry the Artifacts Tab Across a Window Change

The pane's active tab lived in the component instance, so undocking from the
code tab landed the user back on the preview — with their unsaved text out of
sight, which reads as losing it. The tab is pane state now, next to the editor
buffer it belongs with, and the scenario asserts both survive the move.

* 🧹 chore: Drop Unused Imports From the Presentation Spec

* 🎯 fix: Bound the Artifacts Pane's Shared State to Its Session

The second review round found the cost of state that outlives an instance, all
in the seams the first round opened.

- Download now reads the editor buffer only when it belongs to the artifact on
  screen, so selecting another artifact cannot export the previous one's edits.
- The active tab is reset when the pane session ends — close or conversation
  change — instead of following a later artifact onto the code tab.
- A mutation started by a previous pane instance can no longer report back, so
  the mount releases the stale "mutating" flag before handing over the restored
  text; otherwise the edit queued behind a completion that never arrives.
- The undocked window's size and position are read while it still has them, in
  its `pagehide`, so closing through the browser remembers the bounds too.
- Docking from the window moves focus to the control that replaces the one the
  user pressed, which a keyboard user otherwise loses to the document.
- The share host keeps one `EditorProvider` mounted across the closed and open
  branches, so opening the overlay no longer remounts the transcript.

* 🎨 fix: Paint the Undocked Window Before Its Sheet Arrives

A mirrored stylesheet is a fetch, so the popup showed its default white canvas
for that moment — plain against a dark app, and visible to the scenario as a
transparent pane. The host's resolved surface colour is now the `var()`
fallback in the popup's own layout sheet, so the window opens on the app's
canvas and the real token takes over when it lands.

The two scenarios that read settled state — the painted canvas, and a keyboard
Enter that closes the window it was pressed in — now wait for it instead of
sampling the first frame.

* 🔭 fix: Focus the Dock Target Once the Pane Has Mounted\n\nThe focus handoff ran before the pane rendered its toolbar, so the control it\nwas meant to focus did not exist yet and the request was never spent. It now\nwaits for the mount that creates that control.

* 🧩 fix: Give the Edit Pipeline and the Transcript One Owner Each

Round three found the same shape three more times: work that belongs to a
session was still decided by an instance or by a branch.

- The editor no longer infers whether a previous instance's save is running.
  React Query keeps a mutation's callbacks on the mutation, so that request
  settles the shared flag itself; the new instance waits for idle and submits
  the restored buffer once, instead of clearing a flag it does not own and
  resubmitting against an `original` the earlier request may have replaced.
- The shared conversation keeps its transcript in one place — always the first
  panel of the resizable group — so opening the pane, undocking it or docking
  it again changes only the pane's host, not the transcript's ancestry.
- The clipboard fallback runs in the pane's own document, so an undocked pane
  on a deployment without the Clipboard API can still copy instead of only
  reporting failure.

* 🧷 fix: Tie the Editor Buffer and Focus to the Pane Session

Round four found the last places where the retained buffer and the focus
handoff were decided by a code path rather than by the session boundary.

- Closing the pane discards the buffer, the tab and any pending focus request,
  so reopening an artifact starts from what is saved instead of restoring — and
  silently resubmitting — text the user abandoned.
- Only the buffer an instance inherits at mount is drained. Navigating back to
  an artifact restores its own unsaved text in the editor instead of writing
  the persisted content over it, which used to queue that content behind the
  edit and undo it.
- Closing the window through the browser hands focus back exactly as the Dock
  control does, rather than leaving a keyboard user on the document body.
- The clipboard fallback restores focus by capability rather than `instanceof`,
  which never matches across the popup's realm.

* 🔐 fix: Make Undocking Configurable and Its Saves Session-Bound

- `interface.artifactUndocking` is a `configSchema` field, default enabled, so a
  deployment that cannot use popups keeps the docked pane. The hosts resolve it
  — the chat host from the startup config, the shared host from the shared-link
  config, which now carries the flag — and hand it to the pane through the
  context it already takes, rather than the pane reading config itself.
- A save carries the editing session it was started in. React Query keeps its
  callbacks after the editor is gone, and those callbacks used to write the
  buffer a closed session had just cleared and submit its queued edit; they now
  stop at a session boundary, so a closed pane mutates nothing and leaves no
  text behind for the next one.

* ✂️ fix: Stop the Editor from Overwriting Another Artifact's Unsaved Text

- A write this component makes into the Monaco model comes back through
  `onChange` exactly like a keystroke. Restoring an artifact's text therefore
  looked like typing and keyed the shared buffer to the artifact now on
  screen — so selecting another artifact before the debounce fired replaced
  the text the first one was still holding, and returning to it showed the
  persisted content. The value written here is now recognised and consumed,
  and the retained buffer is sent deliberately when its artifact comes back,
  which is where its cancelled debounce finally becomes a save.
- The save lock is the session's, not a request's. A save that outlives its
  session no longer clears the lock or the failure notice a later session
  took, and ending a session releases it — while an edit typed behind a lock
  whose owner is gone is sent by the editor holding it as soon as the lock is
  free, instead of waiting for the user to type again.

* 🔔 fix: Report Failures in the Window the User Is Looking At

The app's toast surface is mounted once in the chat tab, so a notice raised
from the undocked pane — a copy that no clipboard path accepted, for
instance — appeared in a document nobody was looking at. The window now
carries a Radix toast provider and viewport of its own around the portaled
pane; the toast state is shared, so the same notice is shown wherever the
user is rather than routed by hand at each call site.

* 🚧 fix: Offer Undocking Only Once the Deployment Has Answered

An absent config read as enabled, which is the default, but a config request
in flight reads the same way: a user could undock during that window and the
arriving answer would then take the Dock control away with it. Both hosts now
treat an unanswered config as no capability, and the pane keeps the control
that docks it whenever it is undocked, so a capability that disappears cannot
strand the pane in a window with no way back.

* 🎯 fix: Land Queued Edits, the Config Toggle and Focus on the Window

- A queued edit is sent against the content the artifact actually holds. The
  save that held the lock has already replaced what that edit was typed
  against, so submitting the captured `original` had the endpoint reject the
  newest text and leave it in the buffer alone.
- `interface.artifactUndocking` now survives interface loading:
  `loadDefaultInterface` rebuilds the object property by property, so the flag
  never reached `/api/config` or the shared-link payload and a deployment that
  set `false` still saw the control.
- Undocking hands focus to the pane the way docking already did. The control
  the user pressed goes away with the docked toolbar, so a keyboard user was
  left on the empty document of the window that had just opened; the focus
  request is now a move in either direction, which is what it is named after.

* 🔓 fix: Let the Request Own the Save, Not the Session

The save lock was a flag the editor set and cleared, which gave two ways to
be wrong: a callback whose session had ended cleared a lock the next session
was waiting on, and ending a session released a lock whose request was still
running — so a pane reopened mid-save could start a second read-replace-save
against content the first request was about to change.

The state is now the request's. The artifact save carries a mutation key and
`isMutating` is read from React Query's mutation cache, so it is true exactly
while a save is in flight, whoever started it: nothing to release, nothing to
leave behind, and an editor that appears mid-save queues its edit and sends it
— rebased on the content that landed — once the request settles.

* ⏱️ test: Give the Undocked Preview Time to Compile

* 📌 fix: Rebase a Queued Edit on What the Save Actually Wrote

The artifact registry catches up when the edited message propagates, not when
the save returns, so an edit sent in between was rebased on content the server
had already replaced and the endpoint rejected it. The text the last save wrote
is on the request itself: the drain reads it from the keyed mutation in React
Query's cache and falls back to the registry only when there is no save to
speak of. The same applies to a buffer inherited at mount, which is submitted
against that record too.

* 🧷 fix: Keep the Pane's Tab and Its Storage Off the Instance

Both findings of the review at a03ee0f7 are the same shape as the ones before
them: something the pane needs was reached for where it does not survive.

- The tab is pane state, but the reset that keeps it honest was an instance
  ref. A host change mounts a new pane, so that ref started empty, read the
  artifact already on screen as freshly opened and wrote `preview` back —
  undocking and docking both returned the user to the preview, which reads as
  the code they were editing having been thrown away. The marker moves to the
  atom beside the tab it guards, and ends with the pane session like the rest
  of it. Opening a *different* artifact still returns to the preview.

- `localStorage` was reached for at the call site. A policy that denies Web
  Storage throws from the getter itself, before the guard around `getItem`
  could run, so undocking threw instead of falling back to default bounds and
  the redock and teardown paths threw on their way home — stranding the pane in
  a window whose control the user had just pressed. Both helpers take the window
  and touch storage inside their own guard.

The scenario that should have caught the tab defect asserted `aria-checked`
once, which matches the frame before the reset lands, so it is polled now.

* 🧪 test: Drop the Denied-Storage Scenario the Shell Cannot Support

Verification at c94e5ef showed the scenario asserting a capability LibreChat
does not have: denying Web Storage in the browser replaces the page with the
error boundary ("denied") before the pane's controls are reachable, so the
popup never opened and the test timed out in all three projects.

The finding behind it was about one call site — the pane reaching for
`source.localStorage` outside the guard around its `getItem` — and that stays
fixed and covered by the unit tests in `undockedWindow.spec.ts`, which
reproduce the throwing getter and fail without the fix.

Surviving denied storage app-wide is the shell's problem, not the pane's, and
is tracked at berry-13/LibreChat#41. The spec says why the scenario is absent
so it is not added back.

* 🔗 fix: Match the Artifact Trigger's Name as Dev Now Builds It

The scenarios opened the artifact by its full accessible name, spelled out as
"<title> Click to open". Dev's "Unify Artifact Triggers as Tool Rows" (#15915)
folded the format badge and whether the row renders a preview into that name,
so it now reads "E2E HTML Artifact HTML Opens as a rendered preview Click to
open" and an exact match finds nothing. Every scenario in the file failed at
its first click, three retries deep, which is what pushed the e2e shard past
its 30 minute ceiling.

This did not show up locally because the mock harness serves `client/dist`,
and mine was built before the rebase. The old bundle still rendered the old
name, so the stale locator passed here and failed in CI — and dev's own
`plain-text-artifact-row` spec failed locally for the mirror-image reason.
Both pass against a freshly built client.

The trigger is matched on its title now, the way dev's spec does it, so the
badge and the preview hint can change again without breaking the file.

* 🍞 fix: Share One Toast Viewport Between the App and the Window

The undocked artifacts window needs a toast viewport of its own, and it carried its own copy of the app shell's class list — so any change to toast placement, stacking or width would have had to be made twice, or the popup's notices would drift from the app's.\n\nThe viewport is now one composition in \, rendered by both hosts. It keeps the class list it always had and still takes a \, so the popup can adjust its own placement without forking the primitive.

* 🚫 fix: Keep a Rejected Edit Rejected Across a Host Change

A save the endpoint answers with 400 is deterministic, and the editor already refuses to send that exact text again. The refusal lived in the editor instance while the text itself lives in the shared buffer, so moving the pane to another host — which remounts the editor — dropped the marker and the inherited-buffer drain immediately sent the rejected text back, against the same original that produced the 400. Every dock or undock cost another rejected request, with no new edit from the user.\n\nThe marker now sits beside the buffer it describes, in the editor session, and names the artifact it was recorded for. A remount inherits it; a successful save clears it; ending the session clears it with the buffer. Returning to an artifact no longer resends its rejected text either, for the same reason. A genuine new edit still saves.

* 🧭 fix: Key the Artifact Registry to the Host's Conversation

The guard that bounds the artifact registry to one conversation decided that the conversation had changed by reading the chat tab's Recoil slot, which the shared route never sets. A shared conversation's host stays mounted while the reader moves between shared links, so on that route the change was invisible and only the unmount cleanup ever fired: artifacts from the previous link stayed in the registry, and opening an artifact in the next one could list and navigate back to the previous share's content.\n\nThe identity is now the host's to supply — the chat tab passes its Recoil slot, a shared conversation passes its own id — which is also what keeps the hook from reaching into app-global state for something only its caller knows. The first observed identity still does not wipe, so the loading transition into a shared conversation keeps the artifacts that belong to it.

* 🧪 test: Cover the Shared Host, a Blocked Popup and a Rejected Save

Three paths the pane reaches that no scenario exercised: a shared conversation, whose host resolves the undock capability from the shared-link config; a browser that refuses the popup, where the pane has to stay put and say so; and an edit the endpoint rejected, which must not go back on the wire because the pane changed hosts.

* 📝 docs: Document the Artifact Undocking Toggle in the Example Config

\ reached the schema and the shared-link config without ever appearing in the example file a deployment copies, so the lever existed but was undiscoverable. Documented with the default that reproduces today's behavior.

* 🔐 fix: Make the Undock Capability the Host's Answer, Not a Default

\ filled \ with \ when a host left it out, so a host that forgot would offer a window the deployment may have turned off — the one field in that context with no sensible fallback. It is now required, which makes forgetting it a compile error instead of a capability grant.

* 🕰️ fix: Read an Absent Conversation as Loading, Not as a Switch

The registry guard normalized a missing identity to a sentinel and stored it, so a host that reported nothing for a render — a shared link whose data refetches, a chat tab reading its slot before it is filled — looked like a move to another conversation. The reader lost the artifact they had open, and the same conversation coming back read as a first sighting.\n\nAn absent id is now no news at all: the last real identity stays the one the next id is compared against, so returning to it changes nothing and a real switch still wipes. Reported by Devin review of 097f9bfadd (BUG-0002), which also caught that ShareArtifactsContainer's comment already promised this behavior.

* 🏷️ fix: File a Refused Save Under the Artifact That Was Refused

The rejection marker was written with whichever artifact the pane happened to be showing when the 400 landed. A save answers after the user may have moved on, so a refusal for artifact A filed under artifact B left A free to send the same refused text again as soon as the user came back to it — and cleared B's own marker on A's next success.\n\nThe artifact a save was started for is captured when the request goes out, and both callbacks use it: the refusal names that artifact, and a success clears only that artifact's marker. Reported by Codex on 097f9bfadd.

* 🖥️ fix: Do Not Reopen the Pane on a Monitor That Is Gone

Remembered bounds are coordinates, and they outlive the monitor arrangement that produced them. Undocking takes the pane out of the page along with the only control that docks it, so a window reopened onto a display that no longer exists takes the artifact somewhere the user cannot reach.\n\nThe remembered rectangle is now used only when it can still be reached: it either overlaps this display's work area, or the browser says another display is attached, which is the case the feature exists for. A desktop reporting exactly one display is the only one where the rectangle is provably gone, and there the pane opens at the default bounds. A browser that does not report other displays keeps the user's placement. Reported by Devin review of a85d5c348e (BUG-0001).

* 🪞 fix: Follow a Stylesheet the Host Switches, Not Only Rewrites

The style mirror watched for nodes and text, so a sheet whose attributes changed — a \ switch, a \ flag, a \ that stops it being a stylesheet — left the popup showing styling the host had moved on from, with nothing to bring it back into line.\n\nThose attributes are part of the signature now, the observer watches them, and an update applies them to the clone alongside its content. Reported by Devin review of a853d48c90 (BUG-0002).

* ♻️ fix: Rebase Every Resubmitted Edit on What the Last Save Wrote

An edit replaces whatever the last save wrote, and the artifact registry only catches up when the edited message propagates. Three separate paths resubmit retained text — a queued edit, a buffer inherited at mount, and the edit restored when the user comes back to an artifact — and each had to learn that separately; the restore path had not, so it sent \ as the original, the endpoint refused it with a 400, and the text the user typed never landed.\n\nThe rebase now happens once, where the request is built: \ resolves the original from the save's own record unless a caller overrides it, so no path can forget — including the ordinary keystroke debounce, which had the same gap right after a save. Reported by Codex on a7c047cc2a, and the third finding in this family.

* 🧪 test: Let the Shared-Link Dock Click Race Its Own Window

Docking closes the window the click was made in, so the click can resolve against a page that has already gone — the same race the focus scenario already tolerates. The assertion that matters, the pane arriving back in the shared page, is unchanged. Seen once on desktop-dark while verifying a7c047cc2a.

* 🪞 fix: Clone a Stylesheet in the State the Host Has It

The attribute mirror kept a sheet current once the window was open, but the clone was built without those attributes — so a sheet the host had already switched off, or aimed at another medium, arrived in the popup switched on. Its signature matched from that moment, so the sync had nothing to correct.\n\nThe clone now carries the same attributes the sync keeps current. Reported by Devin review of c5d51b85fb (BUG-0002), and the same cause as its predecessor in that round.

* 🧪 test: Match the Blocked-Popup Notice Where It Is Shown

The notice is rendered in the toast and repeated in the live region, so the text matched two nodes and the assertion tripped strict mode on the slower mobile project. Either node proves the user was told; the assertion now takes the first.

* 🗑️ fix: Never Let a Cleared Editor Save Itself as a Deletion

Typing has always refused to save an empty editor: a user who selects all and deletes is mid-edit, not asking for the artifact's content to be removed. The paths that resubmit retained text did not know that, so a buffer holding an empty string was sent the moment the pane changed hosts or the user came back to the artifact — persisting a deletion nobody confirmed.\n\nThe rule now sits with the other decisions about whether a request goes out, in \, so the debounce, the queued edit, the inherited buffer and the restore all share it. Reported by Codex on a9a51439a5 (P1).

* 🧹 fix: Retire the Inherited Buffer Once a Newer Edit Is in Play

A host change hands the replacement editor the text its predecessor never sent, and the drain submits that once the save pipeline is idle. If the user kept typing in the replacement, the newer text queued behind the running save — and when it landed, the drain still had the older buffer in play and sent it, putting the artifact back the way it was.\n\nAnything an instance submits or queues now retires the buffer it inherited at mount, so the newest text is the last word. The drain passes the inherited text itself, which is how it stays exempt. Reported by Codex on 04a9f685b6 (P1).

* 🎨 style: Satisfy the Tailwind v4 Class Order From Canary

* 🧺 fix: Retain a Displaced Buffer Under the Artifact That Owns It

Editing one artifact evicted another's unsaved text from the shared code
buffer: the selection change had cancelled that edit's debounce, so the
overwritten copy was the only place it lived and coming back to the
artifact fell through to its persisted content. A buffer another artifact
displaces is now retained under its owner, and the editor restores and
sends it from there on the way back. Reported by Codex on 591ab13c96 (P1).

* 🧪 test: Key the Tabs Spec's Mocked Buffer to Its Artifact

The pane-wholeness change gated the preview on the buffer naming the
artifact on screen, but the spec's useCodeState mock never set
codeArtifactId, so the edited preview never applied. The mock now carries
the owner the component reads, and the editor spec's mock grows the
retained-buffer field the component destructures.

* 🧪 test: Prove a Displaced Edit Returns With Its Artifact

The displaced-buffer scenario gets its contract-level coverage: an edit
the user leaves on one artifact, an edit that displaces it on another,
and a return that has to land on the first artifact's own unsaved text.
The fake model grows a reply carrying two artifacts so both trigger rows
exist in one conversation, and its one nested ternary is unrolled so the
file lints under the repo rules CI applies to staged files.

* fix: Resolve Every Artifact Surface and Refusal Per Artifact

Preview, download and the Mermaid host now read an artifact's retained buffer the same way the editor does, rejection markers are kept per artifact so one refusal no longer overwrites another, and the saved-content history is only preferred while the registry still sits on this session's chain of saves.

* fix: Hold an Inherited Edit Until the Editor Can Save It

A buffer inherited across a host change while a response was generating was marked drained before the read-only guard dropped the save, and the read-only transition then replaced it with persisted content. The drain now waits for editing to return and writes the inherited text back after that transition.

* chore: Sort the Presentation Spec's Imports After the Canary Rebase

* test: Prove Each Artifact Surface and Save Path End to End

Covers the download of a displaced edit, a refusal per artifact, an edit after another session changed the artifact, and an edit carried through a response by a host change.

* test: Give the Undocked Presentation Case the Canary Query Client

* test: Start Artifact Scenarios From a Settled Reply on the Desktop Layout

* test: Stub the Command Executor Stamp in the Callbacks Spec Mock

Canary's #16556 calls stampCommandExecutor from callbacks.js, but this spec's @librechat/api mock predates it, so three cases failed on canary itself. The mock now carries the real helper, as it already does for isCodeArtifactToolOutput.

* fix: Track What the Server Holds Per Artifact Instead of Inferring It

The editor reconstructed the server's content from the mutation cache and treated every buffer as unsaved. A save now records what it wrote in a per-artifact ledger that the registry retires once it catches up, so a change made elsewhere (including a revert to an earlier value) wins over this tab's history, and text this tab already saved is never sent again by a host change or a return to the artifact.

* fix: Hide the Undocked Pane While Its Conversation Route Is Pending

The route keeps the previous conversation mounted but hidden while another one loads or fails to, and the undocked portal escaped that ancestry. The host now passes its pending state down and the window hides the pane with it.

* fix: Mark the Saved Buffer Copy and Retire Lag the Registry Has Passed

A buffer is saved only while it is the copy a save wrote, so editing away and back to the same text is still sent. Lag values the registry has already moved past are dropped in order, so a later change back to one of them is read as a change made elsewhere.

* test: Drop the Callbacks Mock Stub Canary Now Carries

* perf: Prune Settled Save Records When the Editing Session Ends
2026-10-01 18:41:18 +02:00
Lia
bbb58a867e ⛴️ fix: Preserve Canary Sync Resolutions (#16457)
Retain the tracked-file integration outcomes recorded by original canary sync PR #16457.

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

Original-PR: https://github.com/LibreChat-AI/LibreChat/pull/16457
Resolution-Sources: ffa54e0259, 7fe6eab03e, 8f64336ee4, 207ee8b0df, 7f3f82f284, e9e5b36bd2, ff3f0f8bef, 6bd657753a, 84a53a4464, f66ad88e1c
2026-10-01 03:46:19 +00:00
Marco Beretta
5b84c4b57f ⏳ feat: Add Ephemeral Retention Mode for Forced Temporary Chats (#13811)
* feat: add ephemeral retention mode for forced temporary chats

Adds RetentionMode.EPHEMERAL, which forces every newly saved chat
temporary: hidden from history and search, given the temporary-chat
expiration, and with the toggle locked on.

Forces isTemporary and applies the temporary expiration in the normal
conversation and message save methods, routes Assistants/Threads
messages through the normal message save, applies the all-data
retention policy to file uploads and shared links, and stamps imports,
forks, and duplicates. Locks the frontend toggle and keyboard shortcut
behind an administrator-enforced badge.

The default temporary mode and the existing all mode are unchanged.

* fix: enforce ephemeral retention when resuming paused chats

* fix: preserve forced retention across pauses and assistant turns

* test: Use Real Module IDs for Installed Package Mocks

* test: Wait for Resumed Retention Persistence

* test: Control Mongo Index Setup in OpenID Fixture

* test: Close Mobile Drawer Before Retention Resume Scenario

* fix: Store Responses API Messages Under the Retention Write Context

Input and output messages were saved with the raw request, so under
ephemeral retention they missed the forced-temporary classification the
conversation received. Route both through getConversationWriteContext
and announce the stored reply as saved.

* fix: Align Resumed Responses With the Parent Retention Deadline

A resumed response was saved with a fresh forced-temporary window while
the re-stamp kept the conversation's earlier deadline, so a chat that
paused again could leave its response stored after the conversation
expired. Stamp the saved response with the parent's deadline.

* fix: Clear Released Bookmark Tags When Forcing a Chat Temporary

stampForcedRetention released a converted chat's bookmark counts but
kept its tags, so deleting that chat before TTL removal decremented the
same tags again and reduced counts owned by other visible chats. Clear
the tags in the conditional conversion update that releases them.

* fix: Store No Bookmark Tags on Forced-Temporary Imports

An ephemeral import, fork or duplicate skipped its tag count increment
but kept the source tags, so deleting the copy before TTL removal
decremented counts owned by other visible chats. Store the same tags the
import counts, which is none for a forced-temporary copy.

* test: Provide the Forced-Temporary Retention Helper to the Header Stacking Mock

* test: Reuse One Admin Login per Worker in Ephemeral Retention Scenarios

* fix: Keep Legacy Temporary Chats Temporary When Forking Under All-Data Retention

* fix: Convert a Resumed Chat Under Ephemeral Retention Before It Can Re-Pause Empty

* fix: Treat a Reloaded Pre-Policy Run as Temporary Once Retention Is Forced

* fix: Stamp Messages with the Deadline a Concurrent Retention Stamp Stored

* fix: Wait for the Startup Config Before Rebuilding a Resumed Submission

* test: Wait for the Resumed Response Row in the Ephemeral Resume Scenario

* test: Provide the Real Command Executor Stamp to the Callbacks Mock

(cherry picked from commit 02a70e9c58)

Original-PR: https://github.com/LibreChat-AI/LibreChat/pull/13811
2026-10-01 03:46:19 +00:00
Marco Beretta
e1e1d1b19d 🎒 feat: Carry Project Context Across Conversations (#15684)
* 🎒 feat: Carry Project Context Across Conversations

* fix: fail a project attach whose upload hold cannot be released and keep file deletes independent of project cleanup

- Attaching a project file now fails, with nothing attached, when the file's
  temporary upload hold cannot be released, instead of attaching a file that
  can still expire.
- A failed project cleanup after a file delete is logged rather than failing a
  delete that already happened, and a user-wide delete clears that user's
  project references without reading every file first.
- Both resize handles share the orientation-aware grip, so a primary handle in
  a vertical group renders a rotated grip like the alternate one.

* fix: treat an empty tenant id as no tenant in the project file picker

* fix: attach nothing when a project file is deleted while the attach is in flight

* fix: localize project file association failures instead of showing server text

* test: expect a localized reason for a rejected project file association

* fix: scope project file listing to the caller's tenant and name the file limit when attaching an existing file

- Listing a project's attached files now returns not found when the project
  belongs to another tenant, matching the available-file listing and the
  chat context resolver.
- Choosing an existing file for a full project now names the project file
  limit instead of the generic attach error, like the upload path.

* fix: treat an empty tenant id as no tenant in every project tenant check

A caller whose tenant id is an empty string was refused its own tenantless
project when listing attached or available files, because the handlers
compared '' with null. The project handlers and the chat context resolver now
share one comparison that treats an empty tenant id as no tenant, the rule the
project file queries already follow.

* test: wait for the workspace layout swap and the mobile drawer before acting in the long-metadata spec

The desktop title was measured while the phone layout could still be the one
rendered, and the sidebar row menu was opened before the mobile drawer
committed its open state, which closes a menu opened ahead of it. The spec
now waits for the workspace's phone-only sidebar toggle to leave and for the
drawer to drop inert, the same drawer signal the agents helpers use.

* fix: keep the agent context fingerprint of a turn outside any project unchanged

Every turn now passes a project context key into the agent context
fingerprint, and a turn outside any project passed the no-project sentinel,
which changed the digest of every existing no-project checkpoint. An agent
event conversation written before this change then cold-started and reloaded
its history on its next event. The fingerprint now hashes the no-project key
as absent, so those checkpoints keep matching.

* test: load the long-metadata spec at phone width before driving the mobile drawer

The spec crossed back from desktop to phone width without a reload, which
leaves the drawer on the desktop toggle path whose delayed focus handoff to
the close button dismissed the row menu roughly 200ms after it opened. The
spec now reloads at phone width, as a phone arrives, and waits for the
drawer's own focus handoff before opening the menu.

(cherry picked from commit 4062bc3c00)

Original-PR: https://github.com/LibreChat-AI/LibreChat/pull/15684
2026-10-01 03:46:19 +00:00
Marco Beretta
2be35b2f91 💬 refactor: ChatForm UI redesign with unified palette (#14473)
* 💬 refactor: ChatForm UI redesign with unified palette

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

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

* fix: finish the dev rebase of the composer redesign

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

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

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

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

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

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

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

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

Defects:

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

Tests and lab:

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

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

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

Behaviour:

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

Policy:

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

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

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

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

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

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

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

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

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

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

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

The rest:

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

* fix: move persisted reasoning validation into api package

* fix: restore composer entry points and defaults

* style: normalize reasoning helper formatting

* test: open mobile sidebar before account menu

* test: use settled sidebar layout for mobile account menu

* test: handle empty mobile sidebar in account scenario

* test: target account menu in mobile drawer

* fix: keep composer surfaces and mobile drawer reachable

* fix: let thread approvals receive pointer events

* fix: stabilize composer steering and shortcuts

* fix: commit queue drags and centralize file modal

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* test: drive the surfaces these scenarios actually reach

Four scenarios were failing against surfaces the user never touches.

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

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

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

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

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

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

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

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

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

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

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

* test: reach the account menu without the pinned section

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

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

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

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

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

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

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

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

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

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

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

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

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

* feat: make the queued-send lock expiry configurable

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* test: reuse a published file through the composer palette

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

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

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

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

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

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

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

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

* test: hide the chip before replaying a deferred cancel

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

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

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

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

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

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

* test: type the reasoning snapshot the override helper records

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

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

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

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

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

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

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

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

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

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

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

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

* i18n: localize the whole attachment-limit message

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* style: sort the imports the canary rebase merged

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

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

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

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

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

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

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

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

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

* fix: resolve the effective responses route for upload targets

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

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

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

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

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

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

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

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

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

* fix: preserve numeric reasoning defaults on blur

* test: reopen persisted code cards before checking highlights

* test: follow the current file manager navigation

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* fix: name only the idle composer affordances that act

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

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

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

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

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

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

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

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

* test: scan the attach and tools palette for accessibility

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

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

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

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

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

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

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

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

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

(cherry picked from commit f568a4ba30)

Original-PR: https://github.com/LibreChat-AI/LibreChat/pull/14473
2026-10-01 03:46:18 +00:00
Marco Beretta
eefeb2a7f9 ⚙️ feat: Make the Per-User Passkey Cap Configurable (#16259)
(cherry picked from commit 84180a87e2)

Original-PR: https://github.com/LibreChat-AI/LibreChat/pull/16259
2026-10-01 03:46:17 +00:00
lia-by-librechat[bot]
e396ea9c7b 🫸 fix: Gate MCP App Views and Actions on User Intent (#16297)
* 🫸 fix: Gate MCP App Views and Actions on User Intent

* 🧪 ci: Run MCP Apps Browser Checks on Repository Bot PRs

* 🧲 test: Open App Before Checking Tool-Call Frames

* 🔎 fix: Wait for Stable App Views in Restored Browser Tests

* 🧪 test: Trace Grouped App View Activation in Browser CI

* 🧪 test: Diagnose Grouped App Click Propagation

* 🧪 test: Distinguish Native and React App Click Delivery

* 🧪 test: Inspect Grouped App Button Hit Target

* 🎟️ test: Open Grouped App Views After Scrolling Into Place

* 🧯 fix: Revoke App Approval Before Teardown Handshake

* 🫸 fix: Configure App Limits and Suspend Denied Actions

* 🧾 test: Expect Configured MCP App Limits in API Suites

* 🧱 fix: Isolate Approved App Messages From Composer Drafts

* 🛟 fix: Suspend Aborted App Actions and Restore View Focus

* 🦮 fix: Preserve Focus on App-Initiated Teardown

* 🧳 fix: Exclude Draft Agent State From App Messages

* 🧭 test: Preserve Legacy Null File Overrides

* 🧰 fix: Retain Selected MCP Tools Across App Messages

* 🧾 fix: Acknowledge Accepted App Turns and Disclose Selected Tools

---------

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

Original-PR: https://github.com/LibreChat-AI/LibreChat/pull/16297
2026-10-01 03:46:17 +00:00
Marco Beretta
27f78bc3c7 🎨 feat: Pick the Deployment Theme in librechat.yaml (#16286)
* feat: pick the deployment theme in librechat.yaml

Add `interface.theme` to the config schema, accepting a bundled theme name
or an inline theme definition. The interface loader passes it through, the
pre-login config payload carries it so the login page paints it, and a
DeploymentTheme wrapper around ThemeProvider resolves and validates it and
applies it without persisting it over the user's stored theme.

* fix: restore the user theme when the deployment theme is withdrawn

Move the pre-login interface selection out of the /api route into
buildPreLoginInterface in packages/api, so the route only wires it up.

When an authenticated config drops interface.theme (a principal override
tombstoning it), hand ThemeProvider the user's stored theme instead of
clearing to the LibreChat palette. The e2e scenarios now cover inline and
invalid themes, the withdrawn case, and high-contrast precedence.

* fix: read a legacy stored theme behind a corrupt stored definition

* perf: rebind the deployment theme observer on a cache add, not every event

useIsFetching recomputed the fetch count across every query on each cache
event, which slowed streamed renders enough to break the highlight-throttle
scenario. Subscribe to the query cache and re-render only when a startup
config query is rebuilt.

* test: wait for the composer after sign-in so mobile runs pass

* fix: keep deployment themes whole and restore legacy themes as legacy

A principal override with an inline theme merged into the base theme,
keeping the base's other mode, brands and tokens; interfaceConfig.theme
now replaces whole during override merging.

A withdrawn deployment theme restored a legacy-source stored theme as a
versioned definition, dropping its colors in dark mode; it now goes back
through ThemeProvider's legacy color path.

* fix: persist the user's theme changes after the deployment theme is withdrawn

Persistence now stays off only while a deployment theme is applied and for
the render that restores the stored theme, so later changes through the
theme API are saved again.

* refactor: derive deployment theme persistence from the current theme

(cherry picked from commit f0cbc9a3c0)

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

* fix: preserve MCP App results and enforce sandbox policy

* fix: bind persisted MCP Apps to their server configuration

* fix: complete MCP Apps runtime integration

* fix: type the optional MCP App binding codec explicitly

* test: provide MCP Apps policy in bridge mocks

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

* fix: align MCP Apps CI contracts

* test: preserve MCP abort reasons in recovery mocks

* fix: preserve MCP compatibility across policy profiles

* test: use profiled MCP catalog generations

* test: expect the standard MCP session profile

* fix: remove the unused MCP abort import

* test: expect profiled MCP fixture arguments

* test: seed profiled MCP manager fixtures

* Fix request-header bearer resolution after canary merge

* Preserve MCP App views across canary message updates

* Document message-owned MCP App placement

* ci: Recheck MCP Apps Against Canary Base

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Two gaps this round's own work left behind.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* feat: let operators set the reply polling cadence

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* style: order the conversation row classes for Tailwind v4

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

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

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

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

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

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

(cherry picked from commit b947738d0d)

Original-PR: https://github.com/LibreChat-AI/LibreChat/pull/15025
2026-10-01 03:46:16 +00:00
Marco Beretta
4ffe3825ec 📧 feat: add email address change (#14597)
(cherry picked from commit 9ff251dd96)

Original-PR: https://github.com/LibreChat-AI/LibreChat/pull/14597
2026-10-01 03:46:16 +00:00
Danny Avila
d33c72e6a8
🛂 fix: Rate Limit Authenticated 2FA Management (#16565)
* fix: Rate Limit Authenticated 2FA Management

* fix: Explain 2FA Rate Limits With Localized Retry Guidance

* fix: Preserve Minimum 2FA Setup Budget
2026-09-30 09:10:10 -04:00
Danny Avila
2aea0d6684
🏝️ feat: Scope YAML Custom Endpoints by Tenant (#16537)
* feat: Scope YAML Custom Endpoints by Tenant

* fix: Hide Tenant Model Specs and Preserve Scoped Base Reads

* fix: Finalize Tenant Endpoint Isolation and Interface Defaults

* test: Complete Tenant Endpoint Schema Fixtures

* fix: Invalidate Merged Configurations When Tenant Scopes Change

* fix: Flatten Tenant Identity Resolution and Finalize Regression Coverage

* test: Match the YAML Endpoint Name Contract

* test: Use the Exact Custom Provider Name

* fix: Distinguish Missing Tenant Context in Override Cache Keys

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-29 21:50:04 -04:00
Danny Avila
63363a7776
⏱️ fix: Fit Workspace Command Timeouts Inside the Configured Request Budget (#16464)
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
* ⏱️ fix: Fit Workspace Command Timeouts Inside the Configured Request Budget

* ⏱️ fix: Make Workspace Command Admission Reserve Configurable

* 🧪 test: Match Steering E2E Labels on Dev

* ⏱️ fix: Reject Impossible Workspace Command Admission Reserves

* 🧪 test: Match Failed Call Count in Dev E2E

* ⏱️ fix: Bound Workspace Admission Headroom and Document Its Budget

* ⏱️ fix: Validate Default Workspace Command Admission Reserve

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-28 22:53:14 -04:00
lia-by-librechat[bot]
bf91d2b59c
🥧 fix: Reserve Execution Time in Workspace Admission (#16421)
* 🥧 fix: Reserve Execution Time in Workspace Admission

* 🥧 fix: Pass Workspace Admission Static Checks

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-27 20:19:54 -04:00
lia-by-librechat[bot]
7b2362d7a7
🧲 feat: Attach or Leave a Workspace on a Saved Chat (#16124)
Some checks failed
Codegraph E2E Votes / vote (full suite) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Backend Unit Tests / Build packages (push) Has been cancelled
Backend Unit Tests / Codegraph select (push) Has been cancelled
Backend Unit Tests / Circular dependency checks (push) Has been cancelled
Frontend Unit Tests / Client build recovery regression (push) Has been cancelled
Frontend Unit Tests / Codegraph select (push) Has been cancelled
Frontend Unit Tests / Build packages (push) Has been cancelled
Sync Locize Translations & Create Translation PR / Sync Translation Keys with Locize (push) Has been cancelled
Docker Dev Images Build / publish (push) Has been cancelled
Sync Helm Chart Tags / Ignore non-main push (push) Has been cancelled
Sync Helm Chart Tags / Sync chart tags (push) Has been cancelled
Backend Unit Tests / TypeScript type checks (push) Has been cancelled
Backend Unit Tests / Tests: api (shard 1/3) (push) Has been cancelled
Backend Unit Tests / Tests: api (shard 2/3) (push) Has been cancelled
Backend Unit Tests / Tests: api (shard 3/3) (push) Has been cancelled
Backend Unit Tests / Tests: data-provider (push) Has been cancelled
Backend Unit Tests / Tests: data-schemas (push) Has been cancelled
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Has been cancelled
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Has been cancelled
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Has been cancelled
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Has been cancelled
Frontend Unit Tests / TypeScript type checks (client) (push) Has been cancelled
Frontend Unit Tests / Tests: @librechat/client (push) Has been cancelled
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Has been cancelled
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Has been cancelled
Frontend Unit Tests / Vite build verification (push) Has been cancelled
Sync Locize Translations & Create Translation PR / Create Translation PR on Version Published (push) Has been cancelled
* feat: Attach or leave a workspace on a saved chat

A saved chat that recorded running without an attached environment could
never take one: `without_attached` is sealed for the life of the chat, and
the only transition was a move between attached environments. Switching an
existing chat to a coding agent therefore ended in a composer that could
send but never reach files or commands. A chat sealed to a machine that went
offline had the opposite dead end: Send stayed disabled with nothing on
offer but a reconnect hint, and the "Move the chat to continue without it"
copy promised a request the server rejected as `invalid`.

One transition mechanism now covers all three directions. `from` still
repeats the persisted decision, so a stale view cannot replace a decision it
has not seen, and only a decision the chat actually recorded can move:

- attach, from a recorded `without_attached` onto the environments its
  agents use, with each target workspace revalidated on its worker;
- detach, an empty `to`, which clears the selections without polling the
  machine the chat is leaving;
- move, unchanged, including its refusal to switch the workspace of an
  environment the decision already covers.

The composer keeps the control visible while a chat runs without a
workspace, so that state is named and reversible, and offers "Continue
without workspace" whenever a sealed machine stops being usable. History is
untouched and no file is copied.

A send now also records the decision it was submitted under on its own
conversation. The server seals that pair for the rest of the chat, so a chat
that became saved mid-run held none while the stored one was already sealed:
the composer re-derived an agent default the seal refuses and reported
"Choose workspace" with Send disabled until the page was reloaded.

* 🎨 style: Format the Workspace Transition Hook Tests

* fix: Never seal a partial workspace decision, and gate the new directions

Two review findings on the transition mechanism.

A transition replaces the sealed decision whole, and the next turn resolves
every environment or none. The move path could not truncate before, because it
was offered only in `choose` state, which `aggregateState` reaches only when no
environment is unavailable, unsupported or missing: every environment was then
either carried over or selectable. Widening the gate to `!canSubmit` so an
unreachable machine could be left behind broke that invariant, and an
environment nothing can cover would have been dropped from a decision the
composer then sealed, blocking the next send and needing a second transition to
escape. A nonempty transition now requires every environment to be retained or
selectable; when one cannot be, only leaving attached execution is offered,
which is the escape.

The move protocol version becomes 2. Attach and detach travel on the same
owner-authorized endpoint as the move, so a client built against this change
would otherwise offer both to a deployment that only implements moves, where an
attach comes back `locked` and an empty target set `invalid`. The client already
compares the advertised number against the constant, so the bump is the gate.
`conversationMoves.enabled` still decides whether an owner may replace a sealed
decision at all.

* fix: Keep v1 moves working, and take the conversation updater from its owner

Two review findings on the previous head.

Bumping the move protocol wholesale made the client's exact-version check treat
a replica still advertising 1 as supporting nothing, so an attached chat whose
agent moved to another machine lost the relocation that replica already served
-- the previous head's own compatibility test pinned that regression. The
protocol is now two constants: version 1 is the move between attached
environments, version 2 adds attaching an environment to a chat that recorded
running without one and leaving attached execution behind. The server
advertises the highest it implements and the client keeps every lower
capability, so a v1 replica keeps its move while attach and detach wait for the
version that serves them. Where an environment cannot be covered and leaving is
not served either, no transition is offered and the composer reports the state.

Recording the submitted decision had made this hook a second Recoil writer of
the conversation atom, widening the surface that migration has to convert. The
host that owns the atom already holds its setter, so the hook receives it
instead of reaching through `~/store`.

* fix: Advertise attach and detach beside the move instead of above it

Raising the move protocol to 2 kept a client and server of the same build in
agreement, but not the two builds a rollout actually runs at once. The deployed
client compares the advertised number for equality against its own constant of
1, so a server advertising 2 tells every client already loaded in a browser that
moves are unsupported, and an attached chat whose agent changed machines loses
its relocation until that tab reloads.

The move version therefore stays 1, exactly as before this branch, and the two
new directions are advertised on their own field:

    codeEnvironmentMoveVersion: 1        // move between attached environments
    codeEnvironmentTransitionVersion: 2  // attach an environment, or leave one

Both come from `conversationMoves.enabled`, since all three are one owner
replacing one sealed decision. A client that predates this capability reads only
the move version and keeps working; a client that has it offers attach and
detach only where the second field appears, so it never sends a replica an
attach it refuses as `locked` or an empty target set it calls `invalid`.

* fix: Hold a send while a workspace decision is being replaced

Confirming an attach left Send enabled. The composer disables only the
workspace menu while the request is in flight, so a turn submitted right after
the confirmation started under the decision being replaced: it ran without the
workspace its owner had just chosen, and the replacement still landed, because
the stored decision the compare-and-swap expects was unchanged. The chat then
reported an environment its last turn never used, and nothing said so.

The server's own check has the same shape. It reads the conversation's
generation state, then revalidates each target workspace over the network, then
swaps; a turn that starts during that round trip is invisible to the check that
already ran. It now re-reads the generation state immediately before the swap,
leaving only the instant the compare-and-swap itself covers, which closes the
window for every client rather than just this one.

On the client the submission resolver refuses while a replacement is pending,
so the same signal disables the Send button and makes a programmatic send
return false. The workspace control stays reachable, so the state a chat is in
remains visible while it settles.

* fix: Fence Workspace Transitions and Reconcile Rejected Choices

Advance a private conversation revision after publishing an active generation and before reading its authoritative workspace decision. Transition CAS writes compare that revision, covering admission during the final idle-check window without expiring locks. Preserve tenant middleware and exclude private counter writes from chat activity and indexing.

Default existing undecided chats to no workspace, reconcile failed submissions from the server, scope pending guards to the affected chat, compare selection tuples without delimiter collisions, and opt attach/detach into deployment policy independently of existing moves. Retain legacy selection-only choices through first-send events.

* fix: Retain Failed Workspace Recovery and Skip Disabled Fences

Keep unconfirmed code-environment decisions in conversation-scoped Jotai state after authoritative reads fail, mutation observers reset, or navigation unmounts them. Expose a retry action and release submission only after a matching successful read. Ignore stale completions and reject mismatched conversation responses.

Reuse the owner-scoped conversation already loaded by each ingress when effective conversation moves are disabled. Retain the admitted revision fence for enabled moves, including move-only deployments. Cover failure/retry lifecycle and both policy branches at the helper and ingress levels.

* fix: Reuse the Atomic Admitted Snapshot Through Recovery

Return the admission revision and persisted decision from one Mongo findOneAndUpdate. Skip content indexing per internal query while retaining tenant middleware, private projection, and timestamps. Carry the returned snapshot through web and API initialization instead of validating against a stale pre-admission selection.

Keep first-send workspace choices in both the recovery preset and conversation template, and reconcile using the generated conversation ID from error or message data rather than requiring a saved submission snapshot. Cover single-query storage, indexing isolation, moved-machine validation, and first-send error recovery.

* fix: Reconcile Cancelled Turns and Keep Detach Reachable

Reconcile the submitted code decision before the local cancellation path finalizes streamed content or recovers a minimal submission. A cancel that beats the server rejection must not leave the attempted choice sealed locally; navigation must not update a different conversation.

Offer the authorized detach-only transition when a sealed conversation no longer has any attached agents, while ordinary chat stays sendable. Keep the selector visible for that transition and retain existing policy gates. Cover cancellation branches, no-attached-agent states, managed-only agents and the detach action.

* fix: Recover Workspace Transitions Across Navigation

* test: Verify Saved Workspace Transitions Against Current Dev

* test: Assert Explicit No-Workspace State in Native Journey

* test: Await Browser Settlement Before Switching Native Agents

* test: Settle URL Agent Selection Before Native Chat

* test: Wait for Worker Lease Expiry Before Offline Detach

---------

Co-authored-by: Lia <lia@librechat.ai>
Co-authored-by: Danny Avila <danny@librechat.ai>
2026-09-25 10:08:28 -04:00
lia-by-librechat[bot]
7d5cbc9ebf
🌫️ feat: Add Bounded PII Text Transformation (#16295)
* 🌫️ feat: Add Bounded PII Text Transformation

* ⚡ perf: Reuse Bounded Placeholder Scan

* fix: Respect PII Transformation Session Boundaries

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-24 08:34:49 -04:00
Danny Avila
361553f332
🚀 v0.8.8-rc4 (#16147)
Some checks are pending
Publish `@librechat/client` to NPM / pack (push) Waiting to run
Publish `@librechat/client` to NPM / publish-npm (push) Blocked by required conditions
Publish `librechat-data-provider` to NPM / pack (push) Waiting to run
Publish `librechat-data-provider` to NPM / publish-npm (push) Blocked by required conditions
Publish `@librechat/data-schemas` to NPM / pack (push) Waiting to run
Publish `@librechat/data-schemas` to NPM / publish-npm (push) Blocked by required conditions
Docker Dev Images Build / publish (push) Waiting to run
Sync Helm Chart Tags / Ignore non-main push (push) Waiting to run
Sync Helm Chart Tags / Sync chart tags (push) Waiting to run
* 🚀 v0.8.8-rc4

* chore: bump LibreChat chart to 2.0.14
2026-09-22 23:30:28 -04:00
Dustin Healy
418d62d52d
🔐 feat: Support Cognito Access Tokens for Agent Management (#16224)
* feat: support Cognito M2M for Agent management

* fix: reject compound management scopes

* fix: require scopes for audience-less management tokens
2026-09-22 20:37:40 -04:00
lia-by-librechat[bot]
45300a67b1
⛲ fix: Prevent Agent Model Stream Idle Timeouts (#16201)
* 🌊 fix: Prevent Agent Model Stream Idle Timeouts

* fix: Preserve Default Proxy Dispatcher Construction

* test: Assert Agent Transport Timeout Policy

* test: Cover Direct Model Dispatcher Reuse

* fix: Scope Agent Model Transport Timeouts

* fix: Enforce Agent Timeouts Across Direct and Summary Clients

* fix: Align Model Transport Adapter Types

---------

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

* test: settle ACL index builds before opening the transaction

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

* style: drop the now-unused RoleBits import

* fix: make ACL role replacement one atomic guarded write

* fix: export the permission write retry ceiling

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

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-21 23:40:52 -04:00
lia-by-librechat[bot]
cae9afd807
🧑‍🚀 feat: Add Grok 4.7 Support Through xAI (#16173)
Co-authored-by: Lia <lia@librechat.ai>
2026-09-21 22:36:28 -04:00
Marco Beretta
14d8bb8d3c
⚡ perf: Throttle Code Highlighting While a Message Streams (#16073)
* ⚡ perf: Throttle Code Highlighting While a Message Streams

* fix: harden streamed code highlight throttling

* test: cover wall clock changes during highlighting

* style: tidy highlight regression test

* fix: restart highlight work across lifecycle changes

* style: avoid nested highlight timing ternary

* fix: propagate highlight throttle to startup config

* fix: share and validate highlight throttle

* fix: keep streamed code visible during highlighting

* test: stream highlight tool arguments

* fix: preserve highlights when cadence config resolves

* fix: reschedule highlights when cadence changes

* test: preserve default fake tool chunking

* fix: prevent stale streamed highlights

* test: open the tool pane before asserting streamed highlights

Every scenario in this file waited for highlight tokens without opening the
card. Dev's #16143 stopped passing a closed pane any code at all, so the four
runs polled a card that renders raw text and had nothing to find: the failed
traces show the disclosure at aria-expanded="false" for the whole run, with no
click against it and no tokens in the code element.

Highlighting is now asserted through the card's disclosure, which ProgressText
owns and which carries an aria-expanded state only once the card has input to
show, so waiting on it also waits for the first streamed argument chunk. The
open happens inside expectHighlightedCode, so a scenario cannot assert tokens
without it, and it lands while arguments are still streaming, which is the only
window where the throttle is under test at all.

* test: reopen the rebuilt card for the settled highlight

Opening the pane got the streaming assertions passing and the traces show 240
highlight spans mid-stream, so the throttle itself lands. The settled check
still failed because persisting the streamed message rebuilds the card, and a
rebuilt card starts closed while autoExpandTools is off: the disclosure goes
back to aria-expanded="false" and a closed pane renders raw text.

The settled and cancelled states now assert through the same open-then-wait
helper, so each one measures the card the reader would actually be looking at
instead of the tokens the streaming card happened to leave behind.

* test: leave a window to cancel a streaming highlight

With the settled assertions fixed, the cancellation scenario timed out on the
Stop button instead: it waited for a highlight before stopping, and the ~40
argument chunks it streams at 35 ms are gone in under two seconds, so the run
had already finished and there was nothing left to cancel. It failed on all
three attempts.

The card is now opened and the run stopped before any token is awaited, since
tokens after cancellation are what the scenario is about, and the cancel
variant streams its arguments at a wider cadence so the window does not depend
on how loaded the runner is. Only that label changes cadence; every other
scenario keeps the timing it had.

* fix: preserve initial highlights and honor shared-page cadence

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-21 07:15:32 -04:00
Danny Avila
29ed0993a8
✂️ refactor: Name Tool Rounds From the Trace, and Match a Cut Response From Its End (#16113)
* ✂️ fix: Name Tool Rounds From the Trace, and Match a Cut Response From Its End

* 🧵 fix: Join a Cut Model Call's Round Only When One Is Waiting

* 🏷️ fix: Read Labels From the End Only for the Response the Limit Cut

* 🪪 fix: Say a Tool Round Came From the Conversation Only When It Did

* 🧾 fix: Carry Where a Tool Round's Calls Came From
2026-09-20 08:24:33 -04:00
lia-by-librechat[bot]
9acf9f0ac8
🫗 fix: Roll Back Incomplete Skill Archive Imports (#16052)
* 🫗 fix: Roll Back Incomplete Skill Archive Imports

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

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

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

Addresses the first review round on the archive import rollback.

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

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

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

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

* fix: Ignore Late Skill Import Successes

* fix: Make Skill Import Rollback Retryable

* fix: Propagate Incomplete Skill Cleanup

* fix: Settle Rollback Blob Cleanup

* test: Type Partial Cleanup Fixture

* fix: Preserve Settled Skill Cleanup Steps

* fix: Export Skill Cleanup Step Type

* fix: Reconcile Partially Deleted Skills

* fix: Reconcile Skill Rollback Caches

* style: format cleanup reconciliation changes

* fix: complete skill rollback cleanup

* chore: leave generated locale catalogs unchanged

* fix: preserve synced skill blob cleanup

* test: type synced blob cleanup mock

* fix: Validate Archive Paths and Bound Rollback Cleanup

---------

Co-authored-by: Lia <lia@librechat.ai>
Co-authored-by: Danny Avila <danny@librechat.ai>
2026-09-19 12:41:30 -04:00
lia-by-librechat[bot]
2452f499a8
🗼 fix: Serialize MCP OAuth Token Refresh Across Replicas (#15993)
Some checks failed
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Codegraph E2E Votes / vote (full suite) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Docker Dev Images Build / publish (push) Waiting to run
Sync Helm Chart Tags / Ignore non-main push (push) Waiting to run
Sync Helm Chart Tags / Sync chart tags (push) Waiting to run
Frontend Unit Tests / Client build recovery regression (push) Has been cancelled
Frontend Unit Tests / Codegraph select (push) Has been cancelled
Frontend Unit Tests / Build packages (push) Has been cancelled
Sync Locize Translations & Create Translation PR / Sync Translation Keys with Locize (push) Has been cancelled
Frontend Unit Tests / TypeScript type checks (client) (push) Has been cancelled
Frontend Unit Tests / Tests: @librechat/client (push) Has been cancelled
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Has been cancelled
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Has been cancelled
Frontend Unit Tests / Vite build verification (push) Has been cancelled
Sync Locize Translations & Create Translation PR / Create Translation PR on Version Published (push) Has been cancelled
* fix: Serialize MCP OAuth token refresh across replicas

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

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

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

* fix: Fence MCP refresh waiters instead of redeeming unfenced

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

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

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

* fix: Annotate derived refresh-flight constants for isolatedDeclarations

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

* fix: Hold the MCP refresh flight until redemption settles

Four corrections to the cross-replica refresh flight.

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

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

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

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

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

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

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

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

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

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

* chore: Regenerate the Agents OpenAPI spec for repositoryInstructions

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

* fix: preserve MCP refresh outcomes across replica boundaries

* fix: keep MCP adoption fenced through publication

* fix: anchor MCP refresh adoption to rejected credentials

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

* fix: Preserve OAuth Request Identity Through Recovery and Discovery

* fix: Fence OAuth Adoption Against All Credential Writers

* fix: Gate Coordinated OAuth Rollout and Preserve Unauthenticated Identity

* fix: Preserve OAuth Coalescing Across the Staged Rollout

* style: Sort OAuth Timeout Constant Import

* fix: Invalidate Both OAuth Token Flow Protocols on Rotation

* test: Complete the Rollback Token Flow Fixture

---------

Co-authored-by: Lia <lia@librechat.ai>
Co-authored-by: Danny Avila <danny@librechat.ai>
2026-09-16 21:58:23 -04:00
Marco Beretta
9633edcb88
🗣️ fix: Keep Provider Error Text on Unclassified Agent Failures (#16034)
* 🗣️ fix: Keep Provider Error Text on Unclassified Agent Failures

An upstream failure LangChain does not classify discarded the provider's own
message and answered with the generic upstream sentence plus a status, so a
gateway or privacy-proxy rejection lost the only account of what happened.

The provider text now rides along in the persisted payload as `message`,
withheld only where a content policy inspects the traffic — the same condition
`getUserFacingProviderError` and `getUserFacingRequestError` already decide by.

* fix: Harden Provider Error Detail Retention

---------

Co-authored-by: Danny Avila <danny@librechat.ai>
2026-09-16 21:32:41 -04:00
lia-by-librechat[bot]
a26a6709ff
📪 feat: Send Per-Request MCP Headers Without Hiding the Tool Catalog (#15988)
* 📪 feat: Send Per-Request MCP Headers Without Hiding the Tool Catalog

A `{{LIBRECHAT_BODY_*}}` placeholder in an MCP server's `headers` marks the
server request-scoped, and catalog discovery has no conversation to resolve it
against, so LibreChat skipped tool discovery and the server appeared with no
individual tools.

Operators can now declare those headers separately in `requestHeaders`, which
discovery omits and chat turns resolve and merge over `headers`.

* fix: normalize requestHeaders at each resolution entry point

Registering the new field in every consumer that enumerates header-bearing
config fields left five gaps: startup inspection, case-insensitive override,
the admin-configurable comparison surface, Graph token preprocessing, and
direct-bearer recovery.

Fold `requestHeaders` into `headers` at the entry of each resolution pipeline
instead, so Graph preprocessing, direct-bearer detection, `processMCPEnv` and
the transports keep reading one header map and never learn a second exists.
Catalog paths strip it at the same boundary, startup inspection included.

* fix: keep servers with chat-only headers off the shared app connection

A static `requestHeaders` map left a server eligible for app-level sharing, and
`ConnectionsRepository.loadConnection` handed the raw config to the factory, so
the shared session's own `initialize` and `tools/list` carried headers
documented as chat-only — and every later catalog read reused that session.

One session cannot serve both sides of the field. Exclude such configs from
`canUseAppConnection`, the single predicate both `connectAppServers` and the
repository's own app-level gate already consult, so the chat turn keeps its
headers on a user-scoped connection while catalog work never sees them.

* fix: normalize requestHeaders before the manager's bearer decisions

`createUserConnectionInternal` reads `usesDirectOpenIDBearerRecovery` and
`resolveDirectOpenIDBearerConfig` on the config it receives, while the merge sat
in `resolveRuntimeConfig`, a leaf helper below those calls. An `Authorization`
template declared in `requestHeaders` therefore never entered direct-bearer
mode: a `tools/list` 401 skipped the force-refresh and the connection was
returned with a stale bearer.

Normalize at the birth of that pipeline's config instead, ahead of all four
decisions, and make `getMCPAppToolsPublicationGeneration` normalize before
hashing. Connection paths hold a merged config while cache paths hold the
declared one, so without a canonical hash the two would address different
catalog slices.

* fix: Preserve MCP request header ownership across lifecycle boundaries

* fix: Narrow remote header identity before rebuilding config

* fix: Preserve request header precedence over catalog API keys

* docs: Synchronize generated agent API schemas

* fix: Ignore shadowed generated MCP user key requirements

---------

Co-authored-by: Lia <lia@librechat.ai>
Co-authored-by: Danny Avila <danny@librechat.ai>
2026-09-16 15:16:40 -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