Commit graph

419 commits

Author SHA1 Message Date
Marco Beretta
e95e696d70
🧾 fix: Count the Tool Results a Tool-Limit Stop Retains (#15893)
Some checks are pending
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Codegraph E2E Votes / vote (full suite) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Client build recovery regression (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
Docker Dev Images Build / publish (push) Waiting to run
Sync Helm Chart Tags / Ignore non-main push (push) Waiting to run
Sync Helm Chart Tags / Sync chart tags (push) Waiting to run
* 🧾 fix: Count the Tool Results a Tool-Limit Stop Retains

Context snapshots reach the client only through the SDK's pre-invoke
`ON_CONTEXT_USAGE`, so the results of the tools a call requests are never in that
call's snapshot — the next call's snapshot carries them as kept-message context.
A run that stops at the tool-call limit makes no next call, so the tool result it
retains lives in the response and in no snapshot: the gauge reported
`(budget − remaining) + completedOutputTokens` and left the retained result out
of used tokens and out of the tool-call share until the following turn.

The save path now counts those results with the run's own tokenizer and persists
them as `retainedToolTokens`, a second post-snapshot delta alongside
`completedOutputTokens` rather than a number folded into the provider-reconciled
`messageTokens`. `resolveRetainedToolTokens` owns the rule that only a tool-limit
stop retains anything, and the snapshot handler records where its content ended
so the count starts at the right boundary.

Counting had to avoid `Tokenizer.getTokenCount`, whose fallbacks would have put a
guess inside exact accounting: above 4 KiB it returns byte length, several times
the real count on ordinary text, and it estimates from character length while an
encoding loads. `countExactTokens` tokenizes in bounded slices cut on code-point
boundaries and returns nothing at all when the encoding is cold, so an
uncountable result withdraws the figure instead of inflating it.

The client adds the field to used tokens, subtracts it from the runway headroom
and widens the tool-call share, in the live snapshot after finalization and in
the persisted blob after a reload.

* 🧹 style: Wrap the Retained-Counter Assertion as Prettier Requires

* 🧮 fix: Address the Review of the Retained-Tool Count

Three findings from the first round, each a real defect in how the figure was
produced rather than a style point.

The boundary was a content index recorded mid-run, but completion reshapes the
array — skill cards are unshifted onto the front and `hide_sequential_outputs`
replaces it with a filtered one — so a saved index no longer means the same
position. The snapshot now records the tool-call ids it already accounts for, and
the save path counts the results of the calls missing from that set: ids survive
every reshape, and a filtered-away call is correctly left out.

Counting in 4 KiB slices was not exact either: a BPE merge spanning a seam is
charged twice, measured at ~1 token per slice, and the field exists precisely to
be an exact addend. `countExactTokens` now tokenizes the whole input — ~60 ms/MB,
paid once at the end of a stopped turn — and refuses content past 8 MiB rather
than estimating it.

The counter takes its exact-count function instead of reaching for the tokenizer
singleton, so `resolveRetainedToolTokens` owns the default (the run's own
encoding) and a caller or test can supply another. That also removes the mock of
global state from the specs.

`compactionReclaim` now includes the retained result in the total it subtracts the
kept exchange from. `latestExchangeTokens` already counts that result on the
other side, so leaving it out subtracted content the total never carried and
understated the savings — to zero on a large final result.

* 🧯 fix: Bound One Turn's Retained-Result Tokenization

The tokenizer refuses a single result past 8 MiB, but a final call that requested
several tools in parallel would pay that bound once per result. The counter now
holds a budget for the whole turn and withdraws its figure past it, so the save
path cannot be made to tokenize an unbounded pile of output.

* 🎚️ feat: Configure the Retained-Result Tokenization Budget

The exact count the gauge adds costs ~60 ms/MB of retained tool output, and the
ceiling on that work was hard-coded in two places. It is now one lever:
`endpoints.agents.maxRetainedToolCountChars`, defaulting to the 8 MiB that
reproduces today's behavior, shared by the schema and the save path through
`DEFAULT_MAX_RETAINED_TOOL_COUNT_CHARS`. Deployments whose tools legitimately
return more can raise it; slower hardware can lower it, or set `0` to withhold
the figure entirely.

`Tokenizer.countExactTokens` no longer carries a bound of its own — the caller
owns the budget — and `resolveRetainedToolTokens` passes the configured value to
the counter, which spends it across all of a final call's parallel results.

---------

Co-authored-by: Danny Avila <danny@librechat.ai>
2026-09-13 22:20:25 -04:00
Marco Beretta
91e00bbe6e
🧷 fix: Mark a Failed Compaction So Its Rerun Controls Stay Withheld (#15883)
* 🧷 fix: Mark a Failed Compaction So Its Rerun Controls Stay Withheld

A manual compaction that failed with an error part carried no marker: the
server stamped `initiatedBy: 'user'` only on a summary that produced text and
returned early once an error part existed. On a branch ending in a user
message, the resulting turn had no marker and a user parent, so the hover row
kept Edit, Regenerate and Continue — and using one answered that user message
instead of retrying the compaction.

`markCompactionOutcome` now marks whichever part carries the outcome, summary
or error, and `isUserInitiatedCompaction` reads both. The marking moved from
`api/server/controllers/agents/client.js` into `packages/api`, where the
behavior belongs; the controller keeps the call.

* 🏷️ refactor: Type the compaction spec helpers with SummaryContentPart

* 🧯 fix: Record a Marked Failure When a Compaction Produces Nothing

A compaction run that produced neither a summary nor an error part threw
COMPACTION_FAILED out of `sendCompletion`. The turn was then saved by
`saveErrorTurn`, which writes only top-level `text`/`error` and no content, so
the row carried no compaction marker: on a user leaf the hover row kept
Regenerate, and using it answered that user message.

`markCompactionOutcome` now records the typed failure as a marked error content
part instead, so the turn streams and persists like every other failed
compaction. A cancelled run still fails as a typed error, leaving the abort
path to own the turn. `saveErrorTurn` marks the compaction rows it still writes
for failures that are rethrown rather than recorded as content.

Verified end to end by two new mock scenarios that run Compact context against
a summarizer returning nothing, live and after a reload.

* 🧪 test: Run the Empty-Compaction Scenarios Against a Real Compaction

* 🧱 refactor: Resolve Failed-Turn Compaction Content in packages/api

`saveErrorTurn` decided in CJS whether a failed row carries compaction
identity. The decision moves to `resolveFailedTurnContent` in
`packages/api`, which returns the content fields a failed turn is persisted
with — the marked failure for a compaction, nothing for any other turn — and
`request.js` spreads the result.

* 🧹 fix: Keep an Unusable Summary Out of a Failed Compaction's Turn

History loading accepts any nonempty summary as the conversation's checkpoint
(`BaseClient.findSummaryContentBlock` ignores `failed`), so a compaction that
streamed partial text before failing would have persisted that truncated text
beside its recorded failure and replaced the history it failed to summarize.
The fallback now drops the unusable summary, leaving the typed failure as the
turn's whole outcome.

The empty-summarizer scenarios switch the shared fixture summarizer to blank
output, so the reset moves to `afterEach` and runs even when the helper throws
before its caller's `finally`.
2026-09-13 21:53:29 -04:00
Danny Avila
f6335cb9d7
💰 fix: Bill Stopped Agent Turns From Provider Usage (#15889)
* 💰 fix: Record Token Usage for Stopped Agent Turns

The agents Stop route only signals the abort; the run's cleanup skipped recordCollectedUsage on an aborted signal, trusting an abort middleware that is mounted only on the assistants abort routes. Stopped and error-aborted agent turns therefore wrote no transactions and never debited the balance.

The run now records its collected usage on every exit, labelling a stopped turn's transactions with context 'abort'. The owner of the run charges, so a cross-replica Stop is still billed exactly once.

* 💰 fix: Make the Run the Single Charger for a Stopped Turn

The legacy assistants-mounted abort route still billed a non-assistants job — provider usage via spendCollectedUsage, or a text-count fallback — on top of what the run records on exit, and its array clear ran only after its own awaited write, so the two could race even on one replica. The route now only stops and persists; the run records its usage once, labelled through resolveRunUsageContext in packages/api.

* 💰 fix: Keep the Text-Count Fallback From Re-Billing Recorded Usage

BaseClient falls back to text-count billing whenever the recorded usage has no positive output count, so a stopped call that reported input tokens and no output was debited by recordCollectedUsage and then charged its estimated prompt again. AgentClient.recordTokenUsage now returns early once provider usage was recorded (hasRecordedProviderUsage in packages/api); an all-zero report still falls through to the estimate.

* 💰 refactor: Lift Fallback Token Billing Into packages/api

recordFallbackTokenUsage owns the whole fallback operation — the recorded-usage guard, the estimate spend, the reasoning row and the error boundary — taking spendTokens as an injected dependency. AgentClient.recordTokenUsage only builds the transaction metadata from the client and calls it.

* 💰 fix: Label Fallback Billing From the Run's Stop State

BaseClient invokes the estimate fallback without a context, so the sole row for an initial turn stopped before any provider usage was labelled 'message'. recordTokenUsage now defaults the context from the run's own abort signal.

* 💰 refactor: Default the Fallback Billing Label in packages/api

recordFallbackTokenUsage takes the run's raw abort state and derives the transaction label itself; AgentClient.recordTokenUsage passes the signal through and no longer chooses the context.

* 💰 fix: Guard Fallback Billing on the Collected Primary Entries

The stream aggregate recordCollectedUsage returns takes its input from the first primary call only, so a later cancelled call that reported input alone was billed yet invisible to the fallback guard, which then charged the estimated prompt again. recordFallbackTokenUsage now also consults the collected entries themselves (hasRecordedPrimaryUsage), ignoring summarization, subagent and sequential usage; AgentClient passes its collected entries through.
2026-09-13 21:51:05 -04:00
Danny Avila
17c7b30631
💤 fix: Preserve Dormant Workspace Bindings (#15877)
* fix: Preserve Disabled Workspace Bindings

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

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

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

* 🛂 fix: Address Trace Viewer Review Round 1

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* 🚰 fix: Release Failed Langfuse Response Bodies

A non-success Langfuse response was turned into a TraceReadError without consuming or cancelling its body, and Node's fetch returns a connection to its pool only once the body is released, so a sustained upstream failure left sockets checked out until garbage collection. The body is now cancelled before the status becomes an error.
2026-09-13 00:56:52 -04:00
Danny Avila
74fa60cee1
🔎 fix: Enforce WEB_SEARCH Role Permission on Agents (#15875)
* 🔎 fix: Enforce WEB_SEARCH Role Permission on Agents

Squash of #15822 onto dev, preserving authorship:

- 🔎 fix: Enforce WEB_SEARCH Role Permission on Agents
- 🧪 test: Cover the Runtime Tool Loader's Web Search Gate
- 🔒 fix: Gate Web Search on the OpenAI-Compatible Embedder Surface
- 🩹 fix: Authorize Web Search by the Execution Context's User
- 📝 docs: Note the Grant Memo's One-Subject-Per-Request Assumption
- 🧹 fix: Deny Web Search Before an Endpoint Default Can Grant It
- 🙈 fix: Withhold the Web Search Model Parameter From a Denied Role
- 🧱 fix: Strip Provider-Native Search an Endpoint Re-Enables After Denial
- 🔌 fix: Close the OpenRouter Plugin Path and Stop Pruning Hidden Parameters

* 🧭 fix: Gate Provider-Native Web Search on the Built Config

The web search role gate ran before the provider builder and only when the
agent's stored `web_search` was not `false`, so an endpoint's `addParams`
re-enabled native search for a denied role, and every OpenAI-compatible and
Responses request read the role whether or not search was in play.

The gate now reads the builder's output: when it carries a native search tool
or OpenRouter's `web` plugin, the `WEB_SEARCH` grant is resolved and the search
stripped on denial. The routes that reach `initializeAgent` with `runtime` and
no `req` pass a lazy `resolveWebSearchGrant` that joins their request-memoized
grants, forwarded through agent discovery to handoffs and subagents. The
embedder surface wires it whenever `getRoleByName` is supplied, independent of
`appConfig`.

---------

Co-authored-by: TomasPalsson <tomas2212042710@gmail.com>
2026-09-12 23:00:10 -04:00
Danny Avila
1163045cef
🖋️ feat: Seal Code Environment Choices Per Conversation (#15868)
Some checks are pending
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Codegraph E2E Votes / vote (full suite) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Client build recovery regression (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
Sync Locize Translations & Create Translation PR / Sync Translation Keys with Locize (push) Waiting to run
Sync Locize Translations & Create Translation PR / Create Translation PR on Version Published (push) Blocked by required conditions
* feat: lock code environments per conversation

* style: Sort code environment imports

* fix: Harden code environment decisions

* fix: Preserve code environment rollout compatibility

* fix: Harden code environment boundaries

* refactor: Centralize code environment policy

* test: Restore partial disconnect policy mock

* fix: Close code environment edge paths

* fix: Preserve implicit stateful code routes

* fix: Stabilize implicit code routing

* test: Align remote workspace contract

* chore: Sort code route import
2026-09-12 20:45:00 -04:00
Dustin Healy
19eb24921e
🔠 feat: Render Safe Upstream Model Errors (#15837)
* ✨ feat: Surface Upstream Model Errors

* 🧪 test: Cover Upstream Error Rendering

* 🛡️ fix: Harden Upstream Error Fallbacks

* 🛡️ fix: Defer Upstream Error Fallbacks
2026-09-12 20:23:54 -04:00
Dustin Healy
7a83b8f5d2
📟 feat: Record Safe Upstream Model Failures (#15800)
* ✨ feat: Add Upstream Model Error Observability

* ♻️ refactor: Move Terminal Error Policy to TypeScript

* 🛡️ fix: Preserve Agent Cancellation Semantics
2026-09-12 20:23:17 -04:00
Joseph Licata
f25242df98
🦘 feat: Share Run-Scoped Files With Subagents (#15848)
* feat: add run-scoped file sharing for subagents

Delegate current-message files through authorized execution catalogs and publish selected immutable code-output versions through the existing file pipeline.

Requires the companion agents SDK context adapter before the dependency can be released and pinned.

* fix: preserve child tool artifacts and verify file-sharing lifecycle

Keep citations and other non-sandbox artifacts on their existing delivery path while retaining private code outputs and inspected images until publication.

Cover native and text delivery, nested and sibling authorization, concurrent runs, cancellation cleanup, and checkpoint recovery through the browser harness.

* test: align file-sharing fixtures and integration cleanup

* test: repair LibreOffice conversion fixtures

* test: verify deployment skill bytes across checkout formats

* fix: align subagent file budgets and refresh boundaries

* chore: update agents SDK to 3.8.6

* refactor: move code output processing into API workspace

* fix: enforce shared file budgets for parents and teams

* fix: declare the shared file encoder interface
2026-09-12 20:14:22 -04:00
Hao
bd08a363c4
🔣 fix: Encode Images From Storage Keys (#15851)
* fix: Prefer storage keys for image encoding

* fix: Sanitize assistant image errors

* fix: Sanitize agent image storage errors

* fix: Move blob image encoding into API package

* fix: Complete image encoder TypeScript migration

* fix: Keep request-boundary error logs diagnosable

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

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

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

---------

Co-authored-by: Danny Avila <danny@librechat.ai>
2026-09-12 12:39:26 -04:00
Danny Avila
1d45f5bd40
🏡 feat: Remember Agent Workspace Defaults (#15843)
* 🧭 feat: Remember Attached Workspace Choices

* Guard Workspace Defaults Across Navigation and Version Restore

* Order Workspace Preference Imports

* fix: Harden agent workspace defaults

* fix: Type workspace validation schema

* test: Cover safe execution projections

* fix: Bind workspace defaults to attached environments

* fix: Preserve unchanged workspace bindings

* fix: Scope workspace preferences to active agents

* fix: Preserve workspace selection state

* test: Target workspace discovery status

* fix: Keep workspace reset available

* fix: Resolve workspace defaults per environment

* fix: Collect per-environment workspace defaults

* fix: Reconcile Deleted Agent Graph Caches

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

* fix: declare traversal diagnostics for isolated declaration builds

* refactor: inject locator traversal reporting from application callers

* fix: propagate traversal diagnostics across protected entry points

* fix: complete middleware reporters and hydration message counts
2026-09-11 16:47:48 -04:00
Marco Beretta
e2f5772961
🧮 feat: Surface Retained Tool-Message Context Usage (#15796)
Some checks are pending
Docker Dev Images Build / publish (push) Waiting to run
Sync Helm Chart Tags / Ignore non-main push (push) Waiting to run
Sync Helm Chart Tags / Sync chart tags (push) Waiting to run
* feat: surface retained tool-message context usage

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

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

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

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

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

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

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

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

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

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

Fourth round on the retained tool-message context work:

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

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

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

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

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

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

* test: exercise the context split through the mock harness

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

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

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

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

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

* fix: add pinnedOrder to IUser type and sort imports

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

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

* fix: address review findings on unified pinned section

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

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

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

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

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

* fix: address PR review bot findings

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

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

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

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

* fix: address second round of PR review bot findings

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

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

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

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

* fix: address third round of PR review bot findings

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

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

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

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

* fix: address fourth round of PR review bot findings

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

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

* fix: address fifth round of PR review bot findings

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

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

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

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

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

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

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

* fix: address sixth round of PR review bot findings

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

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

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

* fix: gate pruning on a delivered favorites list

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

* fix: address eighth round of PR review bot findings

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

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

* fix: address ninth round of PR review bot findings

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

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

* fix: address tenth round of PR review bot findings

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

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

* fix: address eleventh round of PR review bot findings

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

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

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

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

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

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

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

* fix: publish the session identity from the user atom

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

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

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

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

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

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

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

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

Leaves AuthContext and the user atom untouched.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* fix: let favorites membership reconcile between tabs

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

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

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

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

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

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

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

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

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

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

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

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

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

* fix: preserve pinned order until favorites membership catches up

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

* fix: preserve reconciled keys during active pinned arrangements

* style: sort pinned order regression imports

* fix: reconcile favorite rollbacks before pinned-order pruning

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

* 🧊 fix: Withhold Rerun Controls on Compaction Turns

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* 🎨 fix: Ask the Editor What It Can Edit

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

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

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

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

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

* 🧹 style: Sort the New Imports in Both Editors

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

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

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

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

* 🧪 test: Exercise the Compaction Controls in the Browser

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

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

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

* feat(insights): improve agent filter controls

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

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

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

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

* fix: Use artifact titles for download filenames

* fix: Match artifact filenames to downloaded content

* fix: Preserve raw artifact extensions and GFM headings

* fix: Download complete artifact files and retain filename provenance

* fix: Distinguish cached artifact exports from originals

* fix: Name unnamed artifact originals by their media type

* fix: Recognize legacy CSV MIME in artifact filenames

* fix: preserve context insights across reloads and configuration changes

* fix: retain primary call details when resuming context snapshots

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

* fix: keep resumed output compatible with older clients

---------

Co-authored-by: Ravi Kumar L <upman@users.noreply.github.com>
Co-authored-by: Danny Avila <danny@librechat.ai>
2026-09-11 15:53:29 -04:00
Danny Avila
d510b6feb6
🛖 fix: Restore Saved Attached Workspaces (#15811)
Some checks are pending
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Codegraph E2E Votes / vote (full suite) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
* Restore attached workspaces from the resolved owner conversation

* Carry restored conversation through lazy tool initialization

* fix: Resolve Workspace State From Effective Conversation

* style: Format Conversation Regression Cases

* test: Retain Real Workspace Resolver In Controller Fixtures

* test: Exercise Workspace Envelope Conversation Identity
2026-09-10 11:33:11 -04:00
Danny Avila
a785a6196a
📯 fix: Propagate Host Cancellation Into API Tools (#15812)
* Propagate host cancellation through API tool execution

* Preserve selected signal ownership across every API ingress
2026-09-10 08:29:47 -04:00
Dustin Healy
03a42d6c7e
🎒 fix: Carry Subagent Identity Past Streaming (#15795)
* fix: resolve saved subagent display identity

* fix: persist explicit subagent execution identity
2026-09-09 23:07:10 -04:00
Danny Avila
6cb0499319
🌳 fix: Guard Ambiguous BYOM Workspace Selection (#15785)
* fix: Preserve BYOM workspace selection state

* 🧭 fix: Centralize Workspace Error Serialization

* 🎨 style: Format Workspace Error Helper
2026-09-09 14:27:54 -04:00
Danny Avila
66faf4c27a
🛑 fix: Preserve BYOM Foreground Cancellation Identity (#15777)
* fix: Preserve BYOM foreground cancellation identity

* fix: Bind foreground cancellation to runtime message
2026-09-09 09:22:08 -04:00
Danny Avila
559fd7d607
🪓 feat: Cancel Background Tool Invocations (#15773)
* ✨ feat: Cancel ordinary background tools

* 🛡️ fix: Keep cancellation receipts rollout-safe

* 🛡️ fix: Harden Background Tool Cancellation

* 🧪 test: Cover cancellation config wiring

* 🎨 style: Sort cancellation imports

* 🧪 test: Align Cancellation Claim Result

* 🛑 fix: Complete Background Cancellation Lifecycle

* 🎨 style: Align Cancellation Test Formatting
2026-09-09 09:06:26 -04:00
Danny Avila
a8087ce454
🏕️ feat: Select Attached Code Workspaces (#15768)
* feat: Select Attached Code Workspaces

* fix: Preserve Workspace Boundaries Across Agent Graphs

* fix: Validate Lazy Agent Workspace Bindings Before Persistence

* fix: Include Handoff Environments in Workspace Selection

* fix: Close Workspace Admission and Remote Ingress Gaps

* fix: Preserve Workspace Selection In Chat Runtime Envelopes

* fix: Authorize Deployment Workspace Status And Match Readiness

* fix: Preserve Ephemeral Chats And Pin Runtime Worker Identity

* test: Complete Deployment Pairing Fixtures
2026-09-09 02:14:50 -04:00
Danny Avila
ec15075dc8
🚚 feat: Route Attachments and Provision Tools Lazily (#15763) 2026-09-08 23:28:52 -04:00
Danny Avila
ab6cde0c79
⏳ fix: Separate Temporary and General Chat Retention (#15734)
* fix: separate temporary and general chat retention

* fix: inherit retention when branching messages

* fix: harden retention lifecycle boundaries

* fix: preserve subagent retention context

* fix: trust stored chat retention for uploads

* perf: overlap generated file retention lookup

* fix: derive retention from trusted chat state

* fix: preserve retention across the full turn lifecycle

* test: accept the conversation retention read adapter

* fix: carry retention deadlines through durable job saves

* fix: resolve retention at cached and new chat admission

* fix: resolve direct tool retention before execution

* fix: preserve retention across assistant writes and direct tools
2026-09-08 11:22:54 -04:00
Danny Avila
ba12eaa418
⛔ fix: Bind Tool Approvals to Generation Scope (#15724)
* fix: bind tool approvals to generation scope

* fix: gate generation scope on replay lifecycle support

* chore: add npmrc for npm v12 support, fix xlsx tarball dl

* chore: bump agents sdk to v3.8.3

* fix: require scoped approval replay support
2026-09-08 08:02:48 -04:00
Dustin Healy
cdc3339a78
🪬 fix: Fence Agent Checkpoint Ownership and Cleanup Recovery (#15680)
* 🔒 fix: Isolate Checkpoint Cleanup by Generation Ownership

* 🔒 fix: Harden Checkpoint Cleanup Ownership

* 🔒 fix: Retain Checkpoint Cleanup Evidence

* 🔒 fix: Persist checkpoint cleanup receipts

* 🔒 fix: Bound checkpoint cleanup receipt lifecycle

* fix: Bind checkpoint cleanup to durable ownership and deletion intent

* fix: Bind event actor checkpoint storage to authenticated owners

* fix: Resolve exact actor checkpoint ownership before lifecycle cleanup

* fix: Preserve actor storage compatibility with durable ownership and prune work

* fix: Defer checkpoint erasure until conversation deletion commits

* fix: Reclaim orphan actor ownership and batch deletion lookups

* fix: bind actor checkpoint ownership to payload rows

* fix: isolate actor readers and await account persistence

* fix: gate owned suspensions and drain complete account state

* fix: unify checkpoint deletion lifecycle and storage authority

* fix: Replay checkpoint deletion from durable owner state

* fix: retain checkpoint cleanup identity before topology loss

* fix: complete checkpoint catalog capture and retirement lifecycle
2026-09-07 22:04:59 -04:00
Danny Avila
6f05678bfc
🧐 feat: Restore Interactive Tool Approval Review (#15717)
* 🧐 feat: Review Pending Tool Actions in the Composer (#15714)

* feat: add interactive approval review to the composer

* fix: Harden interactive approval boundaries

* fix: Bound every approval display label

* test: exercise composer approval review in BYOM acceptance

* fix: reveal all directional approval controls

* fix: canonicalize code approval targets across replicas

* style: sort resumable approval test imports

* test: Exercise Coexisting Approval Surfaces

* Revert "🧐 feat: Review Pending Tool Actions in the Composer (#15714)"

This reverts commit 5f79ded9553405b697e837e1976a70accbfc3fc3.

* Reapply "🧐 feat: Review Pending Tool Actions in the Composer (#15714)"

This reverts commit 52c7d9c7453da0168338bcf79494927f561a92a0.

* chore: bump agents sdk to v3.8.2
2026-09-07 22:02:56 -04:00
Danny Avila
3e2a6f333b
🪗 feat: Compact Context in a Summarize-Only Turn (#15690)
* 🗜️ feat: Manual Context Compaction as a Summarize-Only Turn

Adds a user-triggered "Compact context" action that summarizes the active
branch on demand. The compaction is an ordinary agent turn: the client
submits it through the normal chat pipeline with `compact: true`, the
controller hangs it off the branch's leaf instead of creating a user
message, and the agent client runs the graph summarize-only (the SDK's new
`summarizeOnly` input), so the summary streams into the response
placeholder under the leaf exactly like the automatic detour's and is
persisted as the boundary every later turn starts from.

Nothing new is needed for job registration, billing, abort, persistence,
or the usage snapshot: the run emits the same summary step and post-summary
context snapshot the automatic path already emits, and the response message
carries the summary part plus the `summaryUsedTokens` baseline the gauge
reads. The controller validates the request (existing conversation, a real
leaf, summarization enabled, no edit/regenerate/continue combination) and
answers 409 when the leaf is already a bare summary.

Client-side the submission borrows the regenerate shape — no new user
bubble, the placeholder parents onto the leaf — while the wire payload
drops `isRegenerate` so the server never treats it as a regenerated user
turn. The action sits in the context-usage popover, gated by the same
`summarization.enabled` switch as the automatic detour.

* 🗜️ fix: Localize a Compaction That Cannot Run

A compaction the graph could not attempt (summarization disabled, the
instructions already exceeding the budget, or an explicit recency window
covering the whole conversation) rejects with the SDK's
`ManualSummarizationSkippedError`, which rendered as the generic admin
error. It now maps to a typed `compaction_skipped` payload with the reason,
and a run that ends with neither a summary nor a recorded error fails as
`compaction_failed`; the Error component localizes both. A run that already
recorded why it stopped keeps that error part instead of failing twice.

* 🗜️ fix: Anchor a Compaction on the Leaf Everywhere It Is Read

Review round 1.

- The client sent the leaf's parent as `parentMessageId`, which the
  controller treats as the anchor, so the summary would have skipped the
  latest reply and landed as its sibling. The leaf's own id is now both the
  placeholder's parent and the server-side anchor.
- A compaction has no user message of its own, and every consumer of the
  job's user-message slot now knows it: the error path parents its row on
  the loaded anchor and never upserts the leaf, and the job records the
  regenerate shape so a reconnecting client rebuilds the turn under the
  leaf instead of recreating it as a user message.
- The controller no longer reads the anchor before the branch is loaded;
  `BaseClient` validates it against the history it loads anyway and
  answers 404 for a missing leaf or a typed `nothing_to_summarize` for a
  finished compaction. That predicate is shared through the data provider
  and ignores a summary still streaming or one that failed, so an
  interrupted compaction can be retried.
- A compaction never consumes files staged in the composer, the action is
  shown only when the server advertises `compactionEnabled`, and the
  in-flight marker is feature-local Jotai state rather than a read of the
  Recoil submission store.

* 🗜️ fix: Keep a Compaction Turn to Its Summary

Review round 2, plus the class it belongs to. A compaction submits no user
turn, so nothing that keys off one may run: the memory pass no longer runs
over the history (it would have spent a model call and could repeat memory
writes), and skill primes are no longer injected into the transcript the
run is about to summarize.

The client's in-flight marker is also reconciled on mount: a compaction
that finished while the view was away left the marker set, and the next
ordinary turn in that conversation would have shown as compacting.

* 🧹 chore: Sort Imports in the Compaction Hook Spec

* 🔧 chore: Update @librechat/agents dependency to version 3.8.1 in package-lock.json and package.json files
2026-09-07 21:51:54 -04:00
Danny Avila
4b3a6eaf0e
🪧 feat: Surface Conversation Code Approval Modes (#15703)
* feat: Add conversation code approval modes

* refactor: Reuse shared code approval types

* fix: Scope approval selector to stateful agents

* fix: harden code approval state propagation

* fix: fail closed during approval discovery

* test: cover approval mode acceptance

* test: use visible approval mode label

* test: drive approval menu by keyboard

* test: expose accept edits in BYOM acceptance

* fix: read approval mode atomically on send

* fix: align code modes with endpoint policy

* fix: initialize code limiters at startup
2026-09-07 12:24:29 -04:00
Danny Avila
e370ce4b21
🎒 fix: Bound Agent Attachment Context (#15694)
Some checks are pending
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Codegraph E2E Votes / vote (full suite) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Client build recovery regression (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
2026-09-07 08:16:34 -04:00
Danny Avila
29971f188a
🧺 fix: Skip Priming Denied File Search Resources (#15699)
#15691 paired every read of `AgentCapabilities.execute_code` / `file_search`
with its role grant, and skipped `execute_code` from the resend-file priming
when `RUN_CODE` was denied. It left the `file_search` half: the grant was not
available inside `initializeAgent`, so a role denied `FILE_SEARCH` still had
its prior-turn search files re-hydrated on every resend.

Priming is not free. The files are fetched, `updateFilesUsage` bumps their
counters, and `primeResources` builds `tool_resources.file_search` — all for
a tool the loader is about to drop. A deployment with the capability off paid
the same cost.

`InitializeAgentParams.fileSearchAvailable` carries the capability AND the
grant, resolved from the same single `resolveToolRoleGrants` read that already
answers `codeEnvAvailable`, so pairing the second flag costs no extra role
lookup. Every initializer that resolves grants forwards it: the chat path and
its handoff, added-convo and discovery hand-offs, both API routes, and the
OpenAI-compatible embedder route. Absent leaves priming unconditional, so an
embedder that resolves no grant keeps its current behavior.

The loop that selected the resend tool resources becomes
`resolveResendToolResources`, which makes both halves of the gate testable
rather than reachable only through a full agent initialization.

The memory agent is untouched: it passes no `conversationId`, so it never
reaches this priming.

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-07 07:56:23 -04:00
Danny Avila
a3fc3b9dbf
🚧 fix: Gate File Search and Run Code by Role (#15691)
* fix: enforce FILE_SEARCH role permission server-side

The FILE_SEARCH role permission is stored, served by GET /api/roles/:name and
settable through the admin API, but nothing ever checks it.
PermissionTypes.FILE_SEARCH occurs zero times under api/server; the three
occurrences in @librechat/api are all in the interface-to-role sync, which
writes the permission rather than checking it.

Measured on v0.8.8-rc1 and confirmed unchanged in rc2: a user whose role has
FILE_SEARCH.USE = false can still upload a document with
tool_resource=file_search and gets 200 with "embedded": true. The same user
calling execute_code correctly gets 403.

Two gates, both mirroring toolAccessPermType in ~/server/controllers/tools.js:

* Upload (api/server/routes/files/files.js): a tool-resource-to-permission map
  checked before any branching, so it also covers the assistants path. Returns
  403 with the same log line as the RUN_CODE gate. execute_code is included
  because it had the same hole: the tool CALL was gated, the upload was not.

* Tool loading (api/app/clients/tools/util/handleTools.js): checked outside the
  lazy loader so a denied user never gets the tool equipped, rather than one
  that fails when called. Fails closed if the permission check itself throws.
  All four required imports were already present in that file, next to an
  existing FILE_CITATIONS check.

Both changes live in /api (JavaScript) rather than /packages/api (TypeScript)
as CLAUDE.md prefers for new backend code: each mirrors an existing pattern in
exactly these files, and a second permission gate in another language and
package would be harder to keep in step with the first.

Tests: api/app/clients/tools/util/handleTools.fileSearchPermission.test.js
covers permit, deny, the log line, and the fail-closed path.

* fixup! fix: enforce FILE_SEARCH role permission server-side

* 🔐 fix: Gate `file_search` and `execute_code` on Role Permissions

The `FILE_SEARCH` gate added in the previous commit lives in
`handleTools.loadTools`, which `loadAgentTools` only reaches when
`definitionsOnly` is false. That default is false on the chat path
(`Endpoints/agents/initialize.js`) but true on the responses and
OpenAI-compatible controllers, so on those paths a denied user still got
the tool definition advertised to the model and their files primed by
`primeSearchFiles`, and the call failed later in `loadToolsForExecution` —
the "gets one that fails when called" outcome the gate set out to avoid.

Move the decision to the capability filters that both loaders already run,
mirroring how `canUseMCP` resolves the `MCP_SERVERS` permission ahead of the
synchronous filter. `AgentCapabilities` stays the instance-wide deployment
switch; the role grant is a second condition a tool has to clear. Because
`hasFileSearch`/`hasExecuteCode` derive from the filtered list, priming is
skipped for a denied user too.

`RUN_CODE` had the same hole: `toolAccessPermType` in
`~/server/controllers/tools.js` gates only `POST /tools/:toolId/call`, not
the agent run, so a role without `RUN_CODE.USE` could still execute code
through an agent. Both tools go through the same map.

Checks use `checkAccessWithRequestCache` and run only for tools whose
capability is already enabled, so a run costs at most one role read. A check
that throws denies the tool.

Also formats the test file added in the previous commit, which Prettier
rejects as-is.

* 🔐 fix: Close the Remaining `RUN_CODE` and `FILE_SEARCH` Bypasses

Codex review of the previous commit found four ways past the gates. All four
share a cause: the permission map was copied per call site, so every boundary
that was not copied into stayed open.

Moves the maps and the check into `packages/api/src/tools/rolePermissions.ts`,
per CLAUDE.md ("all new backend code must be TypeScript in `/packages/api`",
"keep `/api` changes to the absolute minimum"), and points the four `/api`
boundaries at it.

- `handleTools.loadTools` now gates every tool in `toolRolePermissions`, not
  just `file_search`. It is the shared boundary the Assistants required-action
  flow crosses via `processRequiredActions`, which never passes the agent
  capability filter — so a legacy Assistant with a raw function named
  `execute_code` ran arbitrary code for a role denied `RUN_CODE`.

- The check is now request-cached (`checkAccessWithRequestCache`). The previous
  `checkAccess` call omitted `req`, so the agent path resolved the same grant
  twice and issued a second serial `getRoleByName` during chat startup, against
  the rule in AGENTS.md.

- `codeExecutionEnabled` is gated by the role result at all three loaders, not
  only the `execute_code` entry in the filtered list. It drives tool
  classification and the programmatic bash tool, so an agent pairing
  `execute_code` with an MCP `code_execution` tool still advertised and
  instantiated `run_tools_with_bash` for a denied role.

- The upload map covers `EToolResources.code_interpreter`, which the Assistants
  builder posts instead of `execute_code`, and native `code_interpreter` /
  `file_search` tools are dropped when an assistant is created or updated.
  Those run inside the provider and reach neither loader, so configuration time
  is the only place they can be gated.

Renames `handleTools.fileSearchPermission.test.js` to
`handleTools.rolePermissions.test.js` — it now covers both tools.

* 🔐 fix: Gate the Image Upload Route and the v1 Assistant Writers

Second Codex round found the same shape again: boundaries the map had not been
wired into. Adds two shared helpers next to the maps in
`packages/api/src/tools/rolePermissions.ts` so a new upload handler or assistant
writer gets the check by calling one function.

- `/files/images` accepts `tool_resource` and routes agent uploads to
  `processAgentFileUpload` on its own. The Code Files UI sends images there, so
  every image was a way around the upload boundary for a role denied
  `RUN_CODE`. Both upload routes now call
  `checkToolResourceUploadPermission`.

- That helper passes `req`, so the role read joins the request cache. The
  previous `checkAccess` call omitted it, and an allowed Assistants upload goes
  on to `processFileUpload` → `addResourceFileId` → `updateAssistant`, whose own
  check does pass `req` — two serial lookups per upload, against AGENTS.md.

- `/assistants/v1` is still mounted and its `createAssistant` / `patchAssistant`
  write native tools straight to the provider. Both now filter through
  `resolveAssistantToolPermissions`, which v2 also uses in place of its local
  copy.

Run-time enforcement for native assistant tools is deliberately not here: it
means overriding `body.tools` at `createRun` in both chat controllers, which
changes run semantics, and is better argued on its own.

* 🔐 fix: Gate Legacy `retrieval` and the Code-Environment File Tools

Third Codex round, same shape twice more.

- The v1 assistant builder submits `{ type: 'retrieval' }` where v2 submits
  `file_search` (`AssistantPanel.tsx:203`). Only the v2 spelling was mapped, so
  `resolveAssistantToolPermissions` treated legacy retrieval as ungated and both
  v1 writers preserved it for a role denied `FILE_SEARCH`. Both spellings now
  answer to the same grant.

- `codeEnvAvailable` in the agent initializer was capability-only, and
  `initializeAgent` rebuilds `bash_tool`, `read_file` and the workspace file
  tools from it — after the tool loader has already dropped `execute_code` for a
  denied role. The bash gate stops command execution, but those handlers still
  read, search, create and edit files in an attached code environment. The flag
  now carries the role grant, and short-circuits before the role read when the
  deployment has the capability off.

* 🔐 fix: Resolve Tool Grants Once Per Request and Pair Every Capability Gate

Four review rounds found thirteen issues, all one class: a boundary the
permission check had not been copied into. Rounds 2 and 3 each found gaps
created by the previous round's fix, and a manual sweep of tool constructors
and upload routes still missed the `codeEnvAvailable` family entirely — because
the thing worth enumerating is not "paths that reach a tool" but "reads of the
capability".

There are 28 such reads. This replaces per-site permission checks with one
resolution per request, pairs every read that is a gate, and pins the list so a
new one cannot be added silently.

- `resolveToolRoleGrants` resolves `RUN_CODE` and `FILE_SEARCH` together and
  memoizes on the request. Both perf findings disappear by construction: gates
  share one role read instead of each issuing its own.

- Newly paired gates: `codeEnvAvailable` in the OpenAI-compatible, Responses and
  memory-agent initializers (`initializeAgent` rebuilds `bash_tool`, `read_file`
  and the workspace file tools from it, and hands their handlers the code
  environment); the capability checks in agent upload processing and in
  agent-management upload purposes; and the library chat-completion service,
  behind an optional `getRoleByName` dependency so embedders are not broken.

- The v1 Knowledge upload posts `assistant_id` with no `tool_resource`, so there
  is no resource to authorize. It now reads the assistant's own native tools and
  requires their grants, instead of treating a missing resource as unrestricted.

- The startup role read moved off the critical path into the existing
  `Promise.all`, and the direct tool-call check passes `req` so the shared
  loader gate reuses its result rather than repeating the lookup.

- `toolCapabilityGates.spec.js` pins every file that reads either capability
  with a count and a reason. A new read fails the suite until it is classified,
  so the next boundary announces itself instead of waiting for a reviewer.

* 🔐 fix: Abort Assistant Writes on Role-Lookup Failure, Authorize Legacy Uploads First

Round 5 found no missed boundary — the inventory held. All three findings are
about how the gates behave.

- Failing closed is right where a denial blocks the operation, and wrong where a
  denial instead filters a payload the caller persists. A transient role-store
  outage during an assistant create or patch was silently stripping
  `code_interpreter` / `file_search` / `retrieval` and saving the result, turning
  a momentary failure into permanent config loss. `checkToolRolePermission`
  gains `throwOnError`, and `resolveAssistantToolPermissions` uses it: every one
  of its callers either persists the filtered list or rejects the request, so a
  lookup failure has to propagate.

- The legacy-assistant upload gate ran after `sanitizedUploadFn` had already
  pushed the file to the provider, so a denied role left an untracked remote file
  and got a 500 for what is a 403. Moved to the route, next to the tool-resource
  gate, before any bytes are sent.

- `resendFiles` hydration derived its resource set from unfiltered `agent.tools`,
  so a denied role still paid the thread walk and code-file reads for a tool
  about to be dropped. The `execute_code` half now keys off
  `effectiveCodeEnvAvailable`, which already carries the grant.

The `file_search` half of that last one needs the grant threaded into
`initializeAgent`, which is plumbing in the most delicate file here for a latency
win on an already-correct path — deliberately left for a follow-up.

* 🧪 fix: Declare `resolveToolRoleGrants` in the Upload Spec's Module Stub

`Tests: api (shard 2/3)` failed on `a0b38c3`: `process.spec.js` stubs
`@librechat/api` wholesale, so the `resolveToolRoleGrants` call added to the
upload gate resolved to undefined and threw. Five failures in
`processAgentFileUpload`, plus one cascading `processFileURL` assertion from the
same suite.

The gate was verified through its own spec and the routes above it, but not
through the spec of the file it lives in — `process.spec.js` was never run
locally. Every spec belonging to a file this PR touches now has been, and the
mongodb-backed ones that still cannot run here were checked statically for the
same stub shape: all but `process.integration.spec.js` spread `requireActual`,
and that one never reaches these paths.

* ⚡ fix: Skip the Role Lookup When Code Execution Is Disabled

The browser initializer already guards this; the OpenAI-compatible and Responses
controllers did not, so every request on those endpoints issued a role read whose
result the capability short-circuit then discarded. Both now start the lookup
only when the deployment has `execute_code` enabled, matching the third.

* ⚡ fix: Drop Three Redundant Reads on the Gated Paths

- The memory initializer resolved grants unconditionally, so a deployment
  without `execute_code` paid a role read for a flag that could only be false.
  Guarded like the three chat initializers.

- Agent-management upload purposes resolved grants before `checkCapability`, so
  a purpose the deployment has switched off paid a role read on the way to being
  rejected. Capability first, then the grant.

- The legacy-assistant preflight builds an OpenAI client to read the assistant's
  tools, and `processFileUpload` then built a second one — re-reading the user's
  key expiry and values. The preflight now hands its client on, and processing
  builds one only when it wasn't given one.

---------

Co-authored-by: Paul <200737214+SSIG-IT@users.noreply.github.com>
2026-09-07 07:03:22 -04:00
Danny Avila
0b9dc209b0
🧫 fix: Verify Early Stream Recovery (#15676)
* feat: harden early buffer recovery observability

* fix: fence recovery to emitted frontier

* fix: close recovery observability races

* fix: require atomic recovery capabilities

* fix: fail incomplete recovery attachments closed

* fix: preserve legacy store contract

* fix: correlate failed overflow persistence

* fix: break recovery type dependency cycle

* fix: reconcile distributed recovery lifecycle

* fix: preserve content snapshot contract

* fix: harden cross-replica recovery lifecycle

* fix: lease recovery subscriber state

* fix: close recovery lifecycle edge cases

* fix: close recovery validation races

* test: align subscriber lease cleanup

* fix: harden subscriber lease lifecycle

* fix: finalize subscriber lease handoffs

* fix: reconcile recovery error replacements

* fix: preserve durable recovery frontier

* test: expect durable frontier gaps

* fix: scope durable snapshot protocol

* fix: trust durable terminal recovery payloads

* fix: close overflow recovery rollout races

* test: bound overflow race fixture memory

* fix: bound overflow marker refresh

* test: reduce recovery fixture memory

* fix: fence overflow recovery admission

* fix: close overflow recovery admission races

* fix: scope overflow admission fencing

* fix: preserve owner replay after remote admission

* test: await pre-admission append fencing

* test: reflect pre-admission durability
2026-09-06 22:28:17 -04:00
aeyeopsdev
88116f7710
🫠 fix: Surface Bedrock Content Filter Refusals (#15647)
Some checks are pending
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Codegraph E2E Votes / vote (full suite) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Client build recovery regression (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
Sync Locize Translations & Create Translation PR / Sync Translation Keys with Locize (push) Waiting to run
Sync Locize Translations & Create Translation PR / Create Translation PR on Version Published (push) Blocked by required conditions
* fix: surface Bedrock content-filtered responses

* refactor: extract model refusal metadata

* test: preserve refusal helper in agent callback mock

---------

Co-authored-by: aeyeopsdev <275853971+aeyeopsdev@users.noreply.github.com>
Co-authored-by: Danny Avila <danny@librechat.ai>
2026-09-06 17:39:02 -04:00
Danny Avila
b181ef0232
🪬 feat: Configure Langfuse Trace User Identity and Metadata (#15667)
* 🪪 feat: Configurable Langfuse Trace User Identity and Metadata

* 🪪 fix: Prefer createRun's conversationId and warn once on an unset userIdField

* 🪪 fix: Validate Langfuse trace field names at the point of use

* 🧹 chore: Sort identity imports

* 🪪 fix: Source the trace model label from the initializer, not a prompt-affecting option

* 🧪 fix: Build the trace context without a prototype so partial client contexts resume

* 📦 chore: Bump `@librechat/agents` to v3.8.0 for the Langfuse trace userId override
2026-09-06 17:30:23 -04:00
Marco Beretta
c9d208ad3b
🧰 feat: Unify Tool Activity, Reasoning, Search, and Agent Workflows (#14546)
* feat: Group Reasoning with Tool Calls and Polish Activity UI

- Treat reasoning (Thoughts) as transparent to tool grouping so interleaved
  thoughts fold into the tool group instead of splitting it
- Group a lone tool call that has reasoning (e.g. a skill) so it gets the
  same collapsible chrome as multi-tool groups
- Count only real tool calls for the group header; add a reasoning indicator
  and a singular 'Used 1 tool' label
- Rework the in-group Thoughts panel: tool-row sizing, rounded content,
  header copy button, and a floating collapse/copy bar
- Round the floating thinking-bar buttons
- Refine the agent handoff row and instructions panel with consistent
  spacing and a copy affordance

* feat: Move subagent runs to an artifacts-style side panel and polish reasoning UI

- Replace the subagent dialog with a right-side panel that shares the
  artifacts slot (currentSubagentRunId + subagentPanelVisibility atoms,
  a subagentRunsState registry, and a useOpenRightPanel cross-clear so the
  two panels are mutually exclusive)
- Rebuild the inline subagent card to be tool-consistent, preview a single
  live/result line, and open the panel (auto-focusing on stream arrival)
- Relocate the originating prompt to a collapsed, smoothly-animated
  disclosure under the panel header
- Gate the Thoughts copy button to expanded state and move the floating
  bar to a scroll-out reveal, matching the code-block pattern
- Fix the reasoning expand/collapse jump by animating the trailing gap
  inside the grid track instead of an expand-only margin

* fix(client): handle singular grouped tool labels

* refactor(client): unify tool row disclosure styling in a shared module

Extract the hover-reveal chevron and expanded panel spacing into
disclosure.ts and align every tool activity row on the same layout:
h-5 header, my-1 rhythm, full-width click target, and a 200ms chevron
rotation. Rows rendered through ProgressText now stretch across the
message column (the absolute content layer was shrink-wrapping to the
text), and the copy buttons in thinking and output panels anchor to
the row instead of the panel corner.

* fix(client): friendly labels and correct arg parsing for native tools

Map skill, read_file, create_file, edit_file, set_memory, and
delete_memory to localized display names so summaries stop showing raw
tool ids, and give the memory tools the Brain icon the Memories panel
already uses. read_file and skill rows parse the arg the backend
schemas actually emit (path, with file_path as a legacy fallback;
skillName) and fall back to a generic noun instead of rendering an
empty name in their labels.

* feat(client): outcome-based tool group summaries

Group headers now describe the activity performed: homogeneous search
groups read "Searched the web" or "Searched web and files", mixed
groups read "Ran N actions" with per-label repeat counts (Create File
x2) and a failure tally in the detail line. Generic tool rows resolve
their label through getToolDisplayLabel, the OAuth trust warning moved
into a shared ToolAuthWarning that a group renders once instead of per
call, and the group body is a flex column so row margins stop
collapsing unevenly between rows.

* feat(client): render file edits as a structured diff view

Replace the highlighted-text diff in file authoring output with a
line-based renderer: red and green tinted rows with +/- gutters,
old/new line numbers when hunk headers carry them, and diff noise
stripped (file headers, streamed old_text/new_text markers, bare @@
separators become dividers). The code window header shows the file
name with +N/-N change stats next to Copy Code, and file authoring
rows adopt the path-first arg parsing and shared panel spacing.

* refactor(client): align memory updates with the standard tool row

Rebuild MemoryArtifacts on the shared disclosure row (useExpandCollapse
grid animation, hover-reveal chevron, h-5 header) in place of its
bespoke ResizeObserver height animation, and simplify the expanded
panel: section headings dropped in favor of bold memory keys, a single
p-3 inset instead of double padding, and the now-unused heading
translation keys removed.

* fix(client): gate retrieval expansion on renderable results

The row offered an expand affordance whenever raw output existed even
when no sources parsed, opening an empty panel. Expansion now keys off
parsed results, which also covers attachment-only sources that arrive
without text output, and collapses if results disappear.

* style(client): soften the message nav hover tooltip

Rounder corners and the light border weight to match the rest of the
floating surfaces.

* fix(client): compact single-number gutter in diff view

The dual old/new gutters left one column blank on every add or delete
row, reading as a stray number floating far from its marker. Each row
now shows the one relevant line number (old for removals, new
otherwise) right beside the +/- marker, and the scroll container is
vertical-only since lines wrap.

* feat(client): dedicated card for memory tool calls

set_memory and delete_memory rendered through the generic tool card,
reading "Ran Save Memory" with raw parameter chips like an unknown MCP
tool. A new MemoryCall part gives them first-class rows: "Saved
memory" / "Deleted memory" with the key as a quiet subtitle, the
Brain icon, and an expanded panel that mirrors the memory attachment
display (bold uppercase key over the stored value, or a deletion note),
with error output shown inline when a write fails.

* style(client): gap between the web search row and its source list

The expanded source panel sat flush against the 22px favicon stack,
which overflows the 20px row. The panel now opens with a 6px top
margin while the row keeps the shared my-1 rhythm.

* feat(client): richer web search source list

The panel only showed favicon, title, and domain while the search
artifact carries much more. Source rows now include the result snippet
(clamped to two lines) and date under the domain, and a Serper answer
box renders as a lead card above the list with its title and snippet.
Streaming behavior is unchanged; the answer box is attachment-only
since it never carries citation anchors.

* refactor(client): move web search answer box into a details hover card

The inline answer card read as assistant prose sitting inside the
source list. The panel is back to sources only; an Info trigger at the
right edge of the row (hover-revealed like the chevron, focus-openable
for keyboard) opens a hover card with the search query, the source
count, and the provider answer box when present. WebSearch now
receives the tool call args to surface the query.

* feat(client): image, shopping, and place verticals in web search results

Serper vertical results were parsed into the artifact and dropped.
The expanded panel now renders them when present: an image strip of
rounded thumbnails at true aspect ratios (sized from thumbnail
dimensions, no layout shift), a shopping card carousel with product
image, title, price and store, delivery note, and star rating, and a
place list with name, category, address, and rating. All link out,
use semantic lists with localized labels, and cap item counts.
Expansion now keys off any renderable content, so a verticals-only
search still opens.

* style(client): help cursor on the retrieval relevance badge

The badge sits inside a clickable row, so it inherited the pointer
cursor while only offering an explanatory tooltip.

* style(client): strip link underlines in web search verticals

The image and shopping anchors sit inside the markdown prose scope, so
every label rendered with the blue link underline.

* feat(client): surface search verticals outside tool disclosures

Image, shopping, and place results were only visible after expanding
the web search row, and disappeared entirely inside a collapsed tool
group. The strips moved into a shared verticals module that renders
in two spots following the attachment pattern: always below the row
for an ungrouped search, and hoisted below the group (visible while
collapsed) for grouped calls, where the row suppresses its own copy
via hideAttachments. The disclosure panel is back to sources only.

* feat(client): platform-native map links on place results

Place rows were the only vertical without a destination. Each row now
links out to the user's native maps app: Apple devices (detected via
the existing isMacPlatform check) get maps.apple.com with the query
and coordinates, everything else gets a Google Maps search link. Both
are keyless https links that degrade to a web map, so a misdetected
platform still lands somewhere useful. Rows pick up the same hover
treatment as the other linked results.

* fix(client): pin the bash copy button while the command scrolls

The button lived inside the scroll container with sticky/float
positioning, so horizontal scrolling dragged it through the command
text. It now sits absolutely in a non-scrolling wrapper around the
scroller and stays in the corner on both axes.

* feat(client): add view-transition morph helper for composer surfaces

Wrap a state update in startViewTransition (with a synchronous flush) so
elements sharing a view-transition-name animate their position, size and
shape between two states instead of swapping.

The composer band gets its own named, opaque snapshot group stacked above
the morphing element: without it a surface travelling between the thread
and the composer paints over the input and bleeds through the strip below
it. Falls back to a plain update where the API is unavailable and for
reduced-motion users.

* style(client): rebuild the ask question surfaces on shared option rows

The popover and the chat card rendered the same question two different
ways: numbered rows in one, wrapped chip buttons in the other, and the
panel was painted with hardcoded white/gray instead of theme tokens.

Both surfaces now render one AskOptions list, so numbering, check badges,
rounding and hover states match wherever a question appears. The card
groups its prompt with the description, styles the answer box like the
composer, and gains a Skip button beside Submit so declining does not
require the popover. While the popover holds the question the card keeps
a hidden copy of itself in the thread, reserving the exact space the card
will need so nothing reflows when the question moves back.

* refactor(client): make one control move a question between chat and composer

The popover carried both a chevron and a close button. Both left the
question pending and both moved it into the chat, so their only real
difference was invisible: the chevron kept the composer wired up as the
answer box while the close button released it. Two icons for one visible
outcome, with the meaning hidden in a placeholder change somewhere else.

Collapsing now does both jobs at once. Moving a question to the chat hands
the composer back for normal messages, and the card's chevron re-arms it,
so the popover's visibility and the composer's role can never disagree.
Escape maps to the same path and the dismissed-ids state is gone. Both
chevrons get a tooltip and a matching label, since no glyph conveys this.

Also fixes two behaviours found along the way: the card's Skip was a
silent no-op once the question left the popover, because it routed through
a helper gated on answer mode instead of the live pause, and clicking a
multi-select row moved the keyboard highlight, leaving a row painted as
selected after it was unchecked.

* style(client): fix changed-file lint formatting

* style(client): align tool call import order

* fix(client): render handoff instructions as readable context

* test: stabilize full test suite

* test(e2e): align assertions with action groups

* fix: preserve tool run and answer state

* fix: sync subagent and answer handoffs

* fix(client): keep summary parts stable through failed summarize rounds

Failed summarize completions spliced the in-flight summary part out of the
content array, remounting every later index-keyed part (collapsing whatever
the user had expanded mid-stream) and breaking the content-position ==
step-index invariant that streaming writes rely on. Finalize the part in
place instead and scope completion to the owning step's slot so
back-to-back rounds cannot clobber a newer in-flight part.

* fix(api): disable summarization below a viable context budget

A tiny user-set maxContextTokens re-triggers summarization on every graph
step (the summary allocation rounds to nothing and history still
overflows), burning dozens of LLM calls until the recursion limit aborts
the run with an opaque LangGraph error. Fall back to plain pruning under a
1024-token floor so the run either fits or fails fast with the actionable
empty_messages breakdown.

* feat(client): render context budget errors with readable copy

empty_messages and final_context_overflow are structured errors thrown by
the agents SDK, but they were missing from the typed-error dispatch table
and surfaced as raw JSON inside the generic failure text. Map both to
localized copy: empty_messages keeps its token budget breakdown in a
details block, final_context_overflow interpolates the projected and
available token counts.

* Fix ask answer handoff and OAuth warnings

* fix(client): address Codex review findings

* fix(client): address Codex review findings on tool group and summary UI

Replace the raw green/red diff palette in DiffView and CodeWindowHeader with
the existing status-success/status-error semantic roles, so a customized or
versioned theme moves the diff colors with it.

Compose the shared Button primitive in the ask option rows instead of
recreating hover, focus-visible and disabled appearance locally, and swap the
raw text-white on the checked badge for text-on-status.

Prefer a THINK part's generated reasoning_label in the grouped rendering path,
matching the standalone Reasoning path, with the generic Thinking/Thoughts text
only as a fallback.

Derive grouped tool completion and failure from the run step's terminal status
through the shared resolveToolCallPhase helper, so a step the run closed as
failed with empty or benign output no longer reads as running and then reports
success while the card beside it shows a failure.

Carry an explicit failed flag on a summarize round that ended in error, so the
partial deltas already streamed into the slot are no longer presented under the
"Conversation summarized" label.

Also drop seven orphaned English locale keys this branch left unused, which
were failing the unused-i18n static check.

* fix(client): address second round of Codex review findings

Reuse the shared Button primitive for the three question move controls (the
chat card's chevron and both popover chevrons), which each repeated the same
hover, focus-ring, color and rounding recipe locally. Only the icon geometry
stays local.

Drop provider image results that carry neither thumbnailUrl nor imageUrl.
Both are optional in the ImageResult contract, and an unusable entry still
made images.length nonzero, so the card rendered an anchor and img with
undefined destinations instead of omitting the result.

Gate the memory deletion confirmation on a completed phase. The panel opens as
soon as the key streams in and the phase can still settle as cancelled, so
"Memory deleted" was claiming a removal that never happened while the header
correctly read Cancelled.

Key pending answer drafts by action id instead of a single shared slot. With
Save drafts disabled, editing a collapsed question in one conversation and
then editing another paused conversation's question overwrote the only slot,
and the action-scoped reader then showed the first card an empty box with its
unsent answer unrecoverable. Entries are dropped once answered.

* fix(client): address third round of Codex review findings

Reuse the shared CopyButton for the handoff instruction copy control, which
recreated hover, focus-ring, opacity, rounding and copied-state appearance
locally. The icon crossfade and tooltip now come from the shared primitive and
only the reveal-on-hover behavior stays local.

Keep unlabeled commentary out of collapsing tool groups. An unlabeled group
auto-collapses once complete, so folding commentary in hid the assistant's
prose behind a generic action header. The flush now splits the block at
commentary and groups each surrounding run on its own, restoring the shape the
previous fallback had while keeping reasoning folded in.

Drop shopping results without a link and places with nothing to name, for the
same reason the image results are filtered: every provider field is optional,
and an unusable entry still made the array nonempty, so the card rendered an
anchor with no destination that looked actionable but could not be opened.

* fix(client): address fourth round of Codex review findings

Move the disclosure chevron appearance into @librechat/client as
disclosureChevronVariants, owning the hover/focus reveal, the motion and the
open rotation. The four tool, search, memory and reasoning surfaces now pass
their expanded state and keep only icon geometry local, so a change to the
shared behavior reaches all of them. Panel spacing stays feature-local, being
genuine layout.

Require a navigation target on image results, not just an image source: a
thumbnail-only entry passed the previous guard and then rendered a styled
anchor with an undefined href, looking actionable but opening nothing.

Exclude closed run steps from the pending-auth predicate. ToolCall already
hides the sign-in button on a terminal status, so a persisted OAuth call whose
progress never reached 1 left the group showing a trust warning with no
authentication action behind it.

Copy handoff instructions through copy-to-clipboard, as the sibling
message-content controls do. navigator.clipboard is undefined on a non-secure
origin, where dereferencing it threw before the rejection handler could run and
the button silently did nothing.

* fix(client): address fifth round of Codex review findings

Compose the shared Button through HoverCardTrigger's asChild for the web search
details trigger, which recreated rounding, hover colors, focus ring and motion
locally. This also replaces Radix's default anchor with a real button. Only the
hover-card reveal and the icon geometry stay local.

Copy compact reasoning through copy-to-clipboard for the same reason as the
handoff control: navigator.clipboard is undefined on a non-secure origin, where
dereferencing it threw before anything was copied.

Document the streaming-peek fade as a narrowly scoped custom-CSS exception. It
is a mask-image stencil rather than paint, so only its alpha channel is read
and no theme role could meaningfully restyle it.

* fix(client): address sixth round of Codex review findings

Recognize the batched-edit separator pair for every edit in a diff preview.
formatEditPreview writes a `--- old_text N` / `+++ new_text N` pair before each
edit's `@@`, but the parser gated on `inHunk`, which is never reset, so only
the first pair was skipped and every later one was counted as a deletion plus
an addition and rendered as a marker row. Matched by name instead, which leaves
content lines that merely begin with `-` or `+` alone.

Compose the shared Button for the popover's type-below hint, suppressing only
the fill the way Summary's quiet text buttons already do, so the focus ring and
disabled handling come from the shared recipe.

Render an answer box that carries only snippetHighlighted. It is independently
optional from snippet, and the details card opens for any answer box, so such a
result previously showed a heading with an empty body.

* fix(client): match synthetic edit headers only in separator position

Matching the marker names alone was wrong: deleting a real `-- old_text`
comment line, as SQL and Lua use, is prefixed to exactly `--- old_text`, so the
previous guard discarded a genuine changed line from both the preview and the
statistics. The pair is now skipped only in separator position, adjacent and
immediately followed by a hunk header, which no run of genuine content
satisfies. Covered by a test asserting such a pair inside a hunk survives as
content.

Also drops the em dashes from the comments added over this review pass.

* fix(client): address eighth round of Codex review findings

Compose the shared Button for the compact reasoning disclosure, keeping only
the row geometry local so the focus ring and disabled handling come from the
shared recipe.

Lazy-mount the compact reasoning body with useLazyCollapseBody, as the
standalone panel already does. Collapsed is the default whenever thoughts are
hidden, and a streaming THINK part re-renders on every delta, so the full text
was being mounted and laid out behind an invisible panel.

Classify grouped memory failures with isMemoryFailureOutput. Those tools report
failure in prose that generic isError parsing does not recognize, so a
persisted call with no terminal status showed a failed card inside a group
reporting success with no failure count.

Announce the diff statistics to assistive technology. The +/- glyphs carry
their meaning through color and sign, so aria-hidden left screen-reader users
without the change summary; the counts are now also exposed as localized
screen-reader text.

* fix: persist failed summaries and stop double-rendering memory mutations

Stamp the failed marker on the aggregated summary part server-side, mirroring
how ON_RUN_STEP_CLOSED already stamps runStepStatus. The SDK aggregator ignores
a complete event that carries no summary, so an errored round's partial deltas
were saved unmarked and a reload re-rendered the truncated text under
"Conversation summarized".

Skip memory attachments that carry a toolCallId in the message-level
MemoryArtifacts decoration. Those calls already render inline as a MemoryCall
card with the same key, value and outcome, so one mutation appeared twice.
Attachments with no originating call keep the decoration as their only surface.

Keep a reasoning-bearing group expanded when Open Thinking Dropdowns by Default
is on. The folded-in THINK part only renders inside the group body, which is
not even mounted while collapsed, so the preference had no visible effect until
the action group was opened by hand.

Give same-named place results unique keys. Several branches of one chain share
a name and often carry no identifier, so rows whose address, rating and map
target all differ collided on one React key.

* fix: adopt the shared code surface and count background task failures

Register surface-code in the versioned theme registry and use it for the diff
preview. The token, its light and dark CSS values and its Tailwind mapping were
already in place and already consumed by CodeBar, CodeBlock and ResultSwitcher;
only the three theme interfaces, the two bundled themes and DiffView were
missing. DiffView no longer coordinates two unrelated surface roles through a
dark: override, and a custom theme can restyle the code surface centrally.

Include background-task failures in grouped outcomes. A backgrounded bash or
code task reports its verdict through a background_task_status attachment
rather than its output, and its dispatch step keeps a benign handle and usually
closes as completed, so the group reported no failed action beside a card
showing failure. Group metadata now derives that signal with the same helpers
the child card uses, correlated per part so a handoff response repeating a
provider tool-call id across agents still routes correctly.

Require a title on shopping results. A link-only card had no accessible name
and no visible identity: the anchor carried no label, its image is decorative
and the title span rendered empty.

* fix(client): compose shared buttons for two disclosures and seed re-enabled ask drafts

Compose the shared Button for the memory-artifacts and web-search disclosure
rows, keeping only their geometry local. The web-search row keeps its instant
hover by suppressing the recipe's color transition, since the chevron beside it
reveals without a fade and the existing test pins that.

Seed the ask-specific draft when Save drafts is re-enabled. An answer captured
while saving was off has no persisted ask draft for autosave to restore, so
expanding opened an empty composer and the next collapse read that empty value
back over the in-memory answer.

* fix(client): surface cancelled actions and protect the released composer

Track cancellation separately from failure in grouped tool metadata and name it
in the group header. A stopped step is settled and not an error, so the group
auto-collapsed under a success-sounding header with the only cancellation
notice hidden inside the panel it had just closed.

Preserve an ordinary unsent message across an ask handoff. With Save drafts
off, collapsing a question releases the composer; typing there and then moving
the question back overwrote that text with the answer and lost it. The released
text is now stashed per pending action and handed back on the next collapse.

Skip the named view transition for batched questions. Only the single-question
surfaces declare view-transition-name: ask-question, so wrapping a batch
handoff gave the browser nothing to pair and it cross-faded the whole root
instead of morphing the question.

* fix(client): restore the released composer text after answering

Submitting an answer from the expanded card never goes through collapse, so the
ordinary unsent message stashed when the question was moved back was never
handed over and its entry leaked. The resume success path now restores it in
place of the reset when one is stashed, and drops the entry either way. Read
through a ref because the callback settles long after the render that armed it.

* fix(client): stop stacking search snapshots and fix three identity defects

Upsert re-emitted web-search attachments instead of appending them. The search
helper rewrites and re-emits the entire payload after every highlight update,
keeping the same type, toolCallId and turn, and those attachments carry no
file_id so the existing upsert never saw them. Each snapshot was appended, so
collectSearchVerticals concatenated one copy of every image, product and place
per update. Keyed by type, tool call and turn, replacing wholesale since the
incoming payload is complete.

Preserve MCP identity in the tool-call label. function_name has already had the
MCP delimiter and server stripped, so re-parsing it classified an MCP function
sharing a built-in's name as that native tool and both showed and announced an
unrelated label.

Qualify grouped tool identity by agent. Provider tool-call ids repeat across
agents in a handoff transcript, and a lone tool with reasoning now groups too,
so two sibling groups shared one React key and one expansion override.

Compose the shared Button for the handoff disclosure, keeping only its geometry
local.

* refactor(client): build edit previews structurally instead of round-tripping diff text

The args preview was formatted into unified-diff text purely so parseUnifiedDiff
could read it back, and the separators that round trip needed between batched
edits are byte-identical to a real changed line: deleting a source line
`-- old_text` prefixes to exactly `--- old_text`. Neither the marker names nor
their position could tell the two apart, so the parser either inflated the
statistics or dropped a genuine edit.

buildEditPreviewDiff now constructs the preview's lines from the structured
edits, so edit boundaries are structural and no separator is ever emitted.
parseUnifiedDiff is back to parsing only real tool output, where `--- ` and
`+++ ` are genuine file headers, and it no longer special-cases synthetic
markers at all. Copy text comes from a one-way serializer.

Also include agent identity in the web-search snapshot key: handoff agents
repeat provider tool-call ids, so without it one agent's search results
replaced another's.

* fix(client): stop counting empty edit sides as changed lines

A pure deletion (`new_text: ""`) rendered a blank green row and reported one
addition, because `''.split('\n')` yields one element. A trailing newline did
the same at the end of either side. Both sides now go through one helper that
treats an empty side as no rows and a trailing newline as a terminator. The
defect predates the structural builder; it was carried over from the string
preview it replaced.

* fix(client): restore the released text for non-text answers too

Only the free-text path sets consumedComposerText, so gating the restore on it
discarded the stashed ordinary message whenever the user answered by clicking an
option or skipping, while the deletion below ran regardless. The stash is now
restored whenever one exists, independently of the reset condition, and it
outranks whatever the composer holds since that is the answer draft the
submission just consumed.

* fix(client): make group identities collision-proof and localize handoff labels

Disambiguate duplicate tool-group identities by how many earlier groups already
claimed the same provider tool-call id. Those ids repeat across agents in a
handoff transcript and restart per turn within one agent, and a lone tool with
reasoning now groups too, so sibling groups could share a React key and one
expansion override. Occurrence order is stable because groups are append-only,
and the first occurrence keeps the bare id, so an id that never repeats is
unchanged and still survives a content-index shift.

Restore a stashed ask message regardless of the current Save drafts setting. The
stash is only ever created while saving is off, so it never reached the
conversation draft; gating the restore on the setting dropped it whenever the
user enabled saving between expanding and collapsing.

Localize the handoff field labels the SDK defines (instruction, instructions,
context). Any other key is an admin-authored promptKey from the agent graph, so
it stays as written, like an agent's own name.

* fix(client): reject unsafe vertical links and scope group identity message-wide

Filter provider-supplied vertical URLs through the markdown allowlist. Search
result payloads are copied into the attachment without validation, so an image
or shopping target could be `javascript:` or another non-network scheme and the
card handed it straight to href. The same helpers are used when admitting a
result and when rendering it, so the two cannot disagree.

Derive tool-group identity from a message-wide occurrence ordinal instead of a
per-instance counter. Phase slices render through separate nested ContentParts
that share the expansion map, so a per-instance count restarted and let a later
slice inherit an earlier group's override. The ordinal is stable under
content-index shifts, and ordinal 0 keeps the bare id, so a group keeps its
identity when a completing phase moves it into a slice.

Build group attachments as a union. Repeated provider ids inside one group
resolve to the same bucket, so appending per part rendered each file and search
snapshot once per repeated call.

* fix(client): let an output diff supersede a create preview, and guard two edges

A diff in the output now supersedes everything, including a create's authored
content. `create_file` overwriting an existing file returns a summary plus a
unified diff, and preferring the authored content there rendered that diff
twice: once through DiffView and again verbatim as the raw output section. This
restores the precedence the string-preview version had.

Give image tiles distinct React keys. Syndicated images reuse one thumbnail
across results that link to different pages, and grouped searches merge
attachments, so the source alone collided.

Require the composer to still hold the submitted text before restoring the
stashed ask message. The textarea stays editable while the resume is in flight,
so anything typed since is newer than both the stash and the answer.

* fix: address remaining Codex findings after dev rebase

Stamp agent ownership on streaming and final search snapshots. Compose the shared floating thought button. Preserve rebased group behavior, correct stale test selectors, and keep expansion callbacks outside state updaters.

* Resolve follow-up review findings

* Scope grouped background verdicts by execution step

* Fix canonical artifact ownership and frontend review regressions

* Fix terminal answer handoff and encoded edit previews

* style(client): keep the search rows on dev's glyph rail

The rebase onto dev landed both halves of #15643's row rail except in
`WebSearch`, whose completed row had since moved its glyph into a shared
`Button` and whose streaming row kept a 10px gap. Restore the shared
`ROW_GLYPH_SLOT` around the completed row's favicon stack or globe and
drop the streaming row's gap to 8px, so both search rows put their glyph
on the avatar's axis and their text where the header's name starts.

* fix(client): pass the thinking preference into ReasoningCompact

`showThinking` is an app-global display preference the group only reads,
and `ToolCallGroup` already receives it from its host. `ReasoningCompact`
still reached for `showThinkingAtom` itself, coupling a grouped thought
to `~/store` and blocking the move to a feature-owned workspace. It
takes the preference as a required prop now, from the value the group
already holds.

* test(client): pin both web-search rows to the shared glyph rail

The rebase onto dev silently dropped `ROW_GLYPH_SLOT` from the completed
row — its glyph had since moved inside a shared `Button` — and left the
streaming row on a 10px gap, so nothing caught either. `Part.tsx` routes
web search past `ProgressText`, so this renderer owns its glyph and has
to take the slot itself; the test fails on both regressions.

* fix(client): keep grouped markers and folded search media visible

Two things a fold could swallow.

A detached-subagent projection is an empty THINK part flagged
`reasoning_unavailable`, which `Part` renders as a `ReasoningMarker`.
`ToolCallGroup` sent every THINK part to `ReasoningCompact`, which has
no text to show and returns null, so the marker disappeared the moment
its call joined a group. Those parts go back through the standalone
renderer.

A phase hoists its span's media out of the fold, and the nested segment
renders with `hideAttachments` so a `WebSearch` row inside it stands
down for that hoist. The hoist was `AttachmentGroup` alone, which drops
`web_search` attachments outright, so a folded search lost its images,
products and places instead of lifting them out. The card renders
`SearchVerticals` beside the attachment row, mirroring `ToolCallGroup`.

* fix(client): recover a released composer stash on revisit

Recovery of the ordinary unsent message stashed while the card owns the
composer was gated on `lastAnswerableRef` — what this hook happened to
observe. Navigating away mid-resume clears that ref while the stash
rightly stays put, so a resume that succeeded or expired while the user
was elsewhere left nobody to hand the message back: returning to the
conversation found `answerable === false` with no ref, exited early, and
the text sat unreachable in `releasedComposerTextAtom` for the session.

The stash carries its conversation now, and recovery keys on that, so a
revisit is a hand-back like any other exit. Only the exit this hook
armed knows what the composer held when the resume started; on a revisit
an empty composer is the only target that cannot overwrite something
newer, and either way the entry is dropped.
2026-09-06 14:56:50 -04:00
Danny Avila
aeac7a2065
🪪 feat: Add Per-Agent Git Identity (#15628)
* feat: Add per-agent Git identity

* fix: annotate git identity schema

* fix: complete git identity controls

* fix: clear git identity on version restore

* fix: Require a complete agent Git identity

* fix: Complete Git Identity Across Bash And Form Validation

* fix: Discard Incomplete Hidden Git Identity Edits

* fix: validate Git identity across panel lifecycle

* fix: preserve saved Git identity when discarding drafts
2026-09-05 23:56:23 -04:00
Ravi Kumar L
000349681e
🩻 feat(insights): Scope Insights to Authorized Agents (#15549)
Some checks failed
Docker Dev Images Build / publish (push) Has been cancelled
Sync Helm Chart Tags / Ignore non-main push (push) Has been cancelled
Sync Helm Chart Tags / Sync chart tags (push) Has been cancelled
* feat(insights): add agent-scoped access

* fix(insights): exclude unattributed assistant messages

* fix(sharing): key role insight toggles by principal

* fix(sharing): preserve insight grant snapshot

* fix(permissions): preserve insight bits atomically

* fix(permissions): guard insight audit rollback

* fix(insights): keep admin grant controls accessible

* fix(permissions): reconcile duplicate principal updates

* fix(insights): show automatic admin access

* fix(permissions): harden insights access updates

* fix(insights): simplify authorization and preserve client state
2026-09-04 20:16:58 -04:00
Danny Avila
770238f22b
🔣 refactor: Replace Mongo Filters With Typed Criteria (#15580)
* ♻️ refactor: Take Typed Criteria, Not Mongo Filters, for Actions and Assistants

`createActionMethods` and `createAssistantMethods` accepted `FilterQuery<T>`,
putting Mongoose's query language in the package's public surface: every caller
wrote raw Mongo, and no engine other than Mongo could satisfy the signatures.

Both now take domain criteria — `ActionQuery` and `AssistantQuery` — naming
concepts rather than stored fields, with an array meaning "any of these". A
per-domain field map translates them, so `FilterQuery` survives only inside the
two translators.

`buildFilter` throws on a criterion the field map does not cover. Callers in
`api/` are JavaScript and get no compile-time checking, and the server sets
`strictQuery`, under which a silently dropped criterion widens the filter
instead of narrowing it — an unscoped `findOne` returns an arbitrary document
rather than none. Failing closed is the only safe default.

`AssistantQuery.avatarFilepath` covers the avatar-authorization lookup, which
queries a nested path no plain field name reaches.

No behaviour change: every migrated call site produces the same filter as before.

* 🧪 test: Update Avatar Authorization Assertion to Typed Criteria

`validateImages.spec.js` asserted the old `{ 'avatar.filepath': { $in: [...] } }`
call shape for `getAssistant`. The earlier sweep matched on `action_id`,
`agent_id` and `assistant_id`, none of which appear in a dotted avatar path, so
this one assertion was missed.

The `getAgent` assertions in the same file keep the filter shape — that method
still takes a `FilterQuery`.

* 🔒 fix: Reject Unknown Criteria Before Omitting Undefined Ones

`buildFilter` skipped a criterion whose value was `undefined` before checking it
against the field map, so a JavaScript caller misspelling a key that happened to
carry `undefined` — `deleteActions({ agent_id: maybeId })` — produced `{}` and
reached `deleteMany` unscoped. That is the exact failure the guard exists to
prevent, defeated by the order of the two checks.

Validate every key first, then apply the undefined-omission rule. The lookup is
an own-property check so inherited names cannot resolve through the field map's
prototype: `{ toString: 'x' }` previously found `Function.prototype.toString`,
passed the truthiness test, and wrote a garbage filter key instead of throwing.

A recognized criterion left `undefined` is still omitted, so optional parameters
keep working.

* 🔒 fix: Reject Query Fragments as Criteria and Keep the Translator Internal

Three review findings on the criteria translator, all of the same shape: the
guard was narrower than the surface it protects.

Criterion values are now validated as scalars or lists of scalars. `matchAny`
copied any non-array through unchanged, so a JavaScript caller could pass
`{ agentId: { $ne: null } }` and have the operator land verbatim in the filter
— the fail-open case the field map exists to close. `null` is rejected too; it
would have matched documents missing the field entirely.

`matchAny`, `buildFilter` and `FieldMap` are no longer re-exported from the
package barrel. They emit Mongo, and shipping them as public API undercut the
point of the change; they were reachable as `require('@librechat/data-schemas')
.buildFilter`. `OneOrMany` moves to `types/query` because the domain query types
reference it and it names no engine — which also drops the `types` -> `utils`
import.

`loadActionSets` names `ActionQuery` through `import()` so the JSDoc type
actually resolves.
2026-09-04 11:54:21 -04:00
Dustin Healy
5840e2f2ae
🪓 feat: Add Tenant-Scoped Agent Deletion (#15573)
* feat: add Agent Management delete endpoint

* fix: scope agent deletion cleanup by tenant
2026-09-04 09:51:12 -04:00
Dustin Healy
ab0d74b492
✏️ feat: Add Agent Management Update Endpoint (#15566)
Some checks are pending
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Codegraph E2E Votes / vote (full suite) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
* feat: add Agent Management update endpoint

* fix: reject unsupported Agent update values

* test: simplify Agent update mocks
2026-09-04 00:16:57 -04:00
Dustin Healy
2ffa9ec420
➕ feat: Add Agent Management Creation Endpoint (#15564)
* feat: add Agent Management creation endpoint

* 🧫 fix: Reject Null Agent Management Models (#15581)

---------

Co-authored-by: Danny Avila <danny@librechat.ai>
2026-09-03 23:45:04 -04:00
Danny Avila
8a46ca070c
🧊 feat: Persist Context Fading Tier Across Agent Runs (#15505)
* 🧊 feat: Persist Context Fading Tier Across Agent Runs

Carry the pruner's latched context-fading tier from `@librechat/agents`
through `contextMeta` the way `calibrationRatio` already travels, so a
historical tool result keeps the same truncated bytes from one run to the
next and Anthropic's prefix-based prompt cache survives across turns
(danny-avila/agents#497).

- Add `IAgentFadingTier` to the message and conversation `contextMeta`
  types, schemas and the data-provider zod schema
- Add `isAgentFadingTier`, `resolvePersistableFadingTier` and
  `resolveRunContextMeta` in `packages/api`; a tier is persisted once it
  carries information (masking active or a budget below the window), and
  a latched tier is kept even at a neutral calibration ratio
- Seed `createRun({ fadingTier })` from the parent response's contextMeta
  regardless of encoding, since caps are character-based; the field rides
  the existing forward-compatible `runConfig` variable and older SDK
  versions ignore it, as does `Run.getFadingTier` being absent
- Accept a valid `fading` field in event actor context and reject a
  malformed one, matching the calibration checks
- Capture run context meta through one module-level helper for both
  completion paths instead of two inline copies

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WNbgMeR2aZDyhsqAy4L8gF

* 🧊 fix: Seed Fading Tier Across HITL Resume, Validate at the DB Layer

Address review findings on fading tier persistence:

- Leave the "is this tier worth persisting" decision to the SDK, whose
  `Run.getFadingTier()` now returns only informative tiers; comparing
  against the client's window misclassified untouched conversations
  whenever a reserve ratio was configured
- Carry `contextMeta` through the HITL pause projection (staged approval,
  job metadata, resume state) and seed the rebuilt client from it, so a
  paused turn resumes with the same tier and calibration instead of
  re-deriving a shallower one and rewriting the prefix
- Share run seeding between `chatCompletion` and `resumeCompletion`, and
  make capture tolerate partial runs and bare resume contexts
- Validate `contextMeta.fading` in `commitAgentEventActorState` with a
  shared `isAgentFadingTier` guard in data-schemas, so a malformed tier is
  rejected at the DB layer instead of silently cold-starting the actor
- Reuse `IAgentEventActorContextMeta` for `IMessage.contextMeta` instead of
  extending an inline duplicate

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WNbgMeR2aZDyhsqAy4L8gF

* 🧊 test: Cover Resume Seeding From Paused Context Meta

Assert the resume controller seeds the rebuilt client from the context meta
captured at the pause before rebuilding the run, and move the capture
helper's JSDoc back above its function.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WNbgMeR2aZDyhsqAy4L8gF

* 🧹 style: Sort Imports in Fading Tier Plumbing

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WNbgMeR2aZDyhsqAy4L8gF

* 🧊 fix: Persist Fading Tier Through Redis Jobs and Branches

Address Codex and Copilot review findings on fading tier persistence:

- Deserialize `contextMeta` in `RedisJobStore`, whose explicit read mapper
  rebuilt every other pause field but this one, so Redis-backed
  deployments resumed with no tier to seed after every HITL pause
- Copy server-private `contextMeta` onto the assistant message created by
  `POST /api/messages/branch`, so the next turn seeds its pruner the same
  way it would from the parallel source response
- Constrain the `fading` subdocuments in both Mongoose schemas (version
  enum, positive budget, required fields) to match the zod schema
- Throw a distinct "fading tier is invalid" error from both context meta
  validators instead of reporting a calibration failure

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WNbgMeR2aZDyhsqAy4L8gF

* 🧊 fix: Carry Context Meta Through Stop and Re-Pause

Addresses the second Codex pass on the fading-tier persistence:

- A re-pause whose resumed segment has nothing persistable now clears the
  job's `contextMeta` in the same transition instead of leaving the first
  pause's calibration and tier for the next resume to seed from.
- The client publishes the run's live calibration and fading tier onto the
  job after each pre-invoke context snapshot (deduplicated on value), and
  the Stop path copies `jobData.contextMeta` onto the stopped response, so
  a follow-up from a stopped turn keeps the prompt prefix stable.
- Mid-run captures (HITL pause, Stop) read the graph's live state; `Run`
  refreshes its own getters only after the stream settles, so the pause
  used to persist the seeds it started from.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WNbgMeR2aZDyhsqAy4L8gF

* 🧊 fix: Fence Context Meta Publication Ahead of Stop

A Stop handled by another replica reads the job before the owner is
signaled, so a fire-and-forget publish could lose the race, and a run
stopped before its first context snapshot never published the tier it
inherited. The client now publishes the inherited seed before the run
streams or resumes, and the context-usage handler awaits each
snapshot's publish so the write lands before the model call it
describes begins. Failures still only log; the pre-run publish is
optional-called so bare resume contexts keep working.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WNbgMeR2aZDyhsqAy4L8gF

* 🧊 fix: Read Back Context Meta After the Abort Claim

The run owner publishes its context meta ahead of each model call and
awaits the write, so a publish landing between the abort's initial job
read and its terminal claim describes the call whose partial output the
abort snapshot carries. abortJob now reads the same-epoch job back after
the claim and content re-read and takes its context meta, so the stopped
response persists the tier that produced its bytes. The refresh is
best-effort and logs on failure like the content refresh beside it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WNbgMeR2aZDyhsqAy4L8gF

* 🧊 fix: Share In-Flight Context Meta Writes and Clear Neutral Live State

Two snapshot callbacks in a parallel-agent run can capture the same tier
before the first write settles; the publisher now caches the in-flight
promise per serialized value so the second caller awaits the same
durable write instead of treating an uncommitted value as published.
A live snapshot with nothing left to persist after an earlier publish now
writes a neutral record (ratio 1, no tier), since a running job's fields
cannot be deleted through the metadata writer, so a Stop no longer
persists an earlier non-neutral state onto the response. The pre-run
seed publish is unchanged and is told apart from live snapshots by a
flag from the context-usage sink.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WNbgMeR2aZDyhsqAy4L8gF

* 🧊 chore: Drop Unused Rest Parameter in Context Meta Test

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WNbgMeR2aZDyhsqAy4L8gF

* 🧊 feat: Persist Per-Agent Fading Tiers as Compact Context Meta

Reconciles the host with @librechat/agents at 9aacad1a, where graph
history stays canonical and each Run derives a provider-only projection
from the latched tiers. LibreChat therefore persists only compact state:
the calibration ratio, the default agent's tier, and now the per-agent
tiers from Run.getFadingTiers(), stored as validated entries so agent IDs
never become MongoDB field names and restored onto a null-prototype
record for RunConfig.fadingTiers. Truncated messages, canonical tool
content, projection provenance and per-message truncation state are
never persisted; the SDK's latched flag is stripped on capture.

The per-agent map travels everywhere the single tier already did:
response contextMeta, event-actor checkpoint state, HITL pause and
resume job metadata in both stores, the Stop path, and branch creation.
A shared Mongoose definition keeps the message and conversation schemas
identical, the zod schema validates entries, and commitAgentEventActorState
rejects malformed maps. Comments no longer describe graph messages as
truncated; only the provider projection is.

Tests cover: tool results and inputs reach the persisted content parts
at full size; contextMeta carries exactly the compact tier and
calibration fields; a persisted snapshot round-trips into the seeded
RunConfig unchanged and prototype-safe; per-agent tiers survive pause,
Redis job round-trips, and event-actor context validation.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WNbgMeR2aZDyhsqAy4L8gF

* 🧊 fix: Restore Event Actor Types and Publish Seeds Before Abortable Setup

The previous commit's doc rewording in the conversation types dropped the
event-actor interfaces that precede the fading tier, which broke the
declaration bundle in CI; they are restored unchanged.

The inherited context meta is now published onto the job as soon as the
parent's state is loaded and awaited at the top of chatCompletion and
resumeCompletion, ahead of run creation and the other abortable setup
stages, so a Stop during setup still persists the parent's tiers onto the
stopped response. The partial response saved when every subscriber
disconnects now carries the job's context meta like the Stop and pause
paths do. The branch route keeps the source's context meta in the saved
message but strips it from the HTTP response, matching client reads.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WNbgMeR2aZDyhsqAy4L8gF

* 🧊 fix: Serialize Distinct Context Meta Publications

Overlapping snapshots from parallel agents could carry different tiers;
each started its own write and both job stores keep whichever write
finished last, so an older snapshot could overwrite a newer one. Each
distinct publication is now issued after the previous one settles, in
call order, so the newest snapshot is what a Stop reads back. Equal
values still share one write.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WNbgMeR2aZDyhsqAy4L8gF

* 🧊 fix: Project Root Message Reads and Keep Inherited Meta on Setup Failure

The root GET /api/messages paths returned raw documents: the
single-message query read called getMessages without a projection and the
cursor page performed an unprojected find. Both now apply
CLIENT_MESSAGE_SELECT, with getMessagesByCursor accepting a select option,
so the persisted fading tiers never reach the client through the
paginated endpoint; the search-hydration read projects the same way.

A turn that loads a parent's context meta but fails before its run exists
used to replace the inherited meta with the capture of a missing run, so
the persisted error response lost the last valid tiers. Both finalizers
now keep the inherited meta when no run was created while a created run's
neutral state may still clear it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WNbgMeR2aZDyhsqAy4L8gF

* 🧊 refactor: Move Context Meta Publication Into packages/api

The publication coordinator (ordering, deduplication, in-flight sharing,
failure state) now lives in packages/api as createContextMetaPublisher,
with selectRunContextMetaToPublish deciding what a publication carries;
the legacy client keeps only the wiring to the job metadata writer. A
transiently failing write is retried with a short backoff before the
publication is reported and forgotten, so a snapshot's model call no
longer proceeds on the first rejection while the job holds the previous
record. The SDK swallows handler errors, so retrying is the only way to
strengthen the fence without failing the turn.

A terminal save now supplies contextMeta: null when the finished run has
nothing to carry, and saveMessage unsets a previously stored value in
that case, so a disconnect snapshot's record cannot outlive the run that
completed neutrally.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WNbgMeR2aZDyhsqAy4L8gF

* 🧊 fix: Widen the saveMessage Method Type for the Null Unset

The exported method interface still typed contextMeta as the message
field, so the spec exercising the null unset failed typechecking; it now
mirrors the implementation signature.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WNbgMeR2aZDyhsqAy4L8gF

* 🧊 fix: Publish Every Agent's Snapshot, Sanitize Search Hits, Unbound Agent IDs

The context-usage handler now awaits the run's context meta publish for
every ON_CONTEXT_USAGE event, hidden sequential agents included, while
the visible-snapshot bookkeeping and the client emission keep their gate;
a Stop before the next visible snapshot finds the tier a hidden agent's
model call latched. Search results are built from the hydrated hit minus
its server-private contextMeta, since Meilisearch hydration projects every
schema field. The per-agent tier entry guard no longer caps the agent ID
length: ephemeral agent IDs encode endpoint, model and sender without a
bound, and dropping such an entry would let that agent alone re-derive
its tier on the next turn. Also formats the publication spec so the
static checks pass.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WNbgMeR2aZDyhsqAy4L8gF

* 🧊 fix: Unset Context Meta Atomically, Keep Publication State After a Failed Write

- `saveMessage` folds the `contextMeta` unset into the same update that
  persists the terminal response, on both the plain and the provenance-merge
  paths, so a failure between two writes can no longer leave a completed row
  carrying a disconnect snapshot's state.
- `createContextMetaPublisher` tracks whether any record has committed
  separately from the retryable latest publication, so `hasPublished` stays
  true after a later publication exhausts its retries and a following neutral
  snapshot still overwrites the earlier record on the job.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WNbgMeR2aZDyhsqAy4L8gF

* 🧊 fix: Carry Context Meta Through the Resumable Stop Route and Neutral Resumed Completions

- The resumable Stop route copies the refreshed `jobData.contextMeta` onto the
  terminal assistant message it persists, as the abort middleware already
  does, so a stopped resumable response keeps the tiers that produced its
  partial output.
- A resumed run that completes with neutral context state now saves
  `contextMeta: null`, which unsets the paused segment's record instead of
  letting an omitted field keep it on the completed row.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WNbgMeR2aZDyhsqAy4L8gF

* 🧊 fix: Trust Only Server-Authored Context Meta, Unset It on a Neutral Stop, Read It From the Job on Disconnect

- `POST /api/messages/:conversationId` and conversation imports drop any
  client-supplied `contextMeta`, and the run seeds its calibration and fading
  tiers only from a server-authored parent response, so a forged tier can never
  shape a provider projection.
- Both Stop paths save `contextMeta: jobData.contextMeta ?? null`, so a job that
  re-paused with neutral state unsets what an earlier pause stored on the row
  instead of leaving it behind.
- The disconnect partial save reads the same-epoch job record for the run's
  published context meta, since the client-facing resume snapshot never carries
  server-private state.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WNbgMeR2aZDyhsqAy4L8gF

* 🧪 test: Mock the Job Store in the Resume Metadata Spec

The disconnect partial save now reads the same-epoch job record through
`GenerationJobManager.getJobStore()`, so the resume metadata spec's manager
mock provides it as the other disconnect spec already does.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WNbgMeR2aZDyhsqAy4L8gF

* 🧊 fix: Keep Context Meta Off the POST Message Response

`POST /api/messages/:conversationId` returned the saved row verbatim, so a
client write against an existing server-authored message echoed the row's
stored context meta. The route now projects the row through the same client
projection the branch route uses, which drops the server-private field.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WNbgMeR2aZDyhsqAy4L8gF

* 📦 chore: Bump @librechat/agents to 3.7.16 for Persisted Fading Tiers

3.7.16 is the first release that carries danny-avila/agents#497, so
`Run.getFadingTier()` / `getFadingTiers()` now report the latched tier
this branch persists and `RunConfig.fadingTier` / `fadingTiers` seed the
next run from it. The dependency set is unchanged from 3.7.15; only the
package entry moves.

Adds an SDK-backed round trip to the fading spec: a first pruner latches
an informative tier, `resolveRunContextMeta` reduces it to the persisted
shape, and a second pruner seeded from that shape reproduces the first
run's projected tool-exchange bytes under instruction and calibration
drift, while an unseeded pruner under the same drift relaxes its tier and
rewrites them.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WNbgMeR2aZDyhsqAy4L8gF

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-02 20:29:43 -04:00
Danny Avila
29f738dea8
⏭️ feat: Honor an Interrupt Before the Model Has Answered (#15491)
* ⏭️ feat: Honor an Interrupt Before the Model Has Answered

An interrupt armed while the model is still thinking sat as "Interrupting"
until the entire turn finished, then landed as a terminal continuation. The
cause is upstream: the SDK reads `shouldPreempt` once per streamed chunk, and
its seal gate requires non-empty text — so a silent provider is never polled at
all, and a reasoning-only turn is never sealable.

`@librechat/agents` gains a discard-and-restart path for exactly that window
(`HOOK_PREEMPT_RESTART_CAPABLE`). This wires the host half:

- `GenerationJobManager.subscribePreempt` registers run-scoped wake listeners,
  notified after an ACCEPTED arm — local or cross-replica, since both land in
  `armPreemptIds`. Fenced on `createdAt` like every other preempt entry point,
  and a throwing listener never fails the arm a queued steer depends on.
- `createSteerPreemptPoll` hands that channel to the SDK as
  `StreamPreemption.subscribe`, gated on a new `isSteerPreemptRestartSupported`
  probe so an SDK that cannot act on a wake is never handed one.

The wake is a hint only: `isPreemptRequested` stays the single authority, so
the level-triggered contract the seal path depends on is unchanged.

Inert until `@librechat/agents` publishes the restart contract — the probe
returns false against the pinned 3.7.11 and the run keeps today's behavior.

* 🩹 fix: Replay an Already-Armed Preempt on Subscribe

Preempt requests are level-triggered, and the window between a job becoming
steerable and the SDK installing its model-attempt listener is real. An
interrupt landing there was recorded with no callbacks to notify, and on a
silent or reasoning-only turn no later chunk poll may ever run — leaving the
request to wait out the whole turn, the exact stall this channel removes.

`subscribePreempt` now replays an existing arm to the newly registered listener
only, after registration: waking the whole set would re-notify runs that
already looked, and waking before registration would leave a concurrent arm
with nowhere to land. The `createdAt` fence is unchanged and still gates the
replay.

The SDK also reads the level flag once at each attempt's start, so this is
belt-and-braces rather than the sole cover — but it makes the host correct on
its own terms instead of resting on when the SDK happens to look.

* 🔧 chore: Update @librechat/agents dependency to version 3.7.14 in package-lock.json and related package.json files

* 🔧 chore: Update dependencies in package-lock.json and package.json

- Bump versions for @humanfs/core (0.19.1 to 0.19.2), @humanfs/node (0.16.6 to 0.16.8), @xmldom/xmldom (0.8.13 to 0.8.15), and qs (6.15.2 to 6.16.0).
- Add @humanfs/types (0.15.0) as a new dependency for @humanfs/node.
- Update dependencies for side-channel and side-channel-list to their latest versions.
2026-09-02 13:35:52 -04:00
Dustin Healy
0b96fb9f70
🪪 feat: Propagate Tenant to Agent Model Headers (#15521)
* fix: propagate tenant to agent model headers

* fix: propagate tenant across agent model calls
2026-09-02 13:25:38 -04:00
Danny Avila
1c7a172321
🕹️ feat: Configure BYOM Tool Permissions (#15504)
* feat: add configurable BYOM permissions

* test: cover BYOM permission settings live

* fix: harden BYOM permission settings

* perf: reuse principals for environment discovery

* chore: normalize BYOM settings style

* fix: Align BYOM Discovery and Admission

* fix: Harden BYOM Permission Boundaries

* fix: Align BYOM Skill Approval Routing

* fix: Preserve Lazy BYOM Approval Capabilities

* perf: Parallelize Cached Environment Reads
2026-09-02 10:38:00 -04:00
Danny Avila
b1c56239f9
🧤 feat: Enforce Safe BYOM Tool Approvals (#15503)
* feat: add safe default approvals for BYOM code

* fix: preserve safe BYOM approval baseline
2026-09-02 08:53:16 -04:00
Marco Beretta
2cf1007f3c
🧺 feat: Preserve Partial Work at Tool Call Limits (#15486)
* feat: Handle reaching the agent tool-call limit gracefully

When the graph exhausts its per-turn step budget, persist the turn as
unfinished with finish_reason tool_call_limit instead of a red error.
Warn the model as the budget runs low, and offer Keep going or Answer now.

* docs: Add screenshots of the tool-call-limit notice

Light and dark captures of the unfinished-turn card for the PR description.

* style: Tighten the tool-call-limit notice card

Pin dismiss to the top-right with uniform rounding, use a slightly
smaller hit target, and round the card to xl. Refresh the PR screenshots.

* fix: Address Copilot review findings on the step-budget path

Skip empty and subagent-scoped PostToolBatch events when counting
rounds. Drop the double-cast in the notice test helper and coerce the
tool-call-limit finish reason in the Continue-gate spec.

* fix: Address Codex review findings on budget and dismiss

Pass the resolved recursion limit into the OpenAI-compatible
processStream path so the step-budget hook matches the graph.
Reset the notice dismiss state when the displayed message id changes.

* fix: Unblock CI typecheck and import sorting

Declare recursion_limit on the OpenAI service agent type, sort that
file's local imports, and route the notice test context through unknown
so tsc accepts the partial ChatContext fixture.

* fix: Sort remaining PR imports for static checks

* chore: Remove tool-call-limit notice screenshots

* fix: Keep recovery actions from consuming composer drafts

Pass empty file, skill, and quote overrides on Keep going and Answer
now so a staged compose is not attached or drained.
2026-09-01 21:38:02 -04:00
Danny Avila
164f146bdf
🛞 feat: Manage Personal Code Environment Lifecycles (#15369)
* feat: add self-service code worker pairing

* fix: enforce code worker principal boundaries

* fix: separate pairing control planes from execution

* fix: preserve principal worker routing

* fix: pin artifact traffic to code workers

* fix: authenticate code worker selection

* test: mock worker-aware artifact headers

* fix: harden self-service code worker routing

* fix: fail closed for principal code pairing

* feat: manage personal code environments

* fix: harden personal code environment lifecycle

* fix: satisfy backend lifecycle types

* fix: harden principal environment lifecycle and quotas

* fix: fence environment lifecycle races

* fix: reconcile code environment stack

* style: format code execution headers

* fix: reconcile code environment lifecycle

* fix: close self-service pairing gaps

* fix: close code environment reconciliation gaps

* fix: close code environment UI review findings

* fix: satisfy code environment type checks

* fix: route code priming to selected worker

* fix: harden code environment lifecycle fences

* fix: type lease renewal interval

* fix: harden environment lifecycle recovery

* fix: close lifecycle recovery races

* fix: type compensated agent timestamps

* fix: fence lifecycle cleanup by tenant and revision

* fix: scope environment revision fencing
2026-09-01 21:10:05 -04:00
Danny Avila
a3c2277c38
🚧 fix: Narrow Chat MCP Selections to What the Picker May Offer (#15478)
* 🚧 fix: Narrow Chat MCP Selections to What the Picker May Offer

The chat MCP picker offers a server only when the operator has not hidden it
(`chatMenu: false`) and the user reaches it directly rather than through an
agent (`consumeOnly`). Nothing enforced either condition on the request, so a
stale client, a replayed body, or a hand-written one could name any server and
get its tools — `consumeOnly` in particular is a permission the registry derives
per user, so ignoring it let a user reach in plain chat a server they had only
been granted through an agent.

Narrow the picker's selection in the two ephemeral loaders, against the same
predicate the client's `selectableServers` uses. The resolver is injected, so
`packages/api` stays free of the registry and the loaders keep their existing
`deps` shape.

Provenance is why this lives in the loaders rather than at the tool-resolution
chokepoint: only here is a server name known to have come from the picker.
Servers a model spec pins are the operator's own choice and are added after the
narrowing, so pinning a chat-hidden server to a spec keeps working.

`chatMenu` only ever comes from the config tier, so the overlay settles it with
no lookup at all. Lookups for the rest run concurrently and are cached per
server and user. A name the registry cannot resolve — request-tier, declared on
the body and never registered — is kept, as is one whose lookup fails: this
narrows an already-authenticated selection and is not the authorization
boundary.

* 📝 docs: Say What chatMenu Now Bounds

The schema still described `chatMenu` as dropdown visibility alone, which is
misleading now that it also bars a server from the chat selection a request
carries. Spell out both halves, and what it deliberately does not restrict:
agents, and servers a model spec pins.

* 🛡️ fix: Close Four Gaps in the Chat MCP Narrowing

Dedupe before resolving. The selection is request-supplied and the loaders used
to build a `Set` immediately; mapping the raw array first let one body repeat a
name enough times to launch a resolver — registry, cache, and ACL reads, with no
single-flight — per occurrence.

Resolve names through the tool-loading aliases. A configured `private server` is
addressable as `private_server` downstream, so an exact-key lookup let the
normalized spelling walk past a `chatMenu: false` check and still load tools.
Names are returned as sent; only the decision is canonicalized.

Let the request overlay settle `chatMenu`. The config tier is where the flag
lives and is what the picker itself was built from, so an overlay that re-enables
a server now outranks the durable config the registry returns, which was silently
dropping a valid selection. `consumeOnly` still comes from the registry.

Narrow the request body, not just the loader's copy. `applyContextToAgent` reads
`req.body.ephemeralAgent.mcp` directly and prefers it over the agent's tools, so
a hidden server's `serverInstructions` reached the model context even after its
tools were dropped.

* 🧭 fix: Ask the Registry Which MCP Servers the Picker May Offer

Three rounds of review found the same mistake in three disguises: this narrowing
re-derived the registry's tier precedence instead of asking for it. A config
entry was treated as authoritative over a user-DB or process-backed server of the
same name; the alias map was built from config names only, so a DB server named
`private_server` was misrouted to a config `private server`; and the overlay
short-circuit ran before any of that could be consulted.

Resolve the accessible set through `resolveAllMcpConfigs` instead — the same call
behind `GET /api/mcp/servers`, so what the request may use and what the picker
was offered come from one place and cannot drift. Precedence, cross-tier name
collisions, and the config overlay are the registry's job again, and the
selectability test is a single flag check over what it returns.

The result is smaller: no overlay branch, no per-server lookups, one catalog read
regardless of how long the selection is, and aliases built over the whole
accessible set so an exact name always outranks another server's normalized form.

Publish the servers actually in play back onto the request body, spec pins
included. `applyContextToAgent` prefers that list over the agent's tools, so
narrowing to the picker selection alone had started dropping a spec-pinned
server's `serverInstructions` while suppressing a hidden one's.
2026-09-01 18:47:36 -04:00
Danny Avila
51edb2a660
🛫 feat: Enable Self-Service Code Worker Pairing (#15367)
* feat: add self-service code worker pairing

* fix: enforce code worker principal boundaries

* fix: separate pairing control planes from execution

* fix: preserve principal worker routing

* fix: pin artifact traffic to code workers

* fix: authenticate code worker selection

* test: mock worker-aware artifact headers

* fix: harden self-service code worker routing

* fix: fail closed for principal code pairing

* style: format code execution headers

* fix: close self-service pairing gaps

* fix: satisfy code environment type checks
2026-09-01 18:46:33 -04:00