Commit graph

5210 commits

Author SHA1 Message Date
Danny Avila
2ec222f117
🪪 fix: Preserve SAML NameID Bindings (#15254)
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 / build (Dockerfile, lc-dev, node) (push) Waiting to run
Docker Dev Branch Images Build / build (Dockerfile.multi, lc-dev-api, api-build) (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
2026-08-26 10:43:02 -04:00
Danny Avila
10c2e53c27
📮 fix: Screen User-Supplied Structured Tool Endpoints (#15253) 2026-08-26 10:38:56 -04:00
Danny Avila
62a55213f0
🖇️ fix: Bind Model-Spec Authorization to the Loaded Agent (#15256) 2026-08-26 10:38:20 -04:00
Danny Avila
0c959deb99
🧢 fix: Cap Batched HITL Answers Before PII and Moderation (#15257) 2026-08-26 10:10:19 -04:00
Danny Avila
76762a20c4
🪺 fix: Heal MCP HITL Aliases Through Nested Subagents (#15258) 2026-08-26 10:03:41 -04:00
Danny Avila
52fa88fc54
📬 feat: Serialize Bound Actor Event Mailboxes (#15260)
* feat: serialize bound actor event mailboxes

* test: harden actor mailbox batch ordering

* fix: treat batch roots as mailbox authority

* test: pin mailbox replay semantics

* fix: preserve mailbox authority through settlement
2026-08-26 10:02:47 -04:00
Danny Avila
68fc46a055
🪢 feat: Resume Bound Event Actors from Checkpoint Forks (#15227)
* feat: resume event actors from checkpoint forks

* fix: fence event actor checkpoint uncertainty

* fix: satisfy event actor type contracts

* fix: make actor reconciliation recoverable

* fix: preserve event actor lifecycle transitions

* fix: fence event actor lifecycle outcomes

* fix: enforce event actor lifecycle ownership

* fix: retain event actor settlement proof

* 🔒 fix: Retain Event Actor Receipts Through Repair and Bound Their Journal

Repair and compensation deleted the reconciliation row they resolved, which
was the only durable proof that the invocation had already applied an external
action. A delayed duplicate owner could then reacquire the same invocation id
and repeat that action. Both resolutions now retire their receipt to `settled`
and record how it settled, so the same-id tombstone survives; `history_repaired`
and `action_compensated` still force a cold rebuild. Compensation undoes the
effect without re-authorizing the delivery, so a legitimate retry must arrive
under a new invocation id. A retried repair converges on its own receipt.

Bound the journal so a long-lived actor cannot grow its conversation document
without limit: a new fence is admitted only when no active lifecycle row
exists, so a capped push can evict nothing but the oldest settled receipts.

Stop shipping the unbounded source payload on every bound-child continuation.
It rode the delivery body regardless of the feature flag while the sibling
`fire` body deliberately sends event identity alone, so a large webhook payload
could push a previously working delivery past the chat route's body limit. The
actor binds an invocation from identity and never builds the prompt from it.

Blank the positional token map on warm continuations. It is derived from the
full DB history, while a warm run executes on checkpoint-restored state, so its
indices address different messages and the pruner never recounts them —
misattributing cached counts to the wrong messages in both directions.

Keep the replaced-claim exit on its cleanup path when preserving reconciliation
fails: the committing CAS already left a blocking row, so the failed status
upgrade costs provenance, not safety.

* 🧪 test: Pin the Warm Continuation's Map/Summary Asymmetry

Give the warm-continuation client test a populated token map and a real
cross-run summary so its assertions bite: the positional map must arrive
blank (checkpoint-restored state no longer matches DB-derived indices, and
the pruner never recounts a populated entry) while `initialSummary` must
pass through unchanged — it rides the system tail and summarizes
pre-boundary turns that were excluded from the very history the committed
checkpoint was built from, so blanking it would silently drop context no
warm run can recover.

* ⚖️ fix: Honor Compensation in Settlement and Age-Bound the Receipt Journal

A compensated receipt still tombstones its invocation id, but its external
effect was explicitly undone — the terminal handler nonetheless replayed
every settled lifecycle's stored action as authoritative and settled the
public outcome as applied, telling an action-aware source the operation
stands and suppressing the new-invocation retry compensation requires. The
handler now settles a compensated invocation as failed with an explicit
compensation error, overriding even fresh applied run evidence from a
replayed generation; verified and repaired receipts continue to replay
applied.

Receipt eviction is now primarily age-based: a stale same-id owner is
bounded by time, not by how many newer invocations settle, so the previous
count-only slice let a high-rate actor evict a tombstone while its delayed
duplicate owner could still wake and repeat the action. Admission prunes
only settled receipts older than a retention window that dwarfs every
generation, job, and delivery-retry lifetime, and the count cap is demoted
to a raised document-size backstop.

* 🔀 fix: Serialize Compensation Against Settlement and Never Evict Live Receipts

The terminal handler read its lifecycle snapshot, verified history, and then
settled the public outcome — so a compensation resolving the same receipt
during that window lost: the handler settled applied from its stale snapshot
and no retry could ever change the replay-identity-locked outcome. The
receipt's status CAS is now the serialization point: verification resolves
the receipt BEFORE settling, whichever transition wins determines the public
outcome, and a crash between resolve and settle converges through the
retained receipt's replay. The verified-replay probe requires the receipt's
own resolution, so a compensated receipt can never satisfy a verification
retry. This inverts the settle-before-receipt ordering deliberately: that
ordering guarded proof that resolution used to delete, and the receipt now
retains its full action proof through resolution.

The document-size cap is no longer an eviction quota. A receipt inside its
retention window is never discarded: when the journal holds a full cap of
unexpired receipts, new invocations are refused fail-closed until receipts
age out, making duplicate protection and document integrity simultaneous
invariants instead of a rate-dependent trade.

* 🎓 fix: Keep Skill-Bearing Event Actors on the Legacy Path

Skill primes are spliced into the message list directly ahead of the newest
message, and a warm continuation forwards only that newest message — so a
checkpoint-restored actor would keep serving the prime bodies baked in at
its last cold start and never observe an edited or newly attached skill.
Until the actor head carries a context fingerprint that forces a cold
rebuild when the agent's skill context changes, agents with always-apply or
manual skill primes stay on the legacy path, which re-primes fresh bodies
every turn: correct on every event, just never warm.

* 📜 fix: Gate Fork Mode on the Skills Capability, Not Just Request-Time Primes

History-derived re-priming was a third path into the same staleness class:
an actor that previously invoked a skill carries no request-time prime
arrays, yet primeInvokedSkills re-resolves that skill's current body from
history each turn and the warm slice drops the reconstruction — leaving the
checkpoint's old body active after edits. The fork gate now keys on the
priming hook itself (present exactly when the skills capability is enabled)
alongside the request-time arrays, so every skill-body path routes to the
legacy rebuild until #15235's context fingerprint restores warm
continuation for skill-bearing actors.

* 🧾 fix: Capture Applied-Action Proof at Tool Execution, Not After sendMessage

The executor read applied-action evidence from the run-step collection the
instant sendMessage resolved, but that collection is populated
asynchronously — an applied invocation could classify as actionless
(runSteps still empty while the tool result already streamed), discarding
its fork and stranding the actor cold while the terminal handler later
settled the same delivery as applied from the persisted evidence.

Authoritative proof is now recorded in graph context the moment the
expected tool executes: the request-owned recorder observes the tool-end
chain (which ToolNode dispatches synchronously with both input and output)
and applies the same fences as run-step evidence — exact tool name with the
MCP-suffixed form, the declared argument subset against the execution
input, an error-free result, and the background non-execution receipt
exclusion. readAppliedAction consults the receipt first; run-step
inspection remains the fallback for paths that bypass the tool-end chain.

Regression coverage reproduces the observed ordering: the real executor
commits the head from the receipt while run steps are empty, warm-continues
the next event, and never re-executes the action; recorder fences and the
receipt-first controller wiring are covered separately.

* 🎯 fix: Supply Execution Arguments to the Tool End Callback

The live Vertex + MCP canary exposed a contract mismatch the synthetic
fixtures hid: the ON_TOOL_EXECUTE execution path invoked its tool end
callback with output only, while the action recorder must verify the
declared argument subset against the execution input. The receipt never
qualified, every turn fell back to cold history rebuilds, and the
tournament advanced with zero actor heads and zero retained checkpoints
while looking successful.

The execution handler owns both halves at the same moment, so the fix is
at the source rather than a correlation store: ToolEndCallbackData gains
the executed call's input and every callback site passes tc.args. A
handler-level regression drives the real createToolExecuteHandler and
asserts the callback receives both fields; recorder regressions pin the
production shapes — an output-only tool end must starve an
argument-fenced receipt rather than trust an unfenced match, and still
qualifies a name-only expected action.

* 🕵️ fix: Mark Background Deliveries So They Cannot Impersonate Applied Actions

The background-claim callback reports the ORIGINAL tool's name for artifact
attribution on the poll turn that harvests a completed task. A name-only
expected action could therefore be impersonated by work some earlier turn
dispatched: the recorder would attribute that delivery to the current
invocation and commit a head whose state never contained the invocation's
own action. The run-step evidence path never had this hole — it sees the
poll tool's name — so the recorder must match its provenance discipline.

Delivery callbacks now carry an explicit backgroundDelivery marker set at
the one site that rewrites the name, and the recorder ignores marked
deliveries outright. Regressions pin both halves of the contract: the
delivery callback must carry the marker with the poll call's arguments,
and a marked delivery can never qualify even a name-only expected action.

* 🧿 fix: Version Invalidations, Keep Evidence Ahead of Output Policy, Gate Detachable Actions

Three closeout-round findings, each converted into an invariant.

Every legacy-path invalidation now advances a durable epoch — including for
headless and already cold-marked actors, where the marker alone leaves no
CAS-visible trace — and the actor-head CAS requires the epoch observed at
preparation. A concurrently prepared fork whose history predates an
intervening legacy turn can no longer commit past it; the commit reports an
ordinary conflict and journals.

Execution identity is now emitted before post-execution output policy: when
a side-effecting tool succeeds but its returned content is withheld by the
output filter, the callback delivers an outputFiltered receipt with blank
content — the recorder accepts it as proof (rejecting model-detached calls
it cannot distinguish through the blank shape), the artifact path never
sees it, and an applied action is no longer reclassified actionless and
re-executed on retry.

Background-capable expected actions stay off the fork path: dispatch
returns a launch handle every evidence fence correctly rejects, and the
completion is provenance-marked as another turn's work, so a fork would
settle actionless before the external effect lands with nothing to stop a
retry from dispatching it again. The gate mirrors the MCP-suffix name
matching of the evidence path.

* 🚧 fix: Seal the Whole Legacy Turn Behind a Second Epoch Advance

The epoch fenced only the legacy turn's start: a fork preparing after the
begin invalidation but before the turn's message persistence observed the
new epoch and cold marker, rebuilt from history that did not yet contain
the turn, and committed cleanly because nothing advanced the epoch again —
making the incomplete rebuild authoritative and clearing the marker.

Every legacy event turn now seals its invalidation at terminal persistence
with a second epoch advance, on the success, replaced-claim, and error
exits alike. Sealing deliberately carries no quiescence requirement — it
must succeed while a fork fence is active, because that is exactly the
mid-turn race it defeats — and a fork that already committed against the
begin epoch is healed the same way: the seal re-marks the head cold, so
the next event rebuilds with complete history. Seal failure never diverts
the turn's own exit; the begin bump still fences everything prepared
before the turn.

* 🔗 fix: Replace the Best-Effort Epoch Bump With a Durable Legacy-Turn Fence

The second epoch advance could not make a legacy turn atomic, and three
findings shared that root cause: two conditional updates left a headless
gap a fork could create the head inside; the error exit sealed before
saveErrorTurn made the error history durable; and any crash or failure
between persistence and sealing left an incomplete fork authoritative,
because the seal was best-effort and its failure was swallowed.

A legacy turn now carries one durable fence. A token is written before
execution by a single update-pipeline write — no two-write gap, and the
cold marker is applied only where a head exists via $cond/$$REMOVE. While
the token is present no fork may prepare (the adapter refuses) or commit
(the CAS requires its absence), because the turn's messages are not yet
durable. One atomic write clears the exact token and advances the epoch
once history is persisted — after saveErrorTurn on the error exit — and
success, replacement, and error exits all route through it.

Failure is now fail-closed rather than silent: a failed seal leaves the
token set, which keeps blocking forks and is logged as such, and a fence
abandoned by a crashed turn is reclaimed only once stale, advancing the
epoch and marking any head cold so the next event rebuilds from whatever
history actually survived.

* fix: serialize legacy event actor turns

* fix: close legacy actor fence ownership gaps

* fix: preserve legacy actor persistence fences
2026-08-26 08:39:00 -04:00
Ravi Kumar L
56f0cde9a5
🩻 feat(langfuse): add tenant export telemetry (#15247) 2026-08-26 07:38:30 -04:00
Danny Avila
f34a49007d
🔣 fix: Escape SPA Language Attribute (#15248) 2026-08-26 07:37:36 -04:00
Danny Avila
6d8b1cb013
🧢 fix: Bound Tokenizer Work Per Input (#15246) 2026-08-26 07:37:19 -04:00
Danny Avila
cdd4c09076
🧠 fix: Apply the Configured Reasoning Effort to Summarization (#15232)
A summarizer that reuses the main agent's client options silently inherits
the agent's reasoning effort: `summarization.parameters.reasoning_effort` is
a scalar, and every OpenAI-compatible LangChain client reads only `reasoning`
from constructor fields — `reasoning_effort` is a call-time option, so it is
dropped outright. A hidden summary configured for `low` runs at whatever the
agent resolved, and the yaml schema (scalars only) gives users no way to
express the nested shape themselves.

Translate the scalar the way the main flow's `getOpenAIConfig` does, into the
top-level `reasoning` object the client honors. Top-level rather than nested,
because the SDK spreads `parameters` onto the agent's client options: a
`modelKwargs` fragment would replace the agent's `modelKwargs` wholesale,
while `reasoning` merges over an inherited `modelKwargs.reasoning` in
`ChatOpenRouter` and is re-emitted as `reasoning_effort` by Chat Completions.

OpenRouter's adaptive Anthropic models keep the main flow's mapping, where
effort is expressed as `verbosity` rather than `reasoning.effort`.

Also prefer the provider `getOpenAIConfig` detects over the one
`getProviderConfig` reports, so a cross-endpoint summarizer pointed at an
OpenRouter endpoint whose config name isn't `openrouter` builds the same
client the main agent flow builds for it.

Supersedes #15088; thanks to @flamerged for the diagnosis and the OpenRouter
repro.
2026-08-25 23:54:36 -04:00
Marco Beretta
227a99ede8
🧮 fix: Render Google Settings From the Shared Schema and Bound Them Per Model (#14989)
* fix: render Google settings from the shared schema and bound them correctly

Google was the last endpoint hand-rolling its own sliders. The schema was
already there and already wired, only the frontend never used it, so
rendering from it replaces 315 lines with the body OpenAI, Anthropic and
Bedrock share.

That closed a functional gap rather than only moving code: the old form
exposed six fields where the schema declares fifteen, so Resend Files,
Thinking, Thinking Budget, Thinking Level, Grounding with Google Search,
URL Context and File Token Limit were unreachable from a Google preset.
resendFiles is added to the Google schema so its switch round-trips, and
the endpoint type is resolved from the endpoints config, since a preset
for a Google-compatible endpoint need not carry endpointType and would
otherwise blank the panel.

Sharing the controls also meant inheriting their gaps, which this fixes:

- Number settings declared a range that nothing enforced, so a value past
  the provider's ceiling was persisted and rejected later. clampSettingRange
  applies it, and generateDynamicSchema validates the same rule, so the
  definition is the single source of truth for both.
- Thinking budget bounds are per model. The generic range capped 2.5 Pro
  below its documented 32,768 and admitted Flash values above 24,576.
  positiveMin carries the documented floors while -1 stays typeable as the
  decide-automatically sentinel.
- Ranges the model narrowed are marked modelSpecific, so a switch to a
  model that ignores the parameter cannot rewrite a value set for another.
- useDebouncedInput rebuilt its debouncer every render, because neither
  setOption nor the inline setter is memoized, so pending edits were never
  really superseded and a flush reached an instance holding nothing. The
  callbacks move to refs, and the text and slider controls flush on blur or
  value commit so Save and Export cannot read a stale preset.
- Controls reset to their definition default on a conversation or preset
  change and only recovered ~560ms later, which showed saved values as
  defaults and could write the default back.

The debounce regression test fails against the previous memo dependencies
and passes with the refs, so the flush is verified rather than assumed.

* fix: keep the context token bounds on the Google setting

The bounds came from the hand-rolled Google editor, but they were added to
the shared definition every endpoint renders, so blurring the field clamped
OpenAI, Anthropic, Bedrock and custom endpoints to a window that is only
Gemini's. Custom endpoints may declare context windows outside it.

* fix: agree with the generated schema across the sentinel gap

A stored value between range.min and zero passed through clampSettingRange
unchanged, though the schema admits only the sentinel or the positive floor,
so normalization could preserve a value the provider then rejects. Validate
a configured default against the same rule.

* fix: keep positiveMin on configured parameter definitions

The runtime schema for customParams.paramDefinitions retained only min, max
and step, so a configured positive floor was stripped before the UI saw it
while the shared SettingRange type advertised it.

* fix: commit a double-click slider reset immediately

The browser dispatches dblclick after the second pointer release, so the
value commit has already flushed and the reset sat in the debouncer. Saving
or exporting inside that window read the value the slider no longer showed.

* fix: normalize an out-of-range stored value on mount

The applied-range ref started at the first range, so the effect returned
immediately and a budget saved under the shared range stayed displayed and
savable when the selected model no longer allowed it.

* fix: normalize on navigation and keep sliders out of the sentinel gap

The parameters panel stays mounted across conversations, so a legacy budget
could arrive under a range that never changed; keying the normalization on
the conversation or preset identity as well catches it. After a navigation
the local value still belongs to the conversation being left, so the
incoming stored value is what gets normalized.

A slider steps straight through the gap between a sentinel minimum and its
positive floor, which the generated schema rejects, so the committed value
is clamped. It is also set before the flush: the keyboard path commits
before it reports the change, so the flush alone had nothing to write.

* fix: close the remaining paths into the sentinel gap

Applying a preset over the open conversation replaces the stored value
without changing the conversation id or the model, so normalization now also
triggers on a stored value that arrives differing from the local one. A
value the user typed reaches the conversation through this same field and
matches by the time it lands, so it stays on the blur-clamped path.

The slider's adjacent number input only flushed on blur, so a typed value
could sit in the gap the track is now kept out of.

A configured positiveMin above the maximum admits nothing but the sentinel
while the clamp maps every non-negative input onto a maximum the generated
schema rejects, so both the config schema and the definition validator
refuse it.

* fix: keep a non-negative sentinel and a loadable slider default

The minimum is the sentinel whatever its sign, and the generated schema
admits it outright, so a range like { min: 0, positiveMin: 10 } no longer
has its 0 lifted to the floor by the clamp.

The synthesized slider default took the midpoint of the whole range, which
for a sentinel range lands in the gap the validation added alongside it, so
an otherwise coherent custom definition failed to load. It now takes the
midpoint of the admissible interval.

---------

Co-authored-by: Danny Avila <danny@librechat.ai>
2026-08-25 21:21:28 -04:00
Marco Beretta
0383030817
perf: Avoid Parallel Full and Paged Prompt Loading on Startup (#15031)
Co-authored-by: Danny Avila <danny@librechat.ai>
2026-08-25 21:21:17 -04:00
Marco Beretta
57f3cb750b
🐇 perf: Bound MCP Agent Access Scan by MCP Referencing Agents and Share the Read-Through Cache (#15028)
* perf: bound MCP agent access lookups to MCP-referencing agents and share the registry read-through cache via Redis

Resolving MCP server access started from the full set of agents a user
can VIEW: the ACL distinct query materialized every accessible agent id
(400+ in affected deployments) and shipped the whole list back as an
$in filter, even when almost none of those agents reference MCP
servers. The calculation now starts from the agents whose
mcpServerNames are non-empty (covered by the existing
mcpServerNames_1_tenantId_1 index) and bounds the ACL query to those
candidate ids, so cost scales with agents that actually use MCP
servers. When no agent references any server, the agent-side ACL query
is skipped entirely. The same inversion applies to single-server
access checks, which now short-circuit on servers no agent references.

The registry's per-user read-through cache was process-local Keyv, so
every container recomputed access and no invalidation crossed
instances. It is now backed by standardCache (Redis when configured,
in-memory otherwise) with generation-based invalidation that orphans
entries in O(1) instead of scanning the keyspace, plus a process-local
memo to keep repeated per-request reads off the network.

Closes #14016

* style: fix import order in registry read-through cache files

* fix: harden MCP registry cache sharing per review

Encrypt the shared read-through store with encryptV2 so decrypted
oauth/apiKey credentials never leave the process in plaintext, and fail
open to a cache miss when an entry cannot be decoded.

Treat MCP_REGISTRY_CACHE_TTL=0 as a full cache bypass: entries derive
from ACL access, and without a TTL there is no bound on how long a
revoked user could keep receiving a stale map, in Redis or anywhere.

Move the invalidation generation tag to its own no-TTL store so it can
never expire before entries written under it, sweep expired memo
entries at most once per TTL window so one-time users cannot accumulate,
and settle the candidates and principals reads through one Promise.all
so a principals rejection can never surface as unhandled. The public
direct-server ACL read now starts alongside the candidate scan instead
of after it.

* fix: encrypt and harden the per-server MCP read-through cache

Route the per-server read-through cache through the same encrypted,
ttl-gated wrapper as the aggregate map, so decrypted credentials never
reach Redis in either cache and MCP_REGISTRY_CACHE_TTL=0 disables both
rather than storing ACL-derived entries forever. A null envelope keeps
cached-absent lookups distinguishable from misses, preserving the
existing negative-caching contract.

Shared-store failures now degrade instead of rejecting: entry and
generation reads fail open to a miss, writes fall back to the
process-local memo, so a Redis outage costs a recompute rather than
failing MCP requests. get and set recheck the generation after the
store round trip so an invalidation landing mid-flight cannot have its
pre-mutation value memoized for a full TTL window.

* fix: tenant-scope shared MCP cache keys and close read races

Shared read-through entries are now keyed with scopedCacheKey, which
appends the active ALS tenant, because the DB reads behind a miss are
tenant-filtered: without it a public or per-user lookup in one tenant
could satisfy another tenant's lookup from Redis. The single-flight map
partitions the same way.

The direct-server ACL read is chained off the principals promise so a
rejection handler is attached the moment it is created on both the user
and public paths, and all three initial reads settle through one
Promise.all. The generation recheck in the aggregate cache moved after
decode, so an invalidation landing during decryption still cannot pin
its pre-mutation value. The per-server cache exposes a single decoded
getEntry whose hit flag preserves negative caching, and an undecodable
entry deletes itself instead of shadowing the server until expiry.

* fix: miss on unreadable cache generation and parallelize the direct fetch

An unreadable generation tag now surfaces as a miss on get and a
memo-only write on set instead of falling back to generation zero,
which is a real first generation: a transient read failure could
otherwise revive an unexpired pre-invalidation entry for another TTL
window. The direct-server fetch, which only needs the ids resolved by
the first settlement, now runs concurrently with the agent ACL query
instead of after it.

* fix: fence cache fills across invalidations and scope them per tenant

A fill is now fenced by the generation observed at its miss: when a
registry mutation invalidates the cache while the caller is still
reading Mongo/YAML, the completed value is dropped instead of written
under the new generation, so a removed server or revoked ACL cannot be
resurrected for another TTL window by any replica.

The generation tag itself is tenant-scoped, matching the tenant-scoped
entries: a mutation in one tenant now evicts only that tenant's entries
instead of forcing every tenant back through the ACL and config reads.
Genuinely global events (operator config changes, lifecycle resets) use
the new invalidateAllGlobal, which trades a rare namespace scan for
cross-tenant eviction.

* fix: fence error-induced misses and decouple the agent ACL path

Store-read and decode failures now record their miss generation like an
ordinary miss, so a fill that lands after Redis recovers is still fenced
when an invalidation completed during the compute. The agent-side ACL
lookup chains from its actual inputs (candidates and principals) and the
direct-server fetch follows the ids immediately, so neither read waits
behind the other's settlement barrier.

* fix: bound fill fences by settlement and scope eviction per tenant

Miss fences no longer expire with the entry TTL: a fence lives until its
fill settles or a newer miss overwrites it, so a compute slower than one
TTL window is still fenced when an invalidation completed mid-flight.
The per-server cache gained the same protection through invalidation
versions: a fill finishing after its key was deleted, or after a
namespace clear, is dropped instead of repopulating the pre-mutation
value for every replica.

CACHE-tier mutations (YAML/App repository writes, reinspection, stubs)
now invalidate globally, since those entries are shared across tenants:
the per-server namespace clears and the aggregate map takes its global
path, while DB-tier mutations keep the tenant-scoped eviction. Tenant
invalidation also stops clearing the whole process memo: entries are
tagged with the tenant they were memoized under and only the acting
tenant's are evicted.

* fix: fence each cache fill by its own miss and pass the reinspection tier through

A miss now hands back a fill token capturing the generation (or, for
the per-server cache, the invalidation versions) it observed, and the
matching set fences on that token instead of a shared per-key marker.
Concurrent fills for the same key straddling an invalidation therefore
keep distinct fences: the pre-mutation fill is dropped even when a
newer miss for the same key is current, while the newer fill lands.
The shared marker maps are gone, along with their expiry and
overwrite semantics.

reinspectServer also threads its storageLocation into the invalidation
so a DB-backed reinspection takes the tenant-scoped path instead of the
global CACHE-tier eviction.

* fix: address PR review bot findings

chatgpt-codex-connector:
- share generation fences across cache replicas
- fence aggregate single-flight work by generation
- use an indexed MCP agent candidate predicate
2026-08-25 20:10:32 -04:00
Marco Beretta
124e357cbf
✏️ feat: Edit Pasted Text and Clear It on New Chat (#15017)
* fix: stop an unsent paste from following every new chat

An explicit new chat now drops the unsaved-chat draft key before the
composer resets. `newConversation` empties the composer, but the key
outlives it and `useAutoSave` restores from that key on the way in, so a
long paste that was never sent came back as an attachment on every later
new chat. Per-conversation drafts are untouched.

Clicking a pasted-text chip opens the text in an editor so it can be
corrected before sending, and the chip's subtitle offers returning the
paste to the composer. The text comes from the in-memory blob, falling
back to the `text` field the file record already carries, so neither
needs a new endpoint.

`FileContainer` grows a `subtitleAction` prop for the second control.
Supplying it swaps the chip's own button wrapper for a full-bleed one
behind the content, since a button inside a button is invalid markup and
browsers drop the inner one's events.

* chore: sort imports to fix static checks

* fix: address paste edit review findings

- Keep the original paste attached until the replacement upload succeeds,
  so a rejected or failed save cannot destroy the only copy
- Guard edits and queued replacements against conversation switches and
  new-chat resets, mirroring the long-paste lifecycle guards
- Recover text for restored pastes by downloading the stored bytes, which
  Assistants and agent uploads persist without a text field
- Delete uploaded attachments when an explicit new chat discards the
  draft that referenced them, instead of orphaning the records
- Mark paste provenance explicitly (session registry plus files draft)
  instead of inferring it from a filename a deliberate upload can share
- Keep the subtitle action revealed on devices without hover

* fix: scope draft cleanup to its tab and delete restored pastes

- Stamp unsaved-chat files drafts with the writing tab's session id and
  skip deletion when another tab owns the record, so a new chat in one
  tab cannot discard the uploads attached in another
- Delete a restored paste's upload when an edit replaces it or returns
  it to the composer, which the attached flag otherwise preserved

* fix: harden paste edit lifecycle guards

- Re-check the originating composer and the file map before detaching an
  edited original on upload success, so navigation or a send during the
  request cannot remove or delete a file the old draft or sent message
  still references
- Record the replacement upload's paste provenance in the session
  registry and the files draft, keeping Edit and Move back on the new chip
- Bind move-inline to the unsaved-chat token as well, and abort the move
  when the chip is no longer attached to an unsent composer
- Restrict new-chat draft cleanup to ids the composer still owns: library
  re-attaches and ids with unknowable ownership are spared, and uploads
  still in flight are deleted once their records reach the files cache,
  unless the file came back attached in the meantime

* fix: match restored paste identities and recheck before opening the editor

- Treat a chip as attached when any of its ids (map key, file id, temp
  id) matches the composer map, since draft restoration keys entries by
  their temporary upload id while the value carries the server-assigned
  one; the previous key-only check made Move back silently do nothing
  and left both chips attached after an edit
- Recheck the originating composer and the attachment map after the
  text resolve before opening the editor, so a send during the download
  cannot stage a replacement upload into the emptied composer
- Extend the provenance predicate to temp ids for the same restored shape

* fix: spare re-attached sent pastes and discard stale editor resolves

- Force-delete a restored paste only when the composer's own draft
  claims its id, so a paste that was already sent and re-attached from
  the library keeps its shared record through Edit and Move back
- Sequence editor-open requests so a slow text resolve cannot overwrite
  the chip a later click selected

* fix: carry deferred discards across resets and clear the pending draft

- Merge newly deferred upload ids with the pending set instead of
  replacing it, so a second reset cannot orphan an earlier in-flight
  upload's eventual record
- Match deferred ids against temp_file_id as well, since the files
  cache keys records by the server id while the discard tracked the
  request uuid
- Clear the pane's pending draft key on an explicit new chat, or a
  running response's queued text and attachments come back with the
  next run

* fix: mint a fresh tab id when sessionStorage was inherited

Duplicated and opener-created tabs start with a copy of the original's
sessionStorage, so a stored tab id only proves continuity when the
document is a reload of the same tab. Every other entry into a document
now mints a fresh id, keeping an inherited one from attributing another
tab's live drafts to this composer.

* fix: gate restored-paste deletion on draft tab ownership and unclip the chip focus ring

- Stamp every files draft with the writing tab, not just unsaved-chat
  ones, and require the stamp to match before a restored paste's record
  is deleted, so another tab restoring the same draft is not destroyed
- Draw the full-chip Edit control's focus indicator as an inset ring
  with the surface's radius, since the offset ring was clipped away by
  the surface's overflow-hidden

* fix: resolve paste ownership before restoration and across draft migration

- Treat a draft's own pastedTextIds as composer-owned at discard time,
  so a reload-then-new-chat click deletes or defers those uploads
  before the composer map has been rebuilt, instead of skipping them
- Read both the pending and idle draft keys when claiming a restored
  paste for deletion, since a response finishing mid-edit migrates the
  record between them

* fix: keep failed edits recoverable and retry failed draft deletions

- Reopen the paste editor with the user's corrections when the
  replacement upload is rejected or fails, instead of leaving only the
  original's text to reopen
- Retain deferred and immediate discard ids when the delete request
  fails, and retry them on the next files-cache update, so an offline
  or transient failure cannot orphan the uploads

* fix: retry restored-paste deletions that fail

A failed delete of a detached restored paste retains its payload in a
session store, and the discard retry effect drains retained payloads
alongside its own batch on every files-cache update, so an offline or
transient failure cannot orphan the upload once its chip is gone

* fix: queue failed edits and lock chips with actions in flight

- Queue a failed edit behind whatever dialog is open instead of dropping
  its corrections, and reopen it when that dialog closes
- Track an in-flight action per source paste and hide its Edit and Move
  back affordances until the replacement uploads or the move settles,
  so the same original cannot be acted on twice

* fix: address PR review bot findings

Codex:
- Keep the tab id on back-forward restoration
- Preserve the original tab owner when rewriting drafts
- Skip clearing idle and pending drafts another tab still owns
- Delete pending-draft uploads before clearing them
- Return failedFileIds from DELETE /files and retry those records
- Spare reattached files from retained deletion retries
- Trigger retained-deletion retries when a delete is retained
- Persist deferred discards across reload
- Delete embedded owned uploads with a discarded draft
- Ignore stale paste-editor failures before toasting
- Abort a queued edit after the original is sent
- Serialize Move back with a synchronous in-flight lock
- Prune paste provenance ids that left the draft

* fix: retain paste deletions the server reports as failed

The delete route answers 200 with `failedFileIds` when a record's storage
delete fails, so the detach path's `.catch()` never fired and the orphaned
upload lost its only cleanup reference once the draft provenance was pruned.
Inspect the resolved response and retain the deletion when it names the file.

Extract the `failedFileIds` reader `useNewChat` already had into the file
utils so both deletion paths read the response the same way, and give the
paste editor coverage for the failed and accepted responses.

Also add the missing `size` on a composer file literal that was failing the
client type-check.

* fix: release draft claims when their tab is gone and keep cleanup durable

A tab stamped its id on a files draft and nothing ever took it off, so a draft
saved in a tab the user then closed became unreachable for good: no other tab
would restore it, write to it, or clean it up, and the closed tab's id can never
be presented again. Tabs now report themselves in a small liveness registry and
release the claim on pagehide, and a claim whose tab is no longer around is
treated as free. Writers restamp a dead claim rather than preserving it.

Ownership also only existed once something was attached, so a typed-but-unattached
draft on a shared composer key read as nobody's and another tab's New Chat cleared
it. Saving text to one of those keys now claims it the same way.

Two more from the same review:

- The delete route answers a partial failure as 200, so treating an id as still
  present unless the response reports it deleted kept a ghost row for a file
  another tab had already removed. Read it the other way around: only a reported
  failure keeps a record cached.
- A retained deletion whose retry failed again moved no effect dependency, so it
  was never attempted a second time, and the payload only lived in memory. It is
  now persisted for the session and asks for a backed-off retry, plus one on
  regaining connectivity.

* fix: keep bfcache claims, retain failed deletes, and move the delete contract to TS

Four findings from the latest review round:

- pagehide fires with persisted: true when a document enters the back-forward
  cache rather than closing. Releasing the tab's claim there let another tab
  take the draft and delete files the restorable document still had attached,
  so the claim is now only handed back on a real unload; a bfcached tab that is
  never restored still ages out through the liveness window.
- useFileDeletion issued its batch and never looked at the outcome, so a fresh
  paste whose delete failed was orphaned with no retry. It now retains whatever
  the server did not delete, reading failedFileIds as well as the rejection.
- A partial failure answers 200, so the unconditional success toast told the
  user a file was deleted while it was still on disk and back in their list.
- The delete response contract lived in the legacy JS route. It moves to
  packages/api as buildDeleteFilesResponse, leaving the route a thin caller.

The useFileDeletion spec's mutateAsync mock returned undefined; react-query
always hands back a promise, so it now resolves like the real one.

* fix: park bfcached tab claims and drop ownership left by an emptied draft

A document in the back-forward cache has a frozen heartbeat, so the ordinary
liveness window expired its claim after 150s even though it could still be
restored with those attachments on screen, letting another tab take the draft
and delete the files underneath it. Entering the cache now parks the tab as
suspended, which holds the claim for 30 minutes: comfortably past the point a
browser keeps a bfcache entry, and still bounded, since a claim that never
expires is what stranded drafts under owners that no longer existed. Restoring
the document beats normally again and clears the flag. The registry entry grew
a shape for this and still reads records written as a bare timestamp.

Clearing the text of a shared composer key also left the ownership-only record
behind, locking the key to a tab with nothing in it: the next tab to type there
could neither restore its own draft nor take the key back. That claim is now
released when the text goes and nothing is attached.

* fix: keep unlinks out of the delete retry and claim shared text before writing

Four findings from the latest round:

- Retaining a failed agent or assistant unlink sent it through the generic
  retry, which replays files alone. That drops the tool_resource context, so
  the route would take its ordinary delete branch and destroy a record the
  agent and other references still point at. A failed unlink orphans nothing,
  so those deletions are simply not queued.
- A retry that resolved naming files in failedFileIds left both stores
  untouched, so nothing moved the effect that would try again. It now asks for
  another attempt on a reported failure, the same as on a rejection.
- The reattachment guard read only the idle new-chat key. After a reload the
  composer map is empty until the autosave restore renders, so a file the user
  had reattached to the conversation they were viewing, or to the pending key,
  could be deleted underneath them. All three keys are checked now, including
  their paste provenance.
- Text was written to a shared composer key before ownership was resolved, so
  a tab could overwrite another's saved text and still be refused the claim,
  leaving it unable to restore what it had just typed. The claim is taken
  first, and a claim with no attachment behind it follows whoever's text is
  actually stored; one backed by an attachment stays with its open owner.

* fix: merge shared discard state and keep restored file-search pastes retrievable

Four findings from the latest round:

- Every mount of useNewChat (header, sidebar, mobile bar, shortcuts) kept its
  own snapshot of the pending-discard list and wrote it back over one shared
  session store, so an id recorded by one instance was dropped by the next
  write from another, orphaning the upload it pointed at. An update now only
  resolves the ids that instance knows about and carries the rest through.
- Refusing an attachment-backed claim still let the text write land, destroying
  the owning tab's text for a tab that could not have restored it anyway. The
  claim now reports whether it succeeded and the write is dropped with it.
- A restored paste has no tool_resource on its record, so an edit to one that
  had been uploaded for file search was re-uploaded as a plain context file and
  the vector-backed original detached, dropping it out of retrieval. embedded
  does survive on the record and is only set for a vectorized file, so it is
  what the destination falls back to.
- The reattachment guard collected map keys and server ids but not
  temp_file_id, while the retry lookup resolves that alias: reattaching a file
  whose discard was pending under its temporary id would not have protected it.

* fix: stop the draft owner refusing its own writes and guard shared pending keys

Three findings, the first a regression from the previous commit:

- The attachment-backed refusal was evaluated before the owner check, so the
  tab that owned the draft was refused its own key: once anything was attached,
  nothing typed after it was saved. Ownership is settled first now, and the
  refusal applies only to another live tab.
- A long paste wrote its provenance and pending-paste record into the shared
  composer key without checking who owned it, and setFilesDraft preserves the
  existing owner rather than rejecting the write, so the paste was recorded
  into another tab's draft, which could then restore and delete the upload
  while this tab still showed the chip. Both write sites now check first.
- Two concurrent runs share the default pending key, and the migration to the
  new conversation ran before the ownership check: the finishing run moved the
  other tab's text and attachments under its own conversation and left that tab
  nothing to carry over. Ownership of the source is verified before migrating,
  and this composer's own text is still saved either way.

* fix: protect cross-tab reattachments and orphaned pastes on every discard path

Five findings from the latest round:

- The retry guard only read this pane's own draft keys, so a file a second tab
  had reattached to a conversation this pane never opened was deleted anyway.
  Drafts live in localStorage and are readable from every tab, so the guard now
  sweeps every persisted files draft rather than three known keys.
- Clearing the composer removed the shared text record without checking who
  owned it, so an empty composer in one tab erased text another tab was still
  holding behind its attachments. The clear path takes the same guard as the
  write path, and both now share one ownership predicate.
- When another tab owned the pending key, this tab's own queued attachments
  were cleared from the map and never written anywhere, because the autosave
  that would have persisted them had been refused that key for the whole run.
  They are now written under the conversation the run just became.
- A draft write that storage refuses (private mode, quota) left a generated
  paste with no record to discard it by. New Chat now also collects the live
  marked pastes the composer is still showing, skipping re-attached ones.
- With draft saving off, the reset path deleted files without awaiting or
  reading the response, so a failure orphaned the upload. It retains what the
  server did not delete, like every other deletion path.

* fix: keep reloading tabs live and spare pastes an active run is using

Three findings:

- pagehide cannot tell a reload from a close, and the tab id survives a reload
  on purpose, so releasing the claim there handed this tab's own draft to
  another one while the document was still bootstrapping. A closing tab is left
  to the ordinary liveness window instead, which is what the window is for.
  Entering the back-forward cache is still marked, since that heartbeat freezes.
- The text-ownership guard only covered the shared composer keys, but a
  conversation key is reachable from every tab viewing that chat and is stamped
  the same way, so one tab could overwrite text another was holding behind its
  attachments. The guard now applies to any key; the ownership stub is still
  only created for the shared keys, which tabs otherwise share freely.
- Submitting empties the file map but leaves the draft's paste provenance until
  the final SSE event, so New Chat during a streaming response treated the empty
  composer as still owning what the message had just sent and deleted files the
  message, and the run reading them, still referenced. The provenance promotion
  is skipped while a run is in flight.

* fix: give each tab its own presence record and publish live attachments

Four findings:

- Tab presence lived in one shared localStorage map, so two tabs beating at the
  same time read the same snapshot and wrote back rival copies; the loser
  disappeared until its next beat, long enough for another tab to treat its live
  draft as abandoned. Each tab now writes only its own key, and expired records
  are swept while reading.
- With draft saving off nothing is written to a draft at all, so a file
  reattached in another tab was invisible to a retry running here and could be
  deleted underneath it. A tab now publishes what its composers are holding into
  its own presence record, and cleanup unions that with the drafted ids.
- The record written when another tab owns the pending key kept only attachment
  ids, so a restored chip stopped being recognised as a paste and lost editing
  and cleanup. Provenance is rebuilt from the session registry. The unsent paste
  text cannot come along: this tab was refused that key all run, so it was never
  stored anywhere to carry.
- New Chat with draft saving off skipped every embedded record, leaving an
  unsent file-search paste with its metadata, storage and vectors intact. A
  paste this composer owns is now included with its real embedded value, while
  other embedded files are still left alone.

* fix: elect one cleanup worker, scope the queue to its account, guard edit writes

Three findings:

- Every mounted useNewChat (header, sidebar, mobile bar, shortcuts) entered the
  cleanup effect against one shared store, so a single retry issued the same
  DELETE several times and toasted about each. A pass is now claimed before it
  runs; an instance that is turned away asks for a later one rather than
  dropping the work.
- The retained queue outlived a sign-out, so the next account retried the first
  one's payloads, was refused by the ownership check, and rescheduled forever.
  Logging out clears the queue and cancels the pending retry.
- The paste path checks draft ownership before recording provenance, but the
  edit path did not, so a replacement could be written into a record another
  open tab owns, which that tab could then delete while this one still showed
  the chip. It takes the same check.

* fix: match paste identities everywhere and stop migrations clobbering a foreign draft

Five findings:

- The presence record published only composer map keys, but a restored upload
  is keyed by its temporary id while the value carries the server one, and a
  retained deletion in another tab names whichever it recorded. All three
  identities are published now, matching the local guard.
- Migrating a finished run checked that the pending record was ours but not the
  destination, so a conversation draft another tab owned with attachments on
  screen was overwritten and restamped. Both ends are checked, and the
  non-owner fallback no longer writes over a foreign destination either.
- The live-paste fallback matched the registry against file_id alone, so a
  completed paste, marked under its client upload id, read as somebody else's
  file and its upload survived New Chat. It matches every identity now.
- An upload still in flight has no filepath or source, so no discard path can
  build a payload and the reset drops the chip anyway. Its id is deferred so the
  record is deleted when it arrives, with draft saving on or off.
- An edited paste that had been staged into the code sandbox was re-uploaded as
  a plain context file, since only the file-search case was reconstructed.
  metadata.codeEnvRef is durable and now routes it back to execute_code.

* fix: silence background cleanup and keep cross-tab protection past a send

Four findings:

- The reset path matched the paste registry on file_id alone, the same alias
  gap already fixed in New Chat, so a completed embedded paste read as somebody
  else's file and survived with its vectors. It matches every identity now.
- The background cleanup pass used the ordinary delete mutation, so a storage
  failure that kept failing announced itself on every retry, and success
  arrived minutes after the action behind it. The mutation takes a silent
  option and the retry pass uses it; direct user actions still report.
- Each hook instance loaded the pending-discard list once and was never told
  when another instance wrote it, so work deferred by an instance that then
  unmounted stalled. Writes now notify every mounted instance, which re-read
  and apply only a real change.
- Cross-tab protection sampled only what a composer was holding right then, and
  sending clears both the map and the draft, so a file reattached in another
  tab and then sent could be deleted between retries. A tab now remembers what
  it recently held for ten minutes, which is long enough for the other tab's
  next pass to see it and cancel that deletion for good.

* fix: honour draft ownership in every clear and track what a message consumed

Five findings:

- The ownership contract was only applied at the new call sites; the SSE final
  event, the steering handoff and the debounced text clear still erased records
  through clearAllDrafts and clearDraft. The check moved inside those helpers,
  so every path that clears a draft respects it.
- Only the explicit logout cleared the retained queue, leaving a silent refresh
  that returns nothing and a failed user query to carry it into the next
  account. It clears wherever the session is lost instead, in the one place all
  three paths pass through.
- Using isSubmitting to decide whether a paste was consumed was wrong for a
  stopped or errored turn: those clear the flag without clearing the draft, so
  New Chat afterwards deleted files the turn already referenced. Submission now
  records the ids it took, and those are excluded by name.
- The presence sweep only ran from deletion cleanup, so a profile that never had
  a failed delete accumulated a record per tab until the origin quota ran out
  and draft writes began failing silently. The heartbeat sweeps.
- When a run finished into a conversation another tab owned, this tab's own
  queued text and attachments were dropped for want of a writable destination.
  They stay on the key it does own and are restored from there.

* fix: mint a tab id when the browser has no randomUUID

crypto.randomUUID is absent on insecure origins and in older webviews, and the
throw left the tab with an empty identity: every draft was then written without
an owner and every ownership guard read another tab's record as its own,
reinstating exactly the loss this layer exists to prevent. Falls back to
getRandomValues, then to a local mint. The id only has to tell tabs apart.

* fix: address PR review bot findings

Clear the retained deletion queue on every direct authentication exit, not
just the debounced context update: an empty or rejected silent refresh, a
failed user query, and the external-IdP logout all leave the page without
passing through setUserContext, so the queue survived into whoever signed in
next and retried under credentials the ownership check rejects forever.

Settle the edit lock when a replacement upload is aborted. Removing the
replacement chip mid-upload consumes the lifecycle through onAbort, which the
paste editor never handled, so the source paste kept its Edit and Move-back
actions hidden for the rest of the session and the typed correction was lost.

Keep the temporary-file cleanup payload for whatever the server reports as
failed. The delete route answers a partial storage failure with a 200 carrying
failedFileIds, and the cleanup mutation cleared FILES_TO_DELETE wholesale on
any success, dropping the only automatic retry those orphans had.

Persist both paste registries per tab. They lived in module-level sets, so a
reload kept the files draft but forgot the paste had been consumed, and New
Chat then classified an already-sent paste as unsent and deleted a file the
persisted message still references.

Withdraw discarded ids from tab presence. A removed, moved, or discarded chip
kept its recent entry for the whole window, and the retry sweep read that as
evidence the file had been reattached: it cancelled its own cleanup and left
the failed upload orphaned on the server. Presence records whose heartbeat
cannot be read are skipped rather than rewritten, since giving one a fresh
seenAt would revive a dead tab's claims over every id it still held.

* fix: address second round of PR review bot findings

Stop a settled deletion from undoing the logout clear. A DELETE that was
already in flight when the session ended settles afterwards, and its handler
is the last reference to that payload, so it wrote the departing account's
records straight back into session storage. Clearing now latches retention
shut and only a newly established session reopens it, which also covers the
paste editor's own retention and the discard paths, not just this one writer.

Reinsert a failed paste when nothing durable holds it. A composer the user
has typed into is deliberately left alone while a recovery record exists,
because that record restores at an anchored offset later. When the shared
draft key belongs to another live tab the guard skips the record entirely, so
the upload callback held the only copy and refusing dropped the text outright.
It now goes back in at the offset its anchors resolve to, which is where a
restore from a record would have put it.

* fix: address third round of PR review bot findings

Withdraw attachment presence from this tab only. The sweep cleared the
withdrawn ids out of every tab's recent map, which is the one record a second
tab has left once it has reattached a file and sent it: its composer and its
draft are both empty by then, so erasing that entry handed the next retry a
file it read as abandoned and let it delete the upload out of the message now
referencing it. The withdrawing tab always published what it withdraws, so its
own record is all it needs to touch.

Guard the direct New Chat deletion against other tabs. The retry effect
consults every other tab's drafts and published presence before deleting, but
the discard that runs on New Chat went straight to the request, so it raced
past that guard and could delete a file another tab still had attached or had
already sent. It now consults the same two sources, excluding its own draft
keys and its own presence record, which hold exactly what the discard is
throwing away.

Fix the import order in Presentation.tsx, which CI static checks flagged.

* fix: address fourth round of PR review bot findings

Read this tab's presence before sweeping stale keys. Timers pause while the
machine sleeps, so a live tab can beat again with its own record already past
the liveness window; the sweep reaped it and the write that followed published
an empty presence, and nothing republished it because the file map had not
changed. Another tab's retry then saw no claim on chips this one still had on
screen.

Keep submitted-use evidence when a later chip is withdrawn. The same file can
be sent on one message and reattached afterwards, and once the composer and
draft have cleared, its recent entry is the only cross-tab record that a
message still references it. Withdrawing a chip no longer erases an entry for
an id a submission already consumed; it ages out on the ordinary window.

Clear composer drafts when the account changes. A files draft carries the whole
text of a paste held as a file, and the browser tab keeps its identity across
an in-app account switch, so the ordinary draft restore could hand the next
account the previous one's writing. Both draft families are now dropped on the
sign-in and sign-out paths, ahead of the skipFirst exception.

Spare a submitted paste from the edit path's explicit deletion. Editing or
moving a reattached library file that an earlier message sent deleted the
server record underneath that message, because the draft-ownership check
succeeded and nothing consulted the submitted marker.

Validate an edited paste as a replacement rather than an extra file. The
original is deliberately still attached while the replacement uploads, so the
shared validation counted both and rejected the edit at the file-count or
total-size limit; with a limit of one, a lone paste could never be edited.

Preserve failed rows after a table deletion. The table's own cache update
removed every requested file without consulting failedFileIds, undoing the
partial-aware update and hiding a file whose storage delete had failed.

Document the two deliberate dependency omissions in AuthContext, which CI now
lints at zero warnings because the file is part of this change.

* fix: address fifth round of PR review bot findings

Clear composer drafts on the way out of a session, not only on the way in.
Clearing them from the login mutation missed social sign-in entirely: OAuth,
OpenID and SAML leave through direct links and come back through the silent
refresh, so a different account could arrive in the same tab with the previous
account's drafts and tab identity intact and have its paste text restored. The
draft clearing is now paired with the retained-deletion clearing in one helper
used by every authentication exit, so neither can be wired into a path the
other was missed from.

Rebuild paste provenance when restoring a queued upload. A paste queued during
a run has its pending draft taken by takeComposerDraft, so choosing Edit
message restored the upload into an empty composer with nothing recording that
it was a generated paste. Filtering existing provenance could not recover that,
and an unmarked restored chip is treated as a shared attachment: removing it
would not delete it and New Chat skipped it, orphaning the unsent upload. The
session registry still knows, so it is consulted.

Drop paste provenance when a rejected upload is removed. Validation can reject
a paste before it reaches composer state, and the failure path removes it with
removeFile, but the id stayed in pastedTextIds. That left a record
hasDraftAttachments reads as a real attachment claim with no chip behind it,
and with the file map unchanged nothing pruned it, so it locked every other tab
out of the shared composer key.

* fix: address sixth round of PR review bot findings

Centralise the foreign-claim guard. Every path that deletes an upload has to
ask whether another tab or pane still claims the file, and the guard was being
assembled by hand at each site, which is exactly why it was missing from three
of them. collectForeignAttachmentClaims now builds that set once, and the New
Chat discard, the no-draft reset fallback in useNewConvo, and the paste
editor's explicit deletion all consult it. A record another tab claims is
skipped rather than retained, since it was never this pane's to delete.

Scope presence withdrawal to the pane that owns it. One tab holds several
composers and the presence record is flat, so the hook that won the global
deletion pass swept every pane's entry while knowing only its own file map,
erasing the evidence of a chip a sibling pane still had on screen. Withdrawal
now takes the pane index, and an id another pane still lists keeps its recent
entry too.

Guard destructive draft clearing against text-only claims. claimComposerDraftTab
stamps a key that holds nothing but text, and the write guard ignores a claim
with no attachment behind it, so a tab finishing a run that began as an unsaved
chat cleared the shared new-chat key and took another tab's half-written
message with it. Clearing now honours any live foreign stamp, while text writes
keep their deliberate last-writer-wins behaviour.

Mark queued override files as submitted. A during-run queued message drains
through overrideFiles into the reuseFiles branch and skipped the marker loop
entirely, so reattaching that paste later left isPasteSubmitted false and New
Chat or an edit could delete a file the queued message still referenced.

* fix: address seventh round of PR review bot findings

Treat publishing an attachment as proof of liveness. The publisher carried the
old seenAt over, so a tab whose timers had been paused past the liveness window
published a chip and stayed expired until its next interval tick, long enough
for another tab's cleanup to sweep the record and delete the file under the
chip that had just appeared.

Count a sibling pane as a claim. The foreign-claim helper excluded this tab
entirely, so the pane doing the discarding could not see the other composer in
the same tab and deleted a file it still had on screen. Live claims are now
gathered per pane: only the discarding pane's own entry is left out, along with
this tab's recent map, which is flat and cannot say which pane an id came from.

Keep a tab identity when session storage is unusable. It can be blocked or full
while localStorage still works, and returning an empty id left the document
unattributed, which every ownership and liveness guard reads as no owner, so
tabs could destructively clear each other's attachment-backed drafts. An id
that lives only for this document still tells the open tabs apart.

Scope attachment withdrawal in the deletion hook to the originating pane, and
thread the composer index through ChatForm, FileFormChat and FileRow to supply
it. Removing a file from one side-by-side composer withdrew the id for every
pane, and with drafts off the sibling never republished its claim.

Check foreign claims before deleting a live edit source. The guard only covered
the restored path, because detach returns early for an in-memory upload before
reaching it, so editing a live paste another tab had reattached from the library
deleted the file underneath that tab's chip.

Keep autosaving to the pending key while the destination is not writable. The
preserved queued work was written under the pending key but the destination was
still recorded as the active conversation, so later edits autosaved against a
foreign key and a reload mounted straight onto the destination, losing the work
that had just been preserved.

* fix: address eighth round of PR review bot findings

Make submitted-use evidence durable and readable across tabs. The tab that
retries a retained deletion is rarely the tab that sent the message, and this
evidence lived in the sending tab's session storage, which left published tab
presence as the only cross-tab record. That ages out on a fixed ten-minute
window, so a retry resuming after a longer freeze classified a sent file as
abandoned and deleted it out of its message. It is timestamped in localStorage
now, with a horizon wide enough to outlast any plausible freeze and a hard cap
so a long-lived profile cannot grow it without bound. Paste provenance stays in
session storage, since which chips offer the paste affordances really is
per-tab.

Tie a blocked pending draft to its intended destination. Keeping the pending
key active while a live tab owned the destination left the pending state with
no memory of where it was heading, so any later navigation looked like the
awaited transition and carried the queued text and attachments into an
unrelated conversation.

Defer an in-flight paste on direct conversation resets. Callers that reach
newConversation without going through New Chat left an upload with no filepath
yet unrecorded, so once the request landed nothing remained to delete the
server file.

* fix: restore the composer clear after send

CI e2e caught this: after sending a message with an attachment the chip stayed
in the composer, so the sent message and the composer both showed it.

Two causes, both from keying composer storage off state that lags a render.
`currentConversationId ?? conversationId` is the previous conversation during
every transition, so the file-cache restore ran against the outgoing key and
put the just-sent attachment straight back into the map that the submit had
cleared. The active key is now the conversation unless the switch effect has
deliberately parked storage on the pending key.

Separately, treating any first mount as the awaited pending transition ran the
pending migration on every direct load of a conversation. That is narrowed to a
pending record this tab owns which actually holds something, which is what a
reload with real queued work looks like.

Verified against the two failing specs locally, then the whole mock chat spec:
8 passed.

* fix: address ninth round of PR review bot findings

Stop expiring submitted-use evidence on a timer. The work it has to outlast is
a retained deletion, and those carry no expiry of their own, so any interval
chosen could be outlived by a suspended tab still holding cleanup work, which
is the same bug with a longer fuse. The ledger is bounded by count instead,
evicting oldest first only when it would otherwise grow without limit.

Consult that ledger before retrying a deletion. The retry pass built its
protection set from drafts and published presence only, both per-tab and
time-bounded, so a file sent from a tab that has since been suspended had
nothing left to speak for it. The record is resolved before judging, because
the discard is often keyed by the temporary upload id while the pane that sent
it marked only the server id.

Refresh liveness when withdrawing presence, matching the publication side. A
retained-deletion pass resuming after paused timers withdrew its own entry and
then swept the record as stale, taking sibling panes' claims with it.

Keep queued attachments when neither draft key is writable. With another tab
owning the pending key and a second owning the destination, the effect cleared
the live map and could persist it nowhere, so unsent attachments vanished the
moment the run got its conversation id.

Remove the replacement provenance when an edited paste is not accepted. The
edit path records the replacement id before routing the upload, and a rejected
upload left a provenance-only draft that reads as a live attachment claim with
no chip behind it.

Verified with the mock chat e2e spec after rebuilding the frontend: 8 passed.
2026-08-25 20:06:59 -04:00
Marco Beretta
21ba9d3f30
🔁 fix: Rerun a Message the Editor Has Not Changed (#15212)
* fix: allow rerunning a message the editor has not changed

The submit button in both message editors was disabled until the draft
differed from the persisted message, so reissuing a request after a
cancelled response, a failed generation, or a backend restarted on
different parameters meant typing a throwaway character and deleting it
first.

The button now reads "Rerun" while the draft is untouched and "Update &
rerun" once it differs, and neither state disables it. An untouched
assistant turn regenerates instead of replaying its own content as an
edit: editedContent retains the existing content and appends the new
completion, so replaying it would return the old answer with a second one
glued onto it.

Two ask options were dead on arrival. editedText was declared on TOptions
and passed by EditMessage but never destructured by ask, and
isResubmission was never set or read anywhere. Since no submission can
carry a text-level edit, and editedMessageId regenerates the row in
place, an assistant turn in the plain-text editor now always reads
"Rerun" and its status slot says where an unsaved edit is about to go.

Fixes #15205

* fix: address PR review bot findings

chatgpt-codex-connector:

- Route a plain-text assistant rerun through regeneration. It kept the
  edit-resubmission options, so it replaced the response in place, and
  with no targetResponseMessageId the submission resolved the NEWEST
  answer for that turn: rerunning an older sibling pruned the wrong
  subtree from the optimistic thread while appending a placeholder keyed
  to the older sibling's own id. It now sends isRegenerate with
  targetResponseMessageId, matching the hover action and
  EditContentParts, and leaves the sibling index alone.

- Let an empty answer reach the rerun handler. The field is registered as
  required so Save cannot blank a message, and routing the rerun through
  handleSubmit meant a response cancelled before its first token had an
  enabled button that did nothing. The answer's draft is never submitted,
  so it no longer gates the rerun or the disabled state.

The status hint changes with the behavior: rerunning discards an unsaved
answer edit and generates a new response rather than replacing this one.
2026-08-25 20:04:02 -04:00
Ravi Kumar L
cd4cdf2ca0
🗄️ fix: support DocumentDB aggregations for insights (#15226) 2026-08-25 19:59:09 -04:00
Danny Avila
e9936b8ad2
🎢 fix: Restore Schedule Dialog Scrolling So Save Stays Reachable (#15225) 2026-08-25 19:58:45 -04:00
Danny Avila
95e1a5c9fa
🧠 fix: Correct Memory Token Accounting (#15224) 2026-08-25 19:58:30 -04:00
Danny Avila
6284139f18 📦 chore: bump @librechat/agents to v3.7.2 2026-08-25 18:35:21 -04:00
Danny Avila
1489623fa3
🎬 test: Record-Once/Replay-Forever Model Fixtures for Mock E2E (#15210)
* 🎬 test: Record-Once/Replay-Forever Model Fixtures for Mock E2E

The mock e2e lane's only credential-free model is a hand-authored script:
`fake-model.js` decides responses from ~60 `E2E_*` prompt markers. That
covers scripted shapes well, but no scenario replays a *real* recorded
provider conversation through the assembled chain, so real streaming
shapes — provider chunk cadence, reasoning deltas, usage metadata — are
only ever approximated.

This adds a record-once/replay-forever tier alongside the marker routing.

Record (`E2E_MODEL_FIXTURES=record`, needs a provider key): the run hook
appends a LangChain callback handler to every agent context's
`clientOptions.callbacks` instead of overriding the model, so the REAL
provider streams while each invocation's `AIMessageChunk`s serialize to
`e2e/fixtures/model-replay/<name>.jsonl` — text deltas, tool_call_chunks,
reasoning kwargs, and genuine usage metadata. Only the latest human text
is recorded for binding; system prompts and tool schemas never enter the
fixture.

Replay (default, keyless): `fake-model.js` consults `tryBindReplay` ahead
of marker routing, binding a conversation whose prompt matches the next
unconsumed invocation. The replaying model is not hand-assigned — it is
registered as SDK provider `librechat-e2e-replay` via `registerProvider`
and constructed through the SDK's own `initializeModel`, so registry
lookup, constructor clientOptions, and real `bindTools` all run the way a
live provider's would. Recorded chunks therefore stream through the same
createRun → graph → SSE → persistence chain.

Consumption is enforced rather than assumed: every invocation re-checks
its prompt against the recording, an invocation past the end of the
script throws, and a per-fixture ledger lets the spec assert at teardown
that every recorded invocation and chunk was drained. Streaming
incrementality is asserted from that ledger, not by sampling transient
DOM, which is a race by construction.

The credential-free profile is unchanged when not recording: the record
provider and its selector entry are template markers that stay comments,
and no existing spec's routing is touched (a fixture only binds on an
exact prompt match; everything else falls through).

Verified: record vs the real DeepSeek API 1 passed (15.2s); keyless
replay 1 passed twice (11.4s, 12.7s) with the ledger fully drained (2/2
invocations, 10/10 chunks, no overruns or mismatches); app-load,
completion, and chat 10 passed unchanged.

* fix(e2e): rebind a replay fixture from the top for a new conversation

The replay cursor is process-global while the web server outlives a
Playwright retry, so a fully consumed fixture left the retry unable to
bind its first prompt: it fell through to marker routing and failed
deterministically, burning every configured CI retry. A partially
consumed attempt failed the same way.

Binding now restarts the fixture when the incoming prompt matches its
first recorded invocation, resetting the ledger with the cursor so the
new attempt is judged on its own consumption instead of accumulating the
previous one's counts. Continuing an in-progress binding still outranks
restarting, so a fixture whose opening prompt repeats later in the script
advances rather than rewinding.

The over-consumption guard is untouched — it fires inside the stream when
the cursor passes the end, not at bind time.

* fix(e2e): close three replay-lane gaps found in review

Restart the recorder on a retry. Its state is process-global like the
replay cursor, so a failed attempt that had already recorded invocations
left the counter advanced: the retry appended 2/3 after 0/1, or kept the
previous attempt's `error` line, and the fixture was unusable for replay.
Recording now truncates and restarts when the opening prompt reappears,
mirroring the replay side's rule and its caveat.

Retain a consumed binding for the conversation that drove it. An extra
user turn past the final recorded invocation found no next invocation and
fell through to ordinary fake-model routing, so it was answered with a
mock reply: the over-consumption guard never ran and the already-drained
ledger still passed. Such a conversation is now recognized by its human
turns opening with the fixture's recorded prompts, and stays bound so the
stream raises the overrun. Continuing an in-progress binding still
outranks restarting, which outranks retaining a consumed one, so a
retry's fresh conversation rewinds rather than being read as an extra
turn.

Validate the fixture the recording actually wrote. Record mode honors
`E2E_MODEL_FIXTURE_NAME`, but the spec always inspected the committed
`deepseek-two-turn`; another name wrote elsewhere while the assertions
read the pre-existing file, and because the prompts are fixed the stale
answers could match and green a run that verified nothing it produced.

* fix(e2e): make replay binding correct for tool and subagent fixtures

Round two's retry and consumed-binding fixes both assumed one model
invocation per user turn. A turn that calls a tool breaks that: the model
is invoked again after the tool result under the same latest human
message.

Identify a retry by the conversation boundary, not the prompt. The
recorder ran per invocation and truncated whenever the opening prompt
reappeared, so a tool round trip looked like a retry and discarded the
recorded tool-call invocation. Restart detection now sits in
`installRecorder`, which runs once per `createRun`: a turn whose history
holds no prior human message begins a conversation.

Compare consumed bindings against user turns, not invocations. Several
recorded invocations can share one prompt, so a one-to-one comparison
could not recognize the originating conversation — invocations `[A, A, B]`
against history `[A, B, C]` failed on both length and elements, and the
extra turn fell through to the fake model with the drained ledger still
passing. Fixtures now carry their collapsed turn sequence.

Override the subagent model too. `graph.overrideModel` is not inherited
by child executors, so a fixture recording a subagent call — record mode
captures child invocations already — would leave the child on its
configured provider: an underrun, and a real provider request in a lane
that must stay keyless.

Reject ambiguous prompt matches. Binding order followed filesystem
enumeration, so a second fixture sharing a prompt could silently redirect
a scenario to the wrong chunks and ledger; the spec's choice never
reaches the server-side loop, so ambiguity fails instead of picking a
winner. Fixture identity is the file name for the same reason — a
recorded `meta.name` is descriptive, and trusting it let a copied fixture
collapse onto another's registry key and ledger.

Prove the recording is fresh. The spec removes the selected fixture
before driving, so a run whose hook never installed the recorder fails
instead of greening against a stale artifact whose answers still match
these deterministic prompts.

* fix(e2e): rewind a replay fixture at the conversation boundary

Consecutive invocations can share a prompt — a tool call produces exactly
that — so an attempt stopping mid-turn left the cursor on an invocation
whose text still equalled the opening prompt. Matching the cursor first
meant a retry's fresh conversation resumed after the tool call instead of
rewinding, consuming the post-tool invocation and silently replaying a
different script than was recorded.

A conversation boundary now outranks an in-progress cursor: a fresh
conversation whose prompt opens the fixture rewinds even when the cursor
would have matched. Continuing still outranks restarting within a
conversation, so a turn that calls a tool advances to its post-tool
invocation rather than rewinding on its own repeated prompt.

* fix(e2e): refuse cross-conversation binding and prove content streaming

A fresh conversation could steal a partly consumed fixture's later turn.
Only a conversation opening with the fixture's first prompt was treated
as a boundary, so after `[A, B]` had consumed `A`, an unrelated new
conversation whose first message was `B` matched the cursor, received the
recorded second-turn response, and advanced the shared cursor without
ever having driven `A`. A conversation start may now only rewind a partly
consumed fixture, never continue it; continuation within a conversation
is unaffected.

The incrementality assertion counted empty frames. Providers emit empty
initialization and usage-metadata chunks around the content deltas, so a
total chunk count above one was satisfied by a single delta: the previous
fixture's closing turn had four chunks and one content-bearing delta
carrying the whole answer, and both modes stayed green without proving
incremental assistant-content streaming at all. Fixtures now track
content-bearing chunks separately, the closing prompt asks for prose
rather than a number, and both modes require several content deltas on
that turn. Re-recorded: the closing turn now carries 28 content deltas.

* fix(e2e): scope record mode to the fixture spec

`E2E_MODEL_FIXTURES=record` replaces the fake-model hook globally, so an
unfiltered entry point such as `npm run e2e:mock` sent every spec under
specs/mock to the paid real-provider endpoint, while each fresh
conversation truncated and rewrote the one selected fixture — leaving an
artifact from whichever scenario happened to run last.

Record mode now matches only the fixture spec: an unfiltered recording
run lists one test instead of 203. Replay mode is untouched and still
collects the full suite.

* 🪪 fix: Bind Replay Fixtures by Conversation, Not Prompt Text

Prompt text was standing in for conversation identity, and three review
rounds found the same class of defect underneath it: a tool call repeats
a prompt across invocations, a retry repeats it across attempts, and a
resumed run has neither prompt nor history because `createRun` is rebuilt
with no messages while state comes from the checkpoint. Each fix in that
space created the next gap.

Thread the identity instead. `createRun` accepts a `conversationId` and
passes it to the run hook, which the agents controller supplies at both
call sites — the same value it already uses as the checkpointer's
`thread_id`. The field is optional and the hook is env-gated, so nothing
changes when the harness is not in use.

Binding then collapses to ownership. A fixture is owned by the
conversation that claimed it, and its cursor is authoritative wherever it
stands: an extra turn reaches the over-consumption guard rather than
falling through to the scripted fake model, and a resumed run keeps
replaying with no prompt to match. A different conversation may claim the
fixture only by opening it, which rewinds — what a Playwright retry looks
like. Everything else is refused, so an unrelated conversation can no
longer continue someone else's partly consumed script by repeating a
later prompt. The prompt is still re-checked on every real turn; only a
resume, which structurally carries no human message, is exempt. The
previous text-and-history rules remain as a fallback when identity is
absent.

The recorder keys the same way: a new attempt is a new conversation, so a
resume no longer truncates the fixture mid-turn and discards its
tool-call invocation.

Record summarization too. The summary provider runs on its own model with
its own callback list, so a scenario crossing the context-pruning
threshold recorded the agent's invocations but not the summariser's,
leaving a fixture that could not reproduce the pruned context.

* 🧾 fix: Harden Record Mode and Make the Rendered-Text Assertion Honest

CI caught what local runs had not: the committed fixture was never
replayed locally, because the record run overwrote it after the replay
check rather than before. Re-recording and replaying in that order is
what surfaced the rest of this.

The DOM assertion compared raw recorded text against rendered markdown.
The previous answer opened with `52.`, which Markdown renders as an
ordered-list marker, so those characters never appear in the DOM and the
match failed on all three CI attempts while replay itself was correct.
The closing prompt now asks for prose beginning with a word, a leading
enumerator is stripped before matching, and only a prose prefix is
compared.

Derived configs discarded the record-mode restriction. `config.redis.ts`
and `config.mermaid.ts` spread this config and then replace `testMatch`,
so `e2e:mock:redis` in record mode would still send its specs to the paid
provider. A restriction expressed as an overridable value cannot hold, so
record mode now refuses any config but the mock one.

Superseded recording callbacks could write across a reset. A failed
attempt with a provider call still in flight keeps its handler on the old
graph; after the retry reset, that call would allocate an invocation from
the new counter or append an `error` entry with a cleared mapping.
Handlers now carry the recording generation they were installed for and
ignore everything from an older one, and attachment dedupes against the
current generation so a graph carried across a restart is not left with
an inert handler.

* 🚧 fix: Make Summarization an Explicit Boundary, Not a Half-Feature

Recording summarization invocations without replaying them is worse than
ignoring them. Replay routes the agent model and subagents only, so a
recorded summarization entry takes a slot in the fixture sequence that
replay never consumes, and the next primary call reads the summariser's
chunks — a prompt mismatch or, worse, silently wrong content.

The attachment was also aimed at the wrong shape: the SDK reads
`summarizationConfig.parameters`, not `.parameters` nested under
`.config`, so the previous attempt would have attached to nothing in a
real run. Its test passed only because the test built the shape the code
expected rather than the shape the SDK provides.

Rather than ship a half-routed feature, recording now fails the moment
summarization runs, naming the reason. Both shapes are guarded so the
guard cannot miss the way the recorder did. Summarization fixtures need
replay routing for that model before they can be supported.

The derived-config guard added alongside it was itself broken: workers do
not carry `--config`, and the argument lookup fell through to
`process.argv[0]`, so every recording run aborted claiming the node
binary was an unexpected config. The flag is now located explicitly and
absence is treated as "not the process that parsed the CLI".

* 🔒 fix: Close the -c Config Alias and Pin the Recorder's Fixture Name

Playwright documents `-c` as an alias for `--config`, so record mode
launched as `playwright test -c e2e/playwright.config.redis.ts` slipped
past a guard that recognised only the long spelling. Both spellings and
both `=` and space forms are now parsed.

Accepting arbitrary fixture names also worked against the ambiguity
check. This spec drives one fixed prompt pair, so recording under another
name left two fixtures sharing those prompts; replay then refused to bind
either and the keyless lane stopped working — a successful documented
recording run could disable the suite it exists to serve. The spec now
records only the fixture it owns and says so when asked for another.

* 🔧 test: Record a Real Tool-Call Turn and Replay It Through the Tool Node

The fixture format carried `tool_call_chunks` and the binding advanced
through a turn's invocations, but nothing had recorded a real
tool-calling conversation end to end — the path was covered only by
hand-written synthetic fixtures, and it is the first one a new scenario
would exercise.

This records one: the provider calls the `remember_fact` MCP tool, the
tool runs, and the model is invoked a second time with its result. That
is the shape a single prompt cannot express — one user turn spanning
several model invocations, all sharing one prompt — so it is what proves
the turn-vs-invocation distinction the binding rules were built around.

Replay drives the real tool node rather than replaying its output, so the
tool executes again and the assertion checks its live result.

Two fixtures now coexist, which the record path had to grow for: the
config keeps an allowlist so an unknown name is still refused, record
mode collects every replay spec, and each spec records only the fixture
it owns and stands down for the others.

MCP tools reach the model under a server-qualified name
(`remember_fact_mcp_e2e-memory`); that qualification has changed before,
so the assertions match the base name as a prefix rather than pinning the
suffix.

Verified: record 1 passed (15.6s, real API) then replay 1 passed (13.6s)
against that fixture, ledger drained 2/2 invocations and 35/35 chunks;
both replay specs together 2 passed; app-load, completion, chat and
mcp-ephemeral 12 passed.
2026-08-25 18:29:55 -04:00
Danny Avila
290b8664d9
🧾 feat: Track Authoritative Agent Event Outcomes (#15213)
* feat: track authoritative agent event outcomes

* fix: isolate agent event outcome types

* fix: declare agent event handler result

* fix: simplify agent event status selection

* fix: preserve authoritative event outcomes

* fix: preserve terminal event evidence

* test: use completed run-step envelope

* test: scope deferred HITL question locator

* fix: settle every agent event terminal path

* style: sort terminal host action imports

* fix: fence agent event terminal evidence

* fix: recover agent event terminal settlement

* fix: scope terminal retry hints by generation

* fix: settle terminal host actions exactly
2026-08-25 18:20:57 -04:00
Danny Avila
6360821470
🪢 feat: Coalesce Bound Agent Event Bursts (#15208)
* 🪢 feat: Coalesce Bound Agent Event Bursts

* fix: Restore API Package Build

* fix: Keep Trigger Batches Within One Window

* fix: intersect trigger batch windows

* fix: fence trigger batch lifecycle

* style: sort trigger service imports

* fix: make batch requeue crash-recoverable

* fix: fence concurrent batch requeues
2026-08-25 10:48:56 -04:00
Danny Avila
6d499ba3ce
fix: Anchor Resumed Elapsed Time at the Generation's Real Start (#15204)
Some checks are pending
Publish `@librechat/client` to NPM / pack (push) Waiting to run
Publish `@librechat/client` to NPM / publish-npm (push) Blocked by required conditions
Publish `librechat-data-provider` to NPM / pack (push) Waiting to run
Publish `librechat-data-provider` to NPM / publish-npm (push) Blocked by required conditions
Publish `@librechat/data-schemas` to NPM / pack (push) Waiting to run
Publish `@librechat/data-schemas` to NPM / publish-npm (push) Blocked by required conditions
Docker Dev Images Build / build (Dockerfile, librechat-dev, node) (push) Waiting to run
Docker Dev Images Build / build (Dockerfile.multi, librechat-dev-api, api-build) (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: Anchor Resumed Elapsed Time at the Generation's Real Start

A reload emptied the Recoil anchor, so the indicator fell back to its
mount time and visibly reset to 0s over a run that had been generating
for much longer. The stream status the resume path already reads carries
the server-recorded generation start; the fill now prefers it, so a
reattached run reports real elapsed time. The fill remains fill-only:
a same-session reattach keeps its original ask baseline, and the
indicator's existing clamp absorbs any client/server clock skew.

* 🕰️ fix: Rebuild the Resumed Baseline From the Server-Computed Age

Codex round 1: anchoring at the server's raw createdAt compares two
clocks — a client behind the server froze the resumed reading at 0s for
the skew, one ahead inflated it. The status route now also reports the
generation's age computed on its own clock, and the client rebuilds a
clock-local anchor as Date.now() minus that age, so each machine only
ever compares to itself. Raw createdAt stays as the fallback for an
older server mid-rolling-deploy.

* 📥 fix: Compute Elapsed Age in TypeScript, Anchor It at Status Receipt

Codex round 2: the elapsed computation moves into packages/api as
getGenerationElapsedMs — the route now just delegates, keeping the
response contract type-checked and the /api surface a thin wrapper —
and the client subtracts the age from the moment the status response
arrived (dataUpdatedAt) rather than from apply time, so a slow history
fetch between receipt and apply can no longer shrink the reading.
Declined with rationale: a shared clock source across replicas — the
residual is inter-replica NTP drift, milliseconds against the
minutes-scale client skew this PR eliminates, and the helper gives any
future shared-clock upgrade a single home.
2026-08-25 09:35:10 -04:00
Danny Avila
d9e6250d05
🛑 fix: Separate Agent Event Backpressure From User Bans (#15200)
* 🛑 fix: Separate Agent Event Backpressure From User Bans

* fix: Address Agent Event Review Findings

* fix: Mirror Case-Insensitive Agent Control Routing
2026-08-25 09:27:35 -04:00
Danny Avila
e9dec7749a
🕶️ fix: Unhide Event Subagent Names on the Dark Surface (#15206)
The event subagent group's child rows are raw buttons with no text color
of their own, and the section root set none either, so the agent name
labels inherited straight from the unthemed black body color — invisible
on the dark surface (and silently off-token in light mode: pure black
where --text-primary is 33 33 33). The slug and status lines carried
explicit text-text-secondary, which is why only the names vanished.

Root gets text-text-primary, matching SubagentActivity and
SubagentThreadPanel, so every descendant inherits the theme role and the
rows' secondary lines keep their explicit overrides. Verified against
the live cascade: the label computes rgb(0,0,0) in both modes today and
the token color (236/236/236 dark, 33/33/33 light) with the root themed.
2026-08-25 09:25:06 -04:00
Danny Avila
877b9b2f1a
🐚 feat: Nonce-Based Content Security Policy for the SPA Shell (#14446)
* 🛡️ feat: Configurable Baseline HTTP Security Headers

Adds helmet's CSP-independent headers (HSTS, X-Frame-Options,
X-Content-Type-Options, COOP, CORP, Referrer-Policy) on every response,
with contentSecurityPolicy explicitly disabled. Every header that can
break a deployment is configurable, so there is no allow-list to go
stale the way #7377's hardcoded CSP directives did.

HSTS includeSubDomains defaults off rather than matching helmet's
on-by-default: it would otherwise pin every sibling subdomain to HTTPS
for a year in every visitor's browser, and undoing that requires
serving max-age=0 from each affected host.

* 🛡️ feat: Nonce-Based Content Security Policy for the SPA Shell

Adds an opt-in, per-response nonce CSP on the HTML response, resolved once
at startup so each request only mints a nonce and concatenates the header.
Report-only by default, since that is the rollout step #7377 skipped.

Rebase and correctness pass over #13226:

- Styles carry no nonce. A nonce in style-src makes browsers ignore
  'unsafe-inline', which would have blocked the <style> element the theme
  script injects at runtime, plus every style third-party components inject.
- frame-ancestors 'self' is now a default rather than opt-in, so enabling
  CSP actually covers the clickjacking half of #7110.
- CSP_SCRIPT_SRC_EXTRA now drops 'strict-dynamic', which would otherwise
  make browsers ignore the very hosts the operator configured.
- Nonce stamping runs after the query-devtools bootstrap injection so that
  injected script is covered too.

* fix: replace frame-ancestors instead of merging it

Merging the configured value into the default turned a deliberate
CSP_FRAME_ANCESTORS='none' into `frame-ancestors 'self' 'none'`, which
browsers resolve back to 'self'. Also bail out if the serialized policy
somehow lacks the nonce slot rather than emitting a header the shell
cannot match.

* fix: address Codex review findings on the CSP defaults

All five were real against LibreChat's actual runtime:

- CSP_REPORT_ONLY now only enforces on an explicit false/off/0/no. A typo
  or `1` previously fell through isEnabled() to enforcing, turning a
  config slip into a blocked SPA. Shares the parse helper with
  headers.ts via a new security/env.ts.
- Module preloads are stamped. A production client/dist/index.html
  carries 32 parser-inserted `<link rel="modulepreload">` tags, which
  'strict-dynamic' does not cover and 'self' cannot rescue.
- Stale nonce attributes are replaced rather than preserved; only the
  current response's nonce is authorized.
- worker-src allows data:, which Monaco's default CDN loader needs to
  bootstrap its workers (there is no loader.config() in the client).
- script-src allows 'wasm-unsafe-eval' for the HEIC upload path, which
  compiles WebAssembly through heic-to. Narrower than 'unsafe-eval'.

Verified against the real built shell: 4 scripts and all 32 preloads
nonced, stylesheets/icons/manifest and <style> untouched.

* fix: address second Codex round on CSP rollout controls

- SECURITY_HEADERS=false now disables CSP too. It is documented as the
  global kill switch, and an operator reaching for it to recover a shell
  broken by an enforcing policy must not be left with that policy on.
- The SPA shell is forced to `no-store` while CSP is enabled, ignoring
  INDEX_CACHE_CONTROL/INDEX_PRAGMA/INDEX_EXPIRES and warning when they
  are set. A cacheable shell pins one nonce across page loads and users,
  which is the whole thing a nonce policy defends against.
- Added CSP_ALLOW_WASM and CSP_ALLOW_DATA_WORKERS. The previous commit's
  .env.example claimed CSP_ADDITIONAL_DIRECTIVES could drop
  'wasm-unsafe-eval' and data:, but merging only ever appends sources, so
  the documented hardening step was impossible. These toggles make it real.
2026-08-25 09:18:52 -04:00
Marco Beretta
bf6144c9e1
🎛️ fix: Withhold the Seeded Model Catalogue Until Models Resolve (#15035)
`useGetModelsQuery` seeds from a static fallback config, so `modelsQuery.data`
describes a hardcoded model list both before the mounted fetch resolves and
after it fails outright. The agent builder read that seed as authoritative and
offered models the active server configuration never exposed.

Blank the catalogue until the mounted fetch actually succeeds, surface the
failure in the model panel instead of silently falling back to the seed, and
refuse to create an agent against a provider/model pair the resolved catalogue
does not offer.

Also wires the builder's orphaned `htmlFor` labels to the controls they name.
2026-08-25 08:58:02 -04:00
James Todaro
018775de07
🧾 fix: Honor Disabled Transactions on the Assistants Usage Path (#15100)
* 🧾 fix: Honor Disabled Transactions on the Assistants Usage Path

Thread the resolved transactions config through `recordUsage` from each of
its callers, so `transactions.enabled: false` is honored on the assistants
token spend path.

* 🧾 fix: Thread the transactions config through the vision-request caller

Address review: `ToolService.processVisionRequest` also records usage without
the resolved config, and `recordUsage`'s documented return type did not match
the function.

* 🧾 fix: Set the resolved transactions config after the usage spread

- provider usage could carry a `transactions` key that overwrote the trusted value
- matches the ordering the other `recordUsage` callers already use
2026-08-25 08:30:12 -04:00
Danny Avila
16dd677be4
🎨 style: Set Question Popover and Subagent Panel on the Sidebar Surface (#15201)
Both floated over the chat on surfaces one step too close to it — the
question popover on surface-secondary, the subagent thread panel on the
chat's own surface-primary. Both now use surface-primary-alt, the
conversation-list sidebar's role, verified in the running app: popover,
panel, and sidebar all resolve to the same computed background in dark
(rgb 23,23,23) and light (rgb 247,247,248). Inline question cards keep
surface-secondary deliberately — that is the tool-record family's
surface, and settled questions collapse into that family.
2026-08-25 08:29:42 -04:00
Danny Avila
2ef12b1e1d
🦺 feat: Configurable Baseline HTTP Security Headers (#14445)
Adds helmet's CSP-independent headers (HSTS, X-Frame-Options,
X-Content-Type-Options, COOP, CORP, Referrer-Policy) on every response,
with contentSecurityPolicy explicitly disabled. Every header that can
break a deployment is configurable, so there is no allow-list to go
stale the way #7377's hardcoded CSP directives did.

HSTS includeSubDomains defaults off rather than matching helmet's
on-by-default: it would otherwise pin every sibling subdomain to HTTPS
for a year in every visitor's browser, and undoing that requires
serving max-age=0 from each affected host.
2026-08-25 08:21:39 -04:00
Ravi Kumar L
3d2da403ce
🥛 fix: Drop Stale Saved Model Defaults in Builder Forms (#15179) 2026-08-25 08:18:17 -04:00
Danny Avila
4b113697b5
🔌 feat: Background Execution Toggles for Actions & Plugin Tools (#14407)
* 🧵 feat: Background Execution Toggles for Actions & Plugin Tools

* 🩹 fix: Resolve action background opt-in across encoded-domain forms and scope it per action

* 🧹 refactor: Resolve action domain in a single pass

* 🧩 fix: Merge Normalized Action Background Options

* 🪢 fix: Reconcile Action Background Aliases

* 🧭 fix: Harden Action Background Compatibility

* 🕰️ test: Allow Settled Task TTL Expiry

* 🧬 fix: Merge Refreshed Action Tool Registrations
2026-08-25 08:13:13 -04:00
James Todaro
4d246469dd
🧾 fix: Honor Disabled Transactions on the Abort Paths (#15099)
Resolve the transactions config from the request and forward it to both
abort write paths, so `transactions.enabled: false` is honored when a
generation is stopped.
2026-08-25 08:10:26 -04:00
Danny Avila
cc0111b3cf
📐 fix: Set the Elapsed Reading on the Column Its Neighbors Share (#15195)
The timer sat at the footer's flush left while everything around it is
inset 6px: the streaming dot pads (24 − 12) / 2 to center on the size-6
header icon's axis, and the hover-button glyphs that replace the timer
sit behind their own p-1.5. The same ps-1.5 inline-start inset lines the
reading up with the dot above it and the glyphs that follow it — measured
in the live app: timer x 382, dot x 382, first settled glyph x 382.
2026-08-25 07:52:37 -04:00
Danny Avila
862ebf3235
🪢 fix: Persist Failed Agent Turns Before Error Publication (#14118) 2026-08-25 06:50:46 -04:00
Danny Avila
a9d99b3771
📌 fix: Keep the Settled Turn Mounted Through Final Content Compaction (#15186)
* 📌 fix: Keep the Settled Turn Mounted Through Final Content Compaction

The agent aggregator writes content parts at provider-source indexes, so
the streamed array is sparse wherever a step produced nothing; the final
SSE event carries the persisted, compacted array. Adopting it verbatim
shifted every part after a hole, re-keying every index-derived React
identity: the settled message remounted wholesale, activity-phase groups
replayed their fold-in entrance, code panes re-highlighted, and the
thread visibly snapped up and down at the end of every tool-calling run.

finalHandler now pairs the compacted parts with their streamed
counterparts in order and stamps each with the index it streamed at
(`streamedIndex`, client-only); render keys read the stamp while all
coordinate logic (edit indexes, phase bounds, cursor) stays on the live
compacted positions the server persisted. Phase-segment keys also anchor
to their first defined part instead of the segment ordinal, since
phantom hole-only segments vanish at compaction and shifted every
segment after them.

* 🔁 fix: Carry Identity Stamps Through Re-Delivered Finals and Parallel Attribution

Codex round 1, both real:
- P1: a later final event can re-deliver an already-settled message as a
  fresh compact array (Assistants runMessages resync); index-aligned
  pairing returned it unstamped, wiping the previous settle's stamps and
  re-keying the older turn all over again. The pairing now carries the
  matched current part's stamp forward, so a settled turn keeps its keys
  through every subsequent final.
- P2: ParallelContentRenderer's sequential stretches invoked
  renderResumeAttribution with only the live index, so steer attribution
  nodes in parallel content still re-keyed at the swap. The stable key
  index now threads through both call sites; getPartKeyIndex moves to
  utils/messages beside the stamp writer it reads.

* 🧿 fix: Require Content Agreement Before Pairing Streamed Identity

Codex round 2 (P2, real): hide_sequential_outputs runs omit intermediate
parts from the final array, so a type-only match could hand the retained
output an omitted intermediate's identity — transferring its key and any
UI state. Non-tool pairing now requires content agreement: mutual-prefix
text for TEXT/THINK/ACTIVITY_LABEL (one side extending the other is the
same part observed at two moments), the Open Responses phase for TEXT,
and the label kind for activity labels — a blank reservation still pairs
with its filled label. Ambiguous shapes fall back to the pre-stamp full
re-key, which is honest for a final that visibly removes parts.

* 🪢 fix: Refuse Stamping When the Server Removed Content; Strip Stamps on Edited Reruns

Codex round 3, two of three real:
- Prefix agreement alone still mis-paired when an omitted intermediate
  happened to prefix the retained output. Pairing now also requires that
  no substantial streamed part is left over: leftovers mean the server
  removed content (hide_sequential_outputs), so every in-order pairing
  is suspect and the message re-keys plainly instead.
- An edited resubmission clones the settled (stamped) prefix and appends
  the rerun's parts at the prefix length; a retained stamp at or above
  that length collides with an appended part's key. The clone now strips
  the client-only stamps, reverting the retained prefix to physical
  identity for the rerun.

The third finding (content-segment keys under late-phase recovery) is
declined with rationale on the PR: user expansion overrides survive via
the message-wide expansion map with stable group ids, recovery is a
genuine restructure at the moment a phase materializes, and first-child
anchoring is the only choice stable under the two high-frequency events
(streaming appends and final compaction).
2026-08-25 06:26:17 -04:00
Danny Avila
ac2aef00f6
🫗 fix: Drain Quoted Excerpts Into Mid-Run Steering (#15175)
* 🧭 fix: Carry Quoted Excerpts Through Mid-Run Steering

"Add to chat" quote chips were dropped by every during-run steer path: the
steer POST had no quotes concept, so a composer-origin steer left the chip
staged (gluing onto the NEXT send) and a queued item steered into the live
run lost its quotes silently.

Quotes now ride the steer protocol end to end:
- POST + admission: `quotes` on the steer body, normalized like the chat
  route's (getReferencedQuotes caps), part of the idempotency fingerprint
  only when present so pre-existing receipts still replay.
- Injection: merged into the model-bound turn as Markdown blockquotes at
  both boundaries (text-only and media paths), mirroring prependQuotes.
- Persistence + replay: the STEER content part stores `quotes` separately
  from the typed text; stampSteerPartMedia re-merges them per turn (even
  with resendFiles off) via the SDK's transient media stamp, with the quote
  block folded into the token budget.
- UI: composer steers/interrupt-steers drain the chips (skill picks stay
  staged — they configure a NEW turn's run); SteerPart and the in-flight
  bubble render the same MessageQuotes reference blocks as user bubbles;
  queued/failed rows show a quote count; reconnect reseeds fall back to the
  server item's quotes when no local chip survives.
- buildMessages keeps its zero-await path to the parallel context kickoff
  via a synchronous stamp-target probe.

* 🧭 fix: Keep Quotes in the Client-Safe Steer Projection

toPendingSteer is the projection behind resume-state pendingSteers, abort
responses, and terminal leftover claims — dropping quotes there would lose
them on exactly the recovery paths the reconnect reseed's server fallback
relies on.

* 🧪 test: In-Flight Steer Bubble Renders Carried Quotes

* 🔁 fix: Re-Stage Quotes When a Pre-Quotes Replica Accepts the Steer

Codex flagged the rolling-deploy window: an old replica 202s a quoted steer
while dropping the excerpts, so the client cleared the chips for context the
model never received.

The 202 (fresh and receipt replay) now echoes quotesAccepted from the
DURABLE item; a missing echo on a quote-bearing composer-origin steer
re-stages the excerpts as composer chips — the pre-steer behavior, so they
ride the next send instead of vanishing — and strips them from the surviving
chip so a later terminal conversion cannot duplicate them. Queued-origin
steers keep quotes on the item, whose restore paths already return it
intact. The residual cross-version lost-ACK retry stays fail-closed as a
409 idempotency conflict (failed chip with retry controls).

* 🔁 fix: Close the Remaining Cross-Version Quote-Loss Windows

Codex round 2:
- Send now of a quoted queued item against a pre-quotes replica now
  re-stages the excerpts too (the row is consumed and the words inject
  bare, so the composer is their only remaining home); the strip clears the
  chip's captured origin copy so reclaims and terminal conversions cannot
  duplicate them.
- A quoted retry whose lost first ACK was accepted by a pre-quotes replica
  now REPLAYS that legacy receipt instead of 409ing: the stored fingerprint
  matching the quote-less hash of the same words proves the cross-version
  case, and the replayed 202's missing echo drives the re-stage. Different
  quotes against a quote-bearing receipt still conflict.
- TSteerAppliedEvent.part gains the quotes field (typed SSE consumers).

* 🧪 test: Drop the Stale Narrow SteerDrainOutput Alias

The spec's local intersection re-declared injectedMessages with
content: string, predating the SDK pin that declares the field natively
(content: string | MessageContentComplex[]). Under CI's clean install the
hook's BaseHookOutput is no longer assignable to that narrower alias; the
plain PostToolBatchHookOutput is the correct type for every drain/boundary
assertion. Verified against the published 3.6.16 dist and the local one.

* 🔁 fix: Honor the Generation Owner's Quote Capability End to End

Codex round 4:
- steerQuotesCapable rides job metadata (createJob + HITL resume rewrite),
  mirroring preemptCapable's owner-recorded pattern: an upgraded admission
  replica no longer stores quotes — or claims them accepted — for a
  generation whose older owning drain would silently drop them at
  injection. The missing echo drives the client re-stage, and a later
  capable handover cannot double-deliver restored context.
- Applied events reconcile dropped quotes: when a quote-less applied part
  settles a quote-bearing chip (the lost-202 ordering the ACK-echo path
  cannot see), resolveSteerChip and both reconnect settle paths re-stage
  the chip's excerpts before removing their only copy. mergeRestagedQuotes
  dedupe keeps every trigger idempotent for the same excerpts.

* 🔁 fix: Re-Read Quote Capability at the Last Moment and Cap Restaged Chips

Codex round 5:
- A HITL resume rewrites steerQuotesCapable without changing the
  generation's createdAt, so the enqueue fence cannot see a
  capable-to-legacy handover landing during admission's awaits. Re-read
  the owner's flag immediately before item construction (paid for only by
  quote-bearing requests); the residual between re-read and enqueue commit
  matches preemptCapable's documented race.
- mergeRestagedQuotes now respects the 10-quote contract with the staged
  chips winning: a restored tail that cannot ride the next send is dropped
  explicitly instead of rendering as a chip the submission would silently
  discard. MAX_QUOTE_COUNT moves to utils/steer as the single client
  source; QuoteButton imports it.

* 🔁 fix: Steer Quote Coverage for Preflights, Memory, and Single-Scan Stamping

Codex round 6:
- Stored-message policy inspection now extracts steer-part quotes as quote
  fragments (path /content/N/quotes/M), so conversation import and shared
  link preflights inspect the newly persisted field exactly like top-level
  message.quotes.
- The memory copy gets its own quote-merge stamp (text only, resendFiles
  false): formatAgentMessages ignores part.quotes, so without it a steer
  whose substance lives in its excerpt reached the chat model but never
  memory extraction.
- collectSteerStampTargets replaces the boolean probe: buildMessages
  collects once and hands the targets to stampSteerPartMedia, keeping the
  zero-await fast path without scanning the history twice.

* 🔁 fix: Redis Quote Plumbing, Conversion-Race Guard, and Quote-Bound Recovery Proof

Codex round 7:
- RedisJobStore.deserializeJob now restores steerQuotesCapable (the explicit
  mapper otherwise dropped it on every read, leaving quote steering inert in
  Redis deployments), with the round-trip spec extended.
- Both Lua parked-steer projections (terminal close + generation
  replacement) forward item.quotes, matching toPendingSteer — a lost final
  no longer strips excerpts from durable recovery in Redis mode.
- The no-echo restage reads the SURVIVING chip (reclaimRejectedChipQuotes):
  a terminal conversion that beat the delayed 202 already moved the quotes
  onto the queued follow-up, and re-staging them again double-delivered.
  Regression-tested with the conversion-before-ACK ordering.
- RecoveredSteerPayload binds normalized, order-significant quotes (builder,
  validator, TS matcher, and the Lua decode+matcher): a stale client
  presenting the same recoverySteerId with altered or missing quotes cannot
  consume the parked source. Quote-less sources keep matching quote-less
  recoveries.

* 🔁 fix: Execution-Bound Quote Capability with an Atomic Enqueue Predicate

Codex round 8:
- steerQuotesCapable becomes a transient assertion translated (at createJob
  and in ApprovalLifecycle.resolve) into steerQuotesExecutionId, valid only
  while it equals the LIVE providerExecutionId. A legacy replica winning a
  HITL resume rewrites the execution id without knowing the marker, so its
  stale assertion self-invalidates — a bare boolean could not be cleared by
  code that predates it.
- The fenced enqueue evaluates that equality atomically (all three Redis
  scripts decode-and-strip like the existing preemptCapable normalization;
  both InMemory sites mirror it) and returns the persisted item, so the
  quotesAccepted echo reflects exactly what was stored even when a handover
  lands between admission's read and the commit. The last-moment re-read is
  gone — the transaction is the authority.
- Tests: capable-resume re-binding, legacy-resume omit-not-clear
  invalidation, the admission-vs-handover race (capability read true, then
  execution rewritten before enqueue), and the Redis round-trip of the
  marker.

* 🔁 fix: Full Redis Parking Coverage and Loss-Moment Quote Restaging

Codex round 9:
- The two remaining Redis parking projections (terminal status CAS and
  stale-running cleanup) forward item.quotes — every field-picked steer
  projection now carries them (audited: 2 Lua 'projected' + 2 Lua
  'clientItem' + toPendingSteer).
- The ordinary no-echo ACK no longer re-stages: the steer has not injected
  yet, so the quotes stay carried on the pending chip. A quote-less applied
  event re-stages them at the actual loss; a terminal leftover conversion
  carries them onto the recovered row, whose normal send delivers quotes on
  any server — re-staging at the ACK let that leftover auto-send bare text
  while the excerpts glued onto an unrelated draft. Only the settled
  receipt replay (already injected, no future event) reclaims immediately.

* 🔁 fix: Legacy-Replayable Receipts with Separate Quote Identity

Codex round 10: an upgraded-first receipt stored a quote-inclusive
fingerprint no pre-quotes replica could recompute, so a lost-ACK retry
routed through one 409'd already-accepted words with duplicate-send
controls.

The durable fingerprint reverts to the quote-independent 3-field hash —
the one shape EVERY deployed version computes, replayable across a rolling
deploy in both directions — and quote identity moves beside it as
requestedQuotesFingerprint (of the REQUESTED quotes, pre any capability
strip, so an incapable-owner acceptance still replays its own retries).
Absent records (legacy-written or quote-less) accept any same-words retry,
preserving the round-5 rule; present records must match exactly, keeping
different-quotes clientSteerId reuse a 409 on quote-aware readers. Under
the keep-on-chip client contract a legacy replay's missing echo is
harmless — the excerpts stay carried on the pending chip.

* 🧪 chore: Re-Trigger CI After Dropped Workflow Events
2026-08-24 22:29:13 -04:00
Danny Avila
c0a55aa0f5
🧮 fix: Currency-Safe Single-Dollar LaTeX via Micromark Tokenizer (#15181)
Replaces the preprocessLaTeX string pass, whose currency allowlist missed
suffixes like "$2bn", letting SINGLE_DOLLAR_REGEX rewrite "$2bn to at
least $4bn" into $$-math. Single-dollar math is now a micromark text
construct (client/src/utils/latex.ts) registered by remarkSingleDollarMath,
so each span is decided during parsing with Pandoc-style boundary rules:
non-space after the opener, non-space before and no digit after the
closer, single-line, no backticks, opaque backslash escapes, balanced
braces, and fail-fast on an invalid close so a later price dollar can
never extend a span. Rejected spans stay byte-identical text, and code
spans, fences, and autolinks are structurally protected by the parser.

The LaTeX parsing setting now gates only this plugin; $$, \(...\), and
\[...\] continue to parse unconditionally via remark-math (aliased to
micromark-extension-llm-math, now mirrored in jest moduleNameMapper so
tests exercise the production tokenizer). katex/contrib/mhchem is loaded
with the markdown config, so \ce/\pu render properly instead of being
regex-mangled. splitMarkdown aligns its math options with the renderer.
2026-08-24 22:29:02 -04:00
Danny Avila
6988ff5d7b
✂️ fix: Unclip the Share Dialog's Public Role Menu (#15177)
PR #14734 replaced PublicSharingToggle's hand-rolled reveal (which set
overflow: visible while open) with the shared Collapse, whose permanent
overflow-hidden shears the non-portaled access-roles menu to a sliver.
Adds an opt-in overflowVisibleWhenOpen prop to Collapse — clipped while
closed and during the closing tween, unclipped once open — so in-tree
popovers can escape; the menu stays non-portaled because portaled menus
inside modal OGDialogs land aria-hidden and get focus-yanked shut.
2026-08-24 20:59:07 -04:00
Danny Avila
69e7c73614
🎛️ feat: Expose Authoritative Subagent Controls (#15169)
* feat: expose authoritative subagent controls

* fix: reconcile subagent control races

* fix: reconcile durable control conflicts

* fix: preserve authoritative subagent control outcomes

* fix: fence subagent controls to child thread

* fix: validate subagent control targets before routing

* fix: close subagent control boundary gaps

* fix: keep control reservations private

* fix: close subagent control admission gaps

* fix: preserve authoritative control history

* style: sort subagent control imports

* fix: preserve authoritative subagent control retries

* style: sort control state imports
2026-08-24 20:37:49 -04:00
Danny Avila
d641c398d5
🧳 fix: Port Subagent Control Receipt Writes to DocumentDB-Safe Operators (#15171)
* fix: harden subagent control receipt persistence

* fix: harden durable subagent control replay

* fix: await terminal control receipts on shutdown

* fix: close subagent control replay races

* test: type stale-owner transport fixture

* fix: quiesce durable subagent controls

* test: await subagent shutdown durability boundary

* fix: serialize durable subagent controls

* fix: fail shutdown on cleanup errors

* fix: report cancellable result availability accurately

* fix: fence subagent control receipt ownership

* fix: close distributed control receipt races

* test: type control receipt race fixture

* chore: require authoritative control receipts

* fix: close subagent control lifecycle races

* style: separate control reservation member

* test: harden subagent settlement wait

* fix: preserve authoritative control replay state
2026-08-24 20:05:39 -04:00
Danny Avila
afcf2e886c
📦 chore: bump @librechat/agents@latest to v3.7.1 (#15176) 2026-08-24 16:06:25 -04:00
Marco Beretta
649e68170e
🖼️ refactor: Consolidate Provider Icons Into a Single Registry (#15148)
* test: make useIsActiveItem observer assertions deterministic

The two attribute-flip tests mutated inside act() and then raced a 4 second
waitFor against MutationObserver delivery, so they failed once the client
workspace gained enough suites for a worker to stall past that budget.

Wait on actual observer delivery instead. The hook registers its observer on
mount, so it is ahead of the test's in delivery order and has already reacted
by the time the promise resolves. The new helper filters on data-active-item
because React writes data-active onto the same element when it re-renders, and
an unfiltered observer would resolve on that write instead.

This removes the last wall-clock dependence in the file, so the 20 second
jest timeout is no longer needed.

* feat: add canonical ProviderId vocabulary and resolver

* feat: resolve custom endpoint provider identity at config load

* feat: add provider icon registry data

* feat: add ProviderIcon and ProviderAvatar components

* feat: add provider icon resolution hook

* refactor: migrate direct icon lookups to the provider registry

* refactor: migrate composite endpoint icons to the provider registry

* refactor: render message provider icons from the registry

* refactor: remove the duplicated endpoint icon maps

The model selector was the last consumer of the icons map, so it now
resolves art through the provider registry like every other icon call
site. That leaves getIconKey with no callers, and the five icon map
types it depended on with no references, so all of them go too.

* fix: address Codex review findings on provider icons

Move brand tile colors onto theme tokens, accept relative image paths,
pass endpoint config into message icon resolution, keep Cohere padding
on landing only, render configured image URLs in provider-only
consumers, preserve the Gemma label, and publish provider assets with
the shared client package.

* fix: address remaining Codex findings on provider icons

Keep monochrome art white on branded avatar tiles, inline provider
assets as module data URLs so ProviderIcon works outside the SPA, and
recognize api.cohere.ai when resolving custom endpoint brands.

* fix: address the latest Codex review notes

Stop inlining provider logos into the shared bundle, keep agents and
assistants marks on group icons, reject CSS appended to brand
gradients, give brand tokens hex fallbacks for package consumers, and
treat data image URLs as configured artwork.

* fix: honor native provider and theme-controlled avatar contrast

Use an explicit custom-endpoint provider when host branding misses,
keep agents and assistants marks on model specs, and drive branded
avatar foreground from a theme token instead of a raw white class.

* fix: tighten brand validation and inherit SVG fill color

Forward the computed color class into provider SVGs, accept only a
single balanced gradient for brand backgrounds, keep provider
foreground hex-only, recognize relative image fragments, and preserve
percentage sizing in URLIcon fallbacks.

* fix: keep EndpointIcon hook-free and accept protocol-relative icon URLs

useMentions.ts invokes EndpointIcon({...}) as a plain function in seven
places, inside useMemo mappings and a React Query select callback, so the
useProviderIcon call added to it ran a hook outside a render and threw
"Invalid hook call" as soon as the mention list was built. It now uses the
hook-free resolveProviderIcon, and a spec pins the imperative-call contract
those call sites depend on.

isImageURL explicitly rejected protocol-relative URLs, so an endpoint or
model group configured with //cdn.example.com/provider.png fell through to
provider resolution and rendered the generic mark, where the removed
UnknownIcon rendered any nonempty custom iconURL. A leading // followed by
a host is now an image; a bare // or /// still is not.

The ConvoIcon spec's two cohere conversations move to one shared fixture,
since ProviderId.cohere is not an EModelEndpoint and a single-step
assertion to TConversation failed the client type check.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MWvn6ezgLmN8D5GDmFVnwv

* fix: annotate themeBrandTokens for isolatedDeclarations

packages/client compiles with isolatedDeclarations, under which
`as const satisfies` is not an explicit type annotation, so the emitted
declaration could not be produced from the initializer alone.

This never surfaced before because the "Type check @librechat/client"
step only runs after "Type check @librechat/api", which was failing on
dev's Agents SDK issue and skipping it.

Annotated as readonly (keyof IThemeBrands)[] and frozen, matching
themeColorTokens directly above it. Both consumers only call .includes()
and .map(), so no literal tuple type is lost.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MWvn6ezgLmN8D5GDmFVnwv

* fix: keep nested provider SVGs at their span's size

ProviderIcon sizes component art with an outer span carrying an inline
width/height, then rendered the SVG with cn('h-full w-full', classes).
Because cn is twMerge, a caller's own sizing class won that merge, so the
fraction applied twice: Landing passes size={41} with h-2/3 w-2/3, ConvoIcon
scales to a 27px span, and the SVG then took two thirds of that again, ~18px
where it used to be ~27px.

Only component-backed providers regressed. The asset branch has no wrapping
span, so its fraction still resolves against the 40px container.

Reordering the merge makes the span's size authoritative while leaving every
other caller class in place, including the [color:inherit] that branded
avatars forward. The img branch keeps resolving against its parent, so its
size is unchanged.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MWvn6ezgLmN8D5GDmFVnwv

* fix: close the image-format and provider-host tables

Two allowlists that the refactor narrowed, fixed as sets rather than one
entry at a time.

isImageURL's extension list had grown by patch four times, each round
restoring one form the old renderer accepted. It now carries every format
browsers actually render, so avif joins apng, bmp, cur, jfif and the jpeg
spellings in a single pass.

The host table had no Azure entry, so an OpenAI-compatible endpoint on
team.openai.azure.com fell through to the generic mark; the custom schema
cannot express provider: azure, so host was its only signal. Both supported
Azure suffixes are added, and enumerating ProviderId against the table
surfaced Google as the same gap, which is added too.

Bedrock, mlx and ollama are the remainder and cannot be host-resolved:
bedrock's hostname is region-scoped under a shared AWS suffix, and the other
two are served from the operator's own machine. That is now recorded next to
the table and pinned by a test, so a provider added later without a host
fails rather than silently rendering the generic mark.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MWvn6ezgLmN8D5GDmFVnwv

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-08-24 13:00:38 -04:00
Danny Avila
3df046f29a
🎓 ci: Graduated E2E Spec Skipping, Wired Dark Until Armed (#15172)
Select emits e2e_skip from the decision's e2e.graduated (skippable-tier specs
whose clean-trial streaks meet the pre-registered bar, 2x where history-
coupled, >=3 distinct days — computed server-side from the shadow's per-spec
ledger). Dark by default: the output is empty unless repo var
CODEGRAPH_E2E_SKIP=on, and even armed it accepts only a well-typed pool-path
list from a non-fail-open decision (traversal segments rejected). Shard steps
subtract the skips from a git-derived run list — unknown names match nothing,
skip-everything falls back to full, and skipped specs still execute post-merge
in every full-suite vote run.

15 verbatim guard tests, scripts extracted from this YAML and executed against
fixtures: arm/disarm, fail-open, malformed/missing/non-array lists, traversal,
out-of-pool paths, unknown names, all-skips fallback, and the 2-real-skips
59->57 arg case. The traversal case caught a real regex gap pre-commit.
2026-08-24 11:53:50 -04:00
Danny Avila
f9c051f8ea
🪶 feat: Support Non-Persistent Controlled Themes (#15170) 2026-08-24 11:52:30 -04:00
Danny Avila
a997275902
🧾 feat: Persist Authoritative Subagent Control Receipts (#15168)
* feat: persist subagent control receipts

* fix: require control receipt persistence

* fix: preserve authoritative control history
2026-08-24 11:39:56 -04:00
Danny Avila
e0d5e11cdf
⏱️ feat: Show Elapsed Time Under the Streaming Response (#15167)
* ⏱️ feat: Show Elapsed Time Under the Streaming Response

A minimalist elapsed-time indicator (5s, then 1m 5s) occupies the footer
slot the hover actions vacate while a response generates, anchored to a
per-index submission-start timestamp so remounts (new-conversation id
hydration, navigation) never reset it. The once-per-second tick is
component-local state, so streaming rows never re-render on its account.

* 🧭 fix: Keep the Original Elapsed Baseline When Reattaching a Stream

Codex round 1: resume-on-load restamped the anchor at reattach time, so
navigating away from a still-streaming conversation and back restarted
the reading at 0s — the exact reset the atom exists to prevent. Resume
paths now leave the anchor alone: a same-session return keeps its ask
baseline, and a reload (atom empty) falls back to the indicator's mount
time, which is what the stamp produced anyway.

* 🪗 fix: Scope the Elapsed Timer to Its Own Generation, Localized and Spoken

Codex round 2, all four findings:

- The anchor is cleared on every terminal path (final, error, abort
  fallback), and resume-on-load only fills an empty one — so a run another
  client started never inherits a stale baseline, while a same-session
  reattach still keeps its original start.
- The indicator additionally requires the newest sibling position:
  latestMessageId follows the selected branch, so a settled older sibling
  paged to mid-regeneration satisfied the latest+submitting gate and got a
  counting timer under settled content.
- Visible digits now come from the shared run-step duration formatter
  (Intl.NumberFormat per locale), replacing the raw-number interpolations.
- The compact reading is aria-hidden with a spoken 'N seconds elapsed'
  equivalent beside it, per the house duration-label pattern; still no
  aria-live, so the tick never announces.
2026-08-24 11:36:36 -04:00
Danny Avila
5a8700643c
perf: Build the Memory Message Copy Only When Something Reads It (#15164)
buildMessages formatted every history row twice per turn — a prompt
copy and a memory copy — then discarded the entire memory payload
unless some row carried fileContext, which is the rare case. The
memory copy has exactly two consumers: that payload, and the canonical
recount of a row, where it is content-identical to the prompt copy
unless the row itself has fileContext. So the prompt copy is now the
recount surface for context-free rows, a fileContext row builds its
memory copy at recount time, and the full memory payload is assembled
in a deferred pass — same formatting, same per-row merge order — only
once a row has proven the payload will be kept. The common turn
formats each row once instead of twice and no longer allocates a
payload it throws away.

Also forwards the run's useLegacyContent to formatAgentMessages as the
new legacyContent option, inert on the current SDK release: once the
SDK change ships, text history is emitted pre-flattened so the
per-request legacy projection stops cloning every message and the
context meter's identity-based count reuse holds across the
projection.
2026-08-24 10:33:47 -04:00
Danny Avila
6f3d303985
📍 ci: Pin the Votes Ledger Results JSON to an Absolute Path (#15166)
First live full-suite vote run (32731087273, 198 passed) wrote
e2e/pw-results.json while the ledger step looked in the repo root and took
the fail-safe branch: zero trials logged. A relative
PLAYWRIGHT_JSON_OUTPUT_NAME resolves against the config directory, not cwd —
reproduced synthetically with the config in a subdirectory. Absolute
workspace path on both the reporter env and the ledger read.
2026-08-24 10:33:12 -04:00