Commit graph

1849 commits

Author SHA1 Message Date
lia-by-librechat[bot]
1746a4ee9a
🎈 fix: Fill Reasoning Previews Before Throttling (#16178)
Co-authored-by: Lia <lia@librechat.ai>
2026-09-21 21:43:23 -04:00
Marco Beretta
14d8bb8d3c
⚡ perf: Throttle Code Highlighting While a Message Streams (#16073)
* ⚡ perf: Throttle Code Highlighting While a Message Streams

* fix: harden streamed code highlight throttling

* test: cover wall clock changes during highlighting

* style: tidy highlight regression test

* fix: restart highlight work across lifecycle changes

* style: avoid nested highlight timing ternary

* fix: propagate highlight throttle to startup config

* fix: share and validate highlight throttle

* fix: keep streamed code visible during highlighting

* test: stream highlight tool arguments

* fix: preserve highlights when cadence config resolves

* fix: reschedule highlights when cadence changes

* test: preserve default fake tool chunking

* fix: prevent stale streamed highlights

* test: open the tool pane before asserting streamed highlights

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

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

* test: reopen the rebuilt card for the settled highlight

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

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

* test: leave a window to cancel a streaming highlight

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

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

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

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-21 07:15:32 -04:00
lia-by-librechat[bot]
9b497ac17e
🪑 fix: Preserve Tool Pane Choices Through Response Finalization (#16152)
* fix: preserve tool pane choices through response finalization

* test: read real message context in content part mock

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-21 07:09:01 -04:00
lia-by-librechat[bot]
fe79265b2f
🌁 fix: Stop Painting the Closed Mobile Drawer (#16127)
Some checks are pending
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Codegraph E2E Votes / vote (full suite) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Client build recovery regression (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
* 🌁 fix: Stop Painting the Closed Mobile Drawer

* 🌁 fix: Re-assert the unpainted value when the slide settles

React owns the resting value and writes it when the travel window closes at
TRANSITION_MS; the release ran a buffer later and cleared the property, which
dropped that value while React still believed its unchanged prop was applied.
React never wrote it again, so every animated close left the drawer painted and
the artifact could recur. Re-asserted through one shared constant, the same way
the drawer width already is.

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-20 21:37:55 -04:00
lia-by-librechat[bot]
61fe243151
📠 fix: Preview SVG Artifacts From Their Edited Source (#16123)
* fix(client): map image/svg+xml artifacts to a renderable template (#16087)

* fix: Rebuild the SVG preview shell from edited source

An SVG artifact previews a derived index.html holding a copy of the
source, so replacing only the edited index.svg left the preview on the
original drawing. Expose the derived-file builder as deriveFiles and
rebuild the whole set from the editor text in SandboxArtifactTabs.

* fix: Scope the SVG preview sizing rule to the root viewport

CSS overrides SVG presentation attributes, so the unscoped `svg` rule in the
preview shell stretched every nested `<svg>` viewport to the panel, corrupting
the layout of sprites and inset diagrams. Scope it to `body > svg`.

---------

Co-authored-by: Frank_zhu <58329837+Frank-zhu0404@users.noreply.github.com>
Co-authored-by: Lia <lia@librechat.ai>
2026-09-20 21:30:06 -04:00
James Todaro
99707d64c6
🖼️ fix: Resolve Pinned Model Icons from Endpoint Config (#16089)
* 🖼️ fix: Resolve Pinned Model Icons from Endpoint Config

- pass `endpointsConfig` and `model` to `MinimalIcon` from the pinned favorites row so a custom endpoint's `iconURL` is honored

Fixes #16088

* test: Cover Pinned Model Endpoint Config Propagation

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-20 21:25:11 -04:00
Danny Avila
ddd8d78d1d
🫧 fix: Stop the Live Activity Row From Flashing Open on Code Calls and Thoughts (#16145)
* 🫧 fix: Fold a Streaming Thought Into the Live Row Before Its First Tool Call

A thought at the live tail rendered as its own row with a multi-line peek until a tool call arrived, which then snapped it into the one-row fold. With a reasoning model that talks between calls that is a jump up and back down on every step. The span now folds from the thought's first character and previews it one sentence at a time, under a reasoning glyph until a tool gives it icons.

* 🫧 fix: Keep a Live Card's Key When Its First Tool Call Arrives

* 🫧 fix: Stop Unfolding the Whole Live Span for Every Code Call Without a Leading Intent

blocksLiveFold unfolded the entire span while a bash/code call with complete args, no output and no intent was running, so its card could show the sandbox-startup label. When the model writes intent after command, every code call qualifies: a 47-call run opened to its full height and shut again on each call. The row now reads the same sandbox signal for its newest call and the span stays one card. Also keeps tool-anchored card-key aliases across finalization so a reasoning-led card a reader opened stays open when the response settles.

* 🧹 chore: Sort Imports in ActivityPhaseGroup

* 🫧 fix: Preserve Reasoning Disclosures and Isolate Streaming Siblings

* 🧪 test: Keep Real Part Identity in Content Renderer Mocks

* 🫧 fix: Migrate Sandbox Startup Readers and Writer to Jotai

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-20 21:00:21 -04:00
Danny Avila
692e7f6dc4
🖍️ perf: Highlight Tool Code Once, and Only When Its Pane Is Open (#16143)
`useLazyHighlight` tokenized the same input twice on every mount that could
highlight immediately. The state initializer highlighted during render whenever
the grammars were already loaded, which holds for every card after the first in
a session, and then the effect highlighted the same input again because its
dedupe ref started empty and could not match on a fresh mount. Each card paid
two tokenizations, two hast-to-React conversions and an extra commit.

Card bodies also tokenized while collapsed. Every code, bash, read-file and
file-authoring card highlighted its content on mount, so opening a long agent
conversation highlighted code nobody had asked to see.

The tokens now carry the key they were produced from, so the effect recognizes
what the initializer already did, and each call site passes its content only
while its pane is open. ExecuteCode gains the raw fallback its three siblings
already had: with highlighting deferred to the pane opening, rendering only the
highlighted nodes would leave the pane empty until the grammars load.
2026-09-20 20:20:53 -04:00
Marco Beretta
7dc745a95b
⚡ perf: Virtualize the Model Selector's Search Results (#16074)
* ⚡ perf: Virtualize the Model Selector's Search Results

* fix: make model search accessibility metadata global

* test: stabilize model selector search scenarios

* test: assert model selector keyboard semantics

* test: simplify model selector keyboard assertion

* test: exercise keyboard pin navigation

* fix: preserve search result announcements

* test: follow active row pin through keyboard

* test: scope pin toggle assertion

* test: scope pin toggle to active row

* test: stabilize keyboard pin scenario

* test: isolate model selector favorites

* fix: preserve virtual search boundary navigation

* test: cover virtual search boundaries

* fix: own virtual boundary by logical position
2026-09-20 19:27:47 -04:00
Marco Beretta
9cd1de30f6
⚡ perf: Split Streaming Markdown Blocks Incrementally (#16071)
* ⚡ perf: Split Streaming Markdown Blocks Incrementally

* test: cover streamed markdown block rendering

* fix: isolate streamed markdown splitter caches

* fix: satisfy markdown splitter static checks

* test: mock isolated markdown splitter

* test: isolate markdown splitter spies

* test: cover concurrent streamed markdown messages

* fix: preserve provisional streaming markdown boundaries

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-20 19:26:38 -04:00
Danny Avila
1f66e9a8e5
🫧 feat: Hold a Live Run's Activity at One Row (#16118)
Some checks are pending
Codegraph E2E Votes / vote (full suite) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Client build recovery regression (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
Sync Locize Translations & Create Translation PR / Sync Translation Keys with Locize (push) Waiting to run
Sync Locize Translations & Create Translation PR / Create Translation PR on Version Published (push) Blocked by required conditions
* 🫧 feat: Hold a Live Run's Activity at One Row

Fold the span a run is still writing into a single collapsed row from its first tool call, with a header that bubbles up the newest activity (streamed intent, generic running text, filled batch label, or the thought streaming after them) on a 500ms leading+trailing throttle. The settled rendering is unchanged.

* 🫧 fix: Name Every Live Line and Take the Fold Preference From the Host

Live header resolves failed/cancelled through resolveToolCallPhase, names trailing commentary, and only folds agents-shaped calls it can name. ContentParts takes foldLiveActivity from its host instead of reading Recoil; subagent panels opt out.

* 🫧 fix: Carry Background Stops and Nested Sign-Ins Into the Live Fold

* 🫧 feat: Preview Tail Reasoning One Sentence at a Time in the Live Row

* 🫧 fix: Keep Handoffs, Detached Failures and Status Announcements Out of the Fold's Blind Spots

* 🫧 fix: Keep the Live Line's Shimmer Off the Ticker's Animated Element

Found in Chromium: .shimmer declares animation/position/display, so on the same element it replaced the slide-out and the retired line never left. The sweep now rides an inner span, and the header button is block-level flex so a live row measures the same 28px as the settled row.

* 🧹 chore: Sort Imports in the Live Activity Helper

* 🫧 refactor: Decide a Live Line's Outcome With the Group Header's Resolver

The live header derived pass/fail on its own and re-learned, one review at a time, signals the cards already handle. getToolMeta moves out of ToolCallGroup into Content/outcome.ts and the live line reads it, which covers cancelled status attachments and memory-tool prose failures. A legacy Assistants call now ends a live span like a handoff, and the live disclosure is named by its current line alone (aria-labelledby) so the polite region's previous line stays out of its accessible name.

* 🫧 fix: Make the Live Row Agree With the Cards It Hides

Span-level outcome beside the newest line (an earlier call can fail while a later one runs), announcements with their own identity in one polite region that outlives the live header, the memory-error artifact and step-scoped attachment ownership in the shared resolver, one localized 'Failed: {{0}}' template for the card and the row, and a parity suite that compares the folded row with the REAL cards on unmocked outcome logic.

* 🫧 fix: Keep Live Subagents Unfolded and Give Reused Ids and CJK Sentences Their Own Lines

* 🫧 fix: Hold a Finished CJK Sentence and Honor Open Thinking in Live Folds

* 🫧 fix: Say "Running in Background" as the Card Does and Hold Reasoning Identity Across Whitespace

* fix: Harden live activity folding boundaries and lifecycle

* 🫧 feat: Surface a Span's Own Glyphs on Its Collapsed Header

A header stands for rows it hides, so it carries the most specific glyphs they show. The icon stack swaps the generic search glyph for the sites a web search read (from attachments, or the streamed results while live), and the settled phase header keeps the span's tool, MCP and site icons instead of a bare check; a failed phase keeps its warning glyph. Applied to the live row, the settled phase header and the tool group header. Source helpers move out of WebSearch into Content/sources.ts.

* fix: Preserve owned glyphs and outcomes across collapsed headers

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-20 19:01:30 -04:00
Danny Avila
1e0076376c
🪢 fix: Bind Preserved MCP API Keys to Server Configuration (#16136)
* fix: bind preserved MCP API keys to server configuration

* fix: surface MCP API key rebinding errors

* test: use typed MCP OAuth re-entry error
2026-09-20 12:33:20 -04:00
Danny Avila
f1bdc5640b
📟 feat: Render System Events as Distinct Turns (#16119) 2026-09-20 09:58:33 -04:00
Danny Avila
2551a057f0
💵 feat: Show Cost per Record, Step and Response in the Trace Ledger (#16120)
Some checks are pending
Codegraph E2E Votes / vote (full suite) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Client build recovery regression (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
* 💵 feat: Show Cost per Record, Step and Response in the Trace Ledger

* 💵 fix: Cost for Whole Responses Only, Hidden Records Included, and Said Aloud

* 💵 fix: Give the Oldest Loaded Response No Cost While Older Records Remain
2026-09-20 09:39:20 -04:00
Danny Avila
29ed0993a8
✂️ refactor: Name Tool Rounds From the Trace, and Match a Cut Response From Its End (#16113)
* ✂️ fix: Name Tool Rounds From the Trace, and Match a Cut Response From Its End

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

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

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

* 🧾 fix: Carry Where a Tool Round's Calls Came From
2026-09-20 08:24:33 -04:00
Danny Avila
a35745bf5f
💬 feat: Read a Model Call as a Conversation in the Trace Viewer (#16103) 2026-09-19 18:14:08 -04:00
Danny Avila
fa1e470b8d
🗣️ feat: Trace Viewer Roles, Agent Identity and Tool Rounds (#16098)
* 🗣️ feat: Trace Viewer Roles, Agent Identity and Tool Rounds

* 🧪 test: Stub the Trace Surface in the ChatView Subagent Spec
2026-09-19 16:43:42 -04:00
lia-by-librechat[bot]
9acf9f0ac8
🫗 fix: Roll Back Incomplete Skill Archive Imports (#16052)
* 🫗 fix: Roll Back Incomplete Skill Archive Imports

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

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

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

Addresses the first review round on the archive import rollback.

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

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

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

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

* fix: Ignore Late Skill Import Successes

* fix: Make Skill Import Rollback Retryable

* fix: Propagate Incomplete Skill Cleanup

* fix: Settle Rollback Blob Cleanup

* test: Type Partial Cleanup Fixture

* fix: Preserve Settled Skill Cleanup Steps

* fix: Export Skill Cleanup Step Type

* fix: Reconcile Partially Deleted Skills

* fix: Reconcile Skill Rollback Caches

* style: format cleanup reconciliation changes

* fix: complete skill rollback cleanup

* chore: leave generated locale catalogs unchanged

* fix: preserve synced skill blob cleanup

* test: type synced blob cleanup mock

* fix: Validate Archive Paths and Bound Rollback Cleanup

---------

Co-authored-by: Lia <lia@librechat.ai>
Co-authored-by: Danny Avila <danny@librechat.ai>
2026-09-19 12:41:30 -04:00
Marco Beretta
c821638e3d
🌓 refactor: Scrim OGDialog With the Overlay Theme Role (#16068)
* 🌓 refactor: Scrim OGDialog With the Overlay Theme Role

OGDialog scrimmed with a literal bg-black/80, so a theme that redefined
surface-overlay moved the Dialog and AlertDialog families and left every
OGDialog black. The scrim now paints bg-surface-overlay/80: the opacity
is unchanged, so the themes whose overlay resolves to black (dark, and
both high-contrast modes) render the same rgba as before, and the light
theme gets the gray scrim it defines, at 4.3:1 against the dialog it
frames.

Follow-up from the review of #15798, tracked as berry-13/LibreChat#14.

* 🧪 test: Carry the Scenario Theme Mode in the URL

The black-overlay scenario switched modes by writing `color-theme` and
reloading, but the init script that seeds the mode stays registered for
the life of the page and rewrote it on every load, so the high-contrast
iterations re-read the first mode and never matched their `<html>`
classes. The mode now rides in the URL and the init script copies
whatever the current navigation asks for.

* 🧪 test: Read the Scrim of the Frontmost Open Dialog

The scrim helpers resolved the dialog with `querySelector`, which takes
the first match in document order. Nothing in the suite is affected —
the settings modal is Headless UI and carries no `data-state`, so the
stacked scenario already measured the account confirmation — but a
scenario that opened an OGDialog from inside another one would have
silently read the outer dialog's scrim. The helpers now resolve the
frontmost open dialog by z-index and read its sibling scrim, and the
color and both sample points come back from one pass over the DOM.

* 🗂️ fix: Let the SharePoint Picker Take the App's Scrim

The picker rendered an OGDialogOverlay of its own beside the
OGDialogContent that portals one anyway. Both sat at depth 1, so both
resolved to z-index 130, and the primitive's overlay — mounted second —
painted over the picker's, so the lighter black it asked for never
reached the screen. The dialog is opaque, so it needs no backdrop of
its own: the extra overlay and its literal are gone and the picker
scrims with the theme's overlay role, exactly once, like every other
OGDialog.

* 🧪 test: Compare the Picker's Scrim to the Primitive's Own

The picker spec pinned the scrim's utility classes, which says nothing
a reader of the app would recognise and would break the next time the
primitive's opacity moves. It now renders a bare OGDialog beside it and
asserts the picker's single scrim is the same layer the app paints.
2026-09-19 08:58:30 -04:00
Danny Avila
038903abc0
📱 fix: Open Sign-In and External Links From iOS Home-Screen Apps (#16077)
* 📱 fix: Open Sign-In and External Links From iOS Home-Screen Apps

Sign-in prompts, the MCP OAuth Continue buttons and the account menu links opened with window.open and a noopener,noreferrer features string. WebKit treats a features string as a popup-window request, which an iOS home-screen app cannot open, and the chat sign-in also awaited its CSRF bind before opening, outside the tap. Links now open through a target=_blank link with rel=noopener noreferrer, and the chat prompt binds when it appears so the tap opens the provider synchronously.

* fix: Keep sign-in closed until its CSRF bind lands, and surface builder OAuth in its dialog

A tap while the chat prompt's bind was still in flight could open the provider before its CSRF cookie existed, and an Action callback has no fallback without that cookie; the button now stays disabled until the bind lands. The MCP builder card opened the authorization URL only after its initialize request, which iOS home-screen apps refuse and which left the card with no way to continue; it now shows the MCP OAuth dialog instead.

* fix: Let the tapped prompt own the CSRF binding, and show only the card's live OAuth flow

Live sign-in prompts share one CSRF cookie per callback path, so the last prompt to bind owned it; a tap now re-binds its own prompt right after opening the provider. The builder card kept a local copy of the authorization URL that outlived its flow and could reopen it on a later initialization; it now shows the manager's shared flow URL, cleared when the flow ends, and only for a flow the card itself started.
2026-09-19 08:09:25 -04:00
Danny Avila
79d1cbbafc
🪶 perf: Cut the Mount Cost of Finished Agent Messages (#16057)
* 🪶 perf: Render a Finished Message's Markdown in One Pass

Opening a conversation rendered every assistant text part per top-level
block: a full mdast parse just to find block boundaries, then one
ReactMarkdown pipeline, two providers and a layout effect per paragraph,
table and fence. The split only pays while a message streams, where it
keeps completed blocks memoized.

A message that was never streamed in this view now renders as one pipeline
and skips the boundary parse, keyed on its source so an in-place edit
remounts it with fresh code and artifact indices. A message that streamed
here keeps the per-block split after it finishes, so ending an answer never
remounts its blocks. The benchmark gains a finished-message mount case.

* 🪪 perf: Keep the Agents List From Re-Rendering Every Message Part

The author header a message hands its parts, restated after an inline
steer, was an element built from the resolved agent. The agents list
resolves after first paint, so that element changed identity, broke the
memo on ContentParts and re-rendered every part of the message, even
though the header only shows after a steer.

Both row renderers now hand the parts one constant header element that
reads the author from AuthorContext. An agent or assistant resolving
re-renders only the headers on screen, and the row's own icon and label
reuse the same memoized author.

* 🧷 fix: Move a Finished Message to Per-Block Rendering on Its First Change

A finished message kept its single pipeline keyed on its source, so every
change remounted all of it. An artifact editor saves the message every few
hundred milliseconds while the user types, and each save collapsed its
expanded Mermaid rows and reset its code blocks, where per-block rendering
had re-rendered only the artifact's block.

The single pipeline now serves a message only while it is exactly as it
mounted. Generating or any content change moves it to per-block rendering
for good, which remounts it once; later changes re-render only the blocks
they touch. The move happens as generation starts, so the fade baseline is
set on the blocks it mounts.

The splitter also sliced each top-level block after its indentation, which
decides how the block parses: an indented fence under a two-digit list item
kept its indentation in the code, and a two-space-indented list turned a note
into a code block. Blocks now keep their line's indentation.
2026-09-18 16:19:19 -04:00
Marco Beretta
5c72d4146e
📱 fix: Fit the Tool Library and Skills Pickers to Small Screens (#16067)
* 📱 fix: Fit the Tool Library and Skills Pickers to Small Screens

The Tool Library dialog assumed a viewport wide enough for its 224px
navigation rail: below `md` the rail took more than half of a 390px
screen and the card grid was squeezed into the remainder. The rail is
now `md`-only, and the same kind and view navigation renders as a
horizontally scrollable chip row under the search field.

Card and row actions were hover-only, so Configure, Favorite and Remove
were unreachable on a touch screen. They stay hidden until hover only
where hover exists (`@media (hover: hover)`), and are always visible
otherwise.

The Skills picker header put the create button, the filter field and the
view radio on one row, where the field collapsed to 50px beside a
`shrink-0` radio. The view radio and the create button now sit on the
title row, the create button flush right, and the filter field owns the
row below them.

The dialogs fill the viewport below `md` and switch `vh` to `dvh`, so
mobile browser chrome no longer cuts off the bottom of the panel.

* ♿ fix: Gate Hidden Tool Actions on Touch, Not on Hover

Hiding an action until hover has to ask whether a finger can reach it, and
`(hover: hover)` does not answer that: on a 2-in-1 it is true because it
describes the trackpad, while the touchscreen sits right next to it. Tool cards
and tool rows gated their Configure, Favorite and Remove controls on that query,
so a finger user of such a device saw no actions at all.

`packages/client/tailwind.preset.cjs` already carries `touch` for this exact
distinction, `(any-pointer: coarse)` rather than `(pointer: coarse)`. This adds
its inverse, `no-touch`, and gates the hidden state on it, so the hide applies
only where no coarse pointer exists at all and hover no longer takes part in the
decision.

* 📐 fix: Split the Skills Header Onto Two Rows Below md

The Skills header put the create button, the filter field and the view radio on
one row. The radio's segments are `whitespace-nowrap`, so the group never
narrows below 261px, and the field — `flex-1`, basis 0 — absorbed the shortfall
and measured 50px on a 390px screen.

Below md the radio and the create button now take the first line, the create
button flush right, and the field takes the second. From md the row is exactly
what it was: create button, field, category, radio. One DOM order serves both
through `order-*`, so the radio and the create button each exist once.

* 🧷 fix: Let the Skills View Radio Wrap Instead of Clipping

The three view segments carry `whitespace-nowrap` and `px-4`, so the group has a
hard 261px minimum in English and more in longer locales. On a 360px phone that
group and the 42px create button exceed the dialog, which is `overflow-hidden`,
and the trailing option becomes unreachable. The group now uses the primitive's
`wrap` variant and may shrink, so the segments flow onto a second row; at 390px
they still occupy one.

`wrap` reproduced `inset-y-1` by assuming the group had no vertical padding, so
turning it on for a `p-1` group shrank the moving indicator by 8px and left it
floating inside its segment. It now measures that padding from the first row's
offset, which leaves an unpadded group's geometry unchanged.

* 🧪 test: Cover the Small-Screen Tool Library and Skills Header

Ten mock-harness scenarios for the behaviour this branch changes, one per
acceptance scenario id, asserting rendered geometry and computed styles rather
than class strings.

The tool library file covers a phone viewport (the dialog fills it, the rail is
gone, the chip row filters, and no card crosses the viewport edge — the 744px
grid-column overflow), the action gate on all three pointer profiles (visible
with a coarse pointer, hover-gated with a mouse, revealed by keyboard focus),
the selected tool row, and the unchanged desktop rail.

The skills file covers the two-row header below md, the wrapped view radio at
320 and 280 CSS px with every option inside the dialog and the indicator on its
checked segment, and the single desktop row.

* 🧪 test: Pin the Scenario Contexts and Settle Their Geometry

The verifier runs every tagged test in three projects, one of which is a touch
phone, so the mouse scenarios asserted a mouse on a device that reports a coarse
pointer, and the desktop rail on a 412px screen. They now pin their own viewport
and pointer instead of inheriting the project.

Geometry and opacity were also read mid-animation: the dialog scales as it
opens, which put its left edge at 1.5px rather than 0, and the actions fade over
the shared motion duration, which caught keyboard focus at 0.84. Both now poll
for the resting value.

With nothing selected the skills section offers only the dashed empty-state
card, whose accessible name carries the hint line, so the exact-name locator for
Add skill never matched.

* 📏 fix: Keep the Tool Library Shell and Its Body the Same Height

Giving the shell an explicit `md:h-[88vh]` while the body kept its 840px ceiling
let the two disagree: on a viewport taller than about 955px the difference became
dead space below the catalog, 216px at 1280x1200, and below `md` the full-height
sheet left 293px on a 744x1133 tablet.

The body carries the height from `md` again, the way it did before this change,
so the shell wraps it. Below `md` the shell stays the full-bleed sheet and the
body is capped to the same `100dvh`, which it needs because its `h-full`
resolves against a grid area sized to the whole catalog.

Measured shell and body heights now agree exactly: 840 at 1280x1200, 757 at
1280x860, 1133 at 744x1133 and 844 at 390x844, with the catalog still scrolling
inside its own container.

* 🎯 fix: Keep the Search Field Clear of the Dialog Close Button

`md:px-6` on the search row is a responsive variant, so it is emitted after the
base utilities and reset the `pr-12` that reserves room for the close button:
on desktop the row's right padding dropped from 48px to 24px and the field ran
16px underneath the button. It now sets only the left side at `md`.

Measured gap between the field's right edge and the button: 8px at 1280x860 and
at 390x844, with no vertical overlap. Asserted inside the phone-viewport and
desktop-rail scenarios rather than as a new id, since it is the same surface.

* ⌨️ fix: Read the Skills Header in Tab Order and Keep the Chip Row Draggable

Two defects with the same shape: a control that the eye can reach and the
keyboard or the mouse cannot.

The Skills header used `order-*` to serve both layouts from one DOM order, which
left tab order disagreeing with the visual order from `md`: focus went from the
rightmost radio group back to the create button and then into the middle. The
breakpoint now selects the DOM order instead, the way the marketplace dialog
already selects its rail, so each layout reads in the order it renders. Every
control is still built once, so there is one radio group and one create button at
any width.

The mobile chip row hid its scrollbar unconditionally. A narrow desktop window is
below `md` as well, and there a wheel scrolls the page rather than the row, so
Made by you and Favorites could not be reached with a mouse at all. The hiding is
now gated on `touch`, the same `(any-pointer: coarse)` query the rest of this
branch uses.

Measured: desktop DOM order create, field, radio and mobile radio, create, field,
each matching its layout; `scrollbar-width` resolves to `auto` in a 520px mouse
window whose row overflows, and to `none` on a touch phone.

* 👆 fix: Give the Touch Layout Touch Geometry

Two findings with one cause: the coarse-pointer layout inherited the mouse
layout's geometry after this branch changed what it shows and in what order.

Card actions no longer fade out where a finger can reach them, but they are
absolutely positioned over the card's content, so on touch they covered the last
line of a three-line description for as long as the card was on screen - an
overlap that used to be transient. The card now reserves a strip for them there,
`touch:h-36` with `touch:pb-9` on the content, which keeps all three lines.

The chip row is that layout's primary navigation and exists only where a finger
is what reaches it, yet its chips were about 30px tall and its create control
32px, while the repository already exposes the 44px `theme-control-touch` size
for this. Both now carry that floor through `touch:`, and the mouse layout keeps
its compact sizing.

Measured on a 390x844 touch profile: all eight chips 44px, the card 144px, and
the description's box clear of the action cluster. Both are asserted in the
phone-viewport and touch-action scenarios.
2026-09-18 17:29:39 +02:00
Marco Beretta
9633edcb88
🗣️ fix: Keep Provider Error Text on Unclassified Agent Failures (#16034)
* 🗣️ fix: Keep Provider Error Text on Unclassified Agent Failures

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

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

* fix: Harden Provider Error Detail Retention

---------

Co-authored-by: Danny Avila <danny@librechat.ai>
2026-09-16 21:32:41 -04:00
Danny Avila
c153c4057f
🪜 feat: Trace Viewer Steps, Sequence Scale and Previews (#16009)
* 🪜 feat: Trace Viewer Steps, Sequence Scale and Previews

* 🪜 fix: split tool-only rounds by run step; preview only a step's own roots

* 🪜 fix: keep windows and previews on the records they describe across pages, modes and failed wrappers

* 🪜 fix: keep step folds and previews honest across page boundaries and failed turns

* 🪜 fix: causal tie-breaks, final-only previews, span-shaped title runs, and truncating long names

* 🪜 fix: index previews in one pass, split agent handoffs, withhold parallel lanes

* 🪜 fix: skip the holes a streaming message leaves in its content

* 🪜 fix: reserve a round for compaction summaries; keep parallel-lane tools with their own model call

* 🪜 fix: record a handoff that starts with reasoning; look lanes up in a map

* 🪜 fix: per-lane leading steps, wrappers for turns without work yet, no final alignment for runs that ended early

* 🪜 fix: append to a step's per-tool bucket instead of copying it per call

* fix: Preserve Trace Preview Alignment Across Run Boundaries

* perf: Cache Trace Ancestors and Lane Branches
2026-09-16 15:22:40 -04:00
lia-by-librechat[bot]
cacc148795
🔅 style: Theme the Tool Approval Decision Fields (#16014)
Co-authored-by: Lia <lia@librechat.ai>
2026-09-16 11:29:52 -04:00
Danny Avila
299dbc6075
📖 Load Repository Instructions for Attached Workspaces (#16008)
* Load authorized workspace repository instructions into agent context

* Unify repository instruction loading across agent ingresses

* Await cancellation regression assertion directly

* Annotate the shared instruction loader for declaration builds

* Expose repository read budget and inject the host-owned cache
2026-09-16 09:00:35 -04:00
lia-by-librechat[bot]
0da30ed479
👆 style: Thumb-Sized Send Button on Touch Devices (#15979)
* 👆 fix: Thumb-Sized Send Button on Touch Devices

* fix: floor the submit target wherever touch is reachable, not only on a coarse primary pointer

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-15 23:39:17 -04:00
lia-by-librechat[bot]
c80f5a7090
🪃 fix: Remember the Last Code Approval Mode (#15973)
* 🪃 fix: Remember the Last Code Approval Mode

The code approval dropdown reopened on "Ask before changes" after every new
chat and reload. `useCodeApprovalMode` derived its selection from
`conversation.codeApprovalMode ?? 'ask'`, and a new conversation never carries
that field: `buildDefaultConvo` runs the last setup through `parseConvo`, whose
agents schema does not pick `codeApprovalMode`, so the pick was dropped.

The menu now records each pick in a localStorage-backed Jotai atom, and the
hook seeds its default from it when the conversation carries no mode of its
own. The remembered value is a preference and not a grant: it passes the same
policy gate as a stored mode, so anything current policy no longer allows
falls back to `ask`, and sign-in/sign-out clears it so a shared browser does
not hand the next account a permissive default.

* 🎨 style: Format the Code Approval Preference Files

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-15 14:05:10 -04:00
Danny Avila
942c9598c0
🧼 fix: Render Agent Description HTML Safely (#15951)
* fix: render agent descriptions consistently

* fix: harden marketplace descriptions

* fix: preserve rich description blocks

* fix: preserve angle-bracket description text
2026-09-14 22:05:51 -04:00
Danny Avila
96cb5e757d
🫴 fix: Preserve Queued Follow-Ups Through Handoff (#15942)
* ⏱️ feat: Reveal Queued Follow-Up At Run Completion

In an agent conversation the server admits a queued follow-up on its own clock, and the client learned of that successor only through the receipt poll, the active-job poll and a resume attach, so the user's words appeared as the latest turn a second or more after the reply above them ended.

The queued follow-up is now drawn as the newest user turn the moment its predecessor completes cleanly, with its chip reduced to a remove action until the server admits it. The drawn turn is presentation intent only: it never enters the message cache, anchors no send, edit, fork or rerun, and shows only while the completed response it follows is the thread's tail. The intent ends once anything parents on that response, on a cancelled, dead or indeterminate receipt, or on the user's own removal. The composer queues behind it and the completed response offers no rerun while it stands.

The receipt poll also stays alive while the client holds a server-owned row the projection has not settled, so a successor that starts and finishes inside one active-job poll gap is no longer noticed only on the next focus.

* ⏱️ fix: Re-select the Reveal When Its Head Settles and Stop Polling Expired Rows

A revealed head that is cancelled or dies before admission leaves the server-owned queue non-empty and its terminal evidence outside the settled receipts, so nothing re-ran the drain for the row the backend moves on to; the drain now subscribes to the admissible head and the reveal itself. An uncertain row whose reconciliation window has expired is held for manual recovery only and no longer keeps the receipt poll alive.

* ⏱️ fix: Route Dictated Submissions Through the Composer's During-Run Path

A transcription completing while a queued follow-up was about to start called the send path directly and could race the turn the server already owed. The form's routing (answer mode, then steer or queue during a run or a pending reveal, then an ordinary send) now lives in one function that typed and dictated submissions share; a refused during-run submit keeps the text in the composer.

* fix: preserve queued turn ownership across admission handoff

* fix: preserve queued handoff lineage and ownership through recovery

* fix: delegate draft consumption and preserve refused prompts
2026-09-14 21:04:08 -04:00
Danny Avila
5e2a2c65a3
📖 fix: Preview Extracted Upload Text (#15946)
* fix: preview extracted upload text

* fix: preserve extracted-text preview metadata

* fix: complete extracted preview recovery paths

* fix: retain preview metadata across attachment recovery

* fix: preserve preview metadata across legacy steering

* fix: hydrate legacy steer preview metadata

* fix: hydrate reconnect steer metadata

* fix: preserve text preview metadata in resumed shares

* fix: hydrate legacy preview metadata safely

* fix: close preview lifecycle and recovery gaps

* fix: preserve preview ownership and wire metadata
2026-09-14 20:58:04 -04:00
Danny Avila
d9c5d1c8d6
🔓 fix: Keep Code Approval Mode Selectable Mid-Run (#15938)
* 🔓 fix: Keep Code Approval Mode Selectable Mid-Run

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

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

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

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

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

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

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

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

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

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

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

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

A conversation that has its id but no detail record yet now gets one from the live conversation when a mode is picked, the same key the resumable transport seeds optimistically, so recovery and navigation find the pick. A chat with no id yet still keeps the pick in conversation state alone.
2026-09-14 18:36:49 -04:00
Danny Avila
bc12fad6f1
🕹️ feat: Run Declared Project Actions on Attached Workers (#15943)
* feat: use declared attached project actions

* Complete named action definitions and approval previews

* Sort named environment imports

* Sort native environment fixture imports
2026-09-14 18:35:33 -04:00
Danny Avila
2f8bc3dfcd
🎞️ fix: Deliver Opted-In Custom Endpoint Media Safely (#15937)
* feat: send video/audio to custom endpoints that opt in via supportedMimeTypes

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

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

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

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

* fix: canonicalize input_audio format from MIME type

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

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

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

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

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

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

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

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

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

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

* fix: reject unsupported provider audio during upload

---------

Co-authored-by: Renato Garita Figueiredo <renato.garitafigueiredo@uni-osnabrueck.de>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-14 16:38:51 -04:00
Marco Beretta
16faadb998
🪧 feat: Unify Artifact Triggers as Tool Rows (#15915)
* 🪧 feat: Unify Artifact Triggers as Tool Rows

Every chat-side artifact trigger — code-execution output, a model-authored
`:::artifact` block, and a mermaid diagram — now renders through one
`ArtifactRow` that sits on the tool-row axis instead of three card variants
in a wrapped chip strip. The row carries the file type twice: the language's
brand glyph where one exists, and a format badge for titles that are not
filenames. `kind.rendersPreview` tints the glyph and folds the same fact into
the accessible name, so the row says whether opening it yields a rendered view
or source to read.

The mermaid panel routes every download through its export menu — SVG, PNG and
the diagram source — rather than parking a second, unlabelled button beside it.
The menu turns the pressed format into its own loading row, defers the
synchronous SVG export by a macrotask so the spinner paints before the frame
blocks, and no longer disappears on the code tab. A mermaid download keeps its
real filename: its content *is* the stored `.mmd`, so it is not suffixed
`.preview`.

`useArtifactDownload` holds the original-file vs. edited-content decision that
both the generic download button and the mermaid menu need.

* 🩹 fix: Save the Stored Artifact File, Not Its Cached Text

The panel serialized a mermaid diagram from `artifact.content`, which is the
backend cache `extractUtf8` truncates at 512 KB, so "Download source" saved a
corrupt `.mmd` for any larger stored diagram. An unedited mermaid artifact now
takes the same original-file route as every other text-backed artifact,
`handleDownload` reports whether bytes were actually delivered, and the export
menu turns a failed delivery into its failure status and toast instead of
"Diagram download started.".

A `text/plain` row announced "Opens as source" while the panel opened it on the
rendered markdown preview; it now announces the preview. A pending preview
placeholder keeps the row slot it arrived in rather than sinking to the end of
the artifact group and jumping up once it resolves.

* 🧪 test: Exercise Artifact Rows and Mermaid Exports End to End

Seven acceptance scenarios in the mock harness cover what the unit suites
cannot: that a message which writes five artifacts shows five trigger rows on
one axis, that a row's accessible name matches what the panel actually does
with the artifact (rendered preview vs. source, including `text/plain`), that
the mermaid export menu offers SVG, PNG and the diagram source on both the
preview and the code tab, that "Download source" delivers the stored file and
announces a failure when the stored file is unreachable, and that a pending
preview placeholder keeps the row slot it arrived in.

Each test carries its `@scenario:<id>` tag and is self-contained: fixtures come
from the existing fake-model markers, Mongo seed helpers, or page-scoped route
stubs, and every seeded conversation is deleted again.

* 🏷️ fix: Name a Mermaid Blob After the Preview It Is

A share with snapshots disabled strips the download route from a
code-execution `.mmd` but keeps the cached `attachment.text`, and that text is
what `extractUtf8` truncated at 512 KB. With no route to the stored file the
panel can only serialize that cached copy, and the mermaid exception in
`getArtifactDownloadFilename` handed those partial bytes over as `flow.mmd` —
the stored file's own name, from a menu item labelled "Download source".

Mermaid now follows every other file-backed artifact: a serialized blob is named
`flow.preview.mmd`, and only the original-file route produces `flow.mmd`. A
model-authored diagram has no stored file to be a preview of, so it keeps its
own name.

* 🎹 test: Reach the Export Menu's First Item From Either Start

`supports keyboard export` opened the menu with Enter and pressed ArrowDown
once, assuming no item was active yet. CI observed the opposite — the first item
already active — so the single ArrowDown walked past SVG onto PNG and the test
failed there while passing locally (it failed the same way on the previous head).
`Home` lands on the first item from either starting point.

* 🔧 test: Fix the Fixtures Three Artifact Scenarios Ran On

The first verification run failed five of the seven scenarios on fixture defects,
not on product behavior:

- `artifact-trigger-rows` drove a fake-model marker
  (`E2E_ARTIFACT_SHOWCASE_REPLY`) that does not exist, so the reply carried no
  artifacts and no trigger rows. Both tests now seed the assistant message text
  through Mongo, the way the passing plain-text scenario does.
- `mermaid-source-download` waited for an `ArtifactRow` that a code-execution
  `.mmd` never renders — it renders an inline diagram whose trigger is "Open as
  artifact" — and its cached diagram embedded the literal truncation marker,
  which mermaid cannot parse, so the diagram failed to render at all. The cached
  copy is now a valid shorter diagram and the stored file keeps the sentinel that
  proves which bytes were saved.
- `pending-artifact-row-slot` gave the tool call's id to only one of its two
  attachments. Attachments reach a renderer through `mapAttachments` keyed by
  tool-call id, so the other one rendered nowhere; both now carry the same id and
  land in the one `artifact-row-group` whose ordering the scenario is about.

* 🪜 test: Count Four Authored Rows, Then the Mermaid One\n\nA mermaid fence is not a trigger row while it is inline: it renders the diagram\nwith an "Open as artifact" button and only becomes an ArtifactRow once opened.\nThe axis scenario now asserts the four authored artifacts stack as rows, then\nopens the diagram and asserts its row joins the same column.

* 📐 test: Measure the Row Axis in One Layout State\n\nOpening an artifact narrows the chat column, so comparing the mermaid row's x\nagainst a box measured before the panel opened reported an 8px offset that no\nuser sees. All five rows are now measured after the open, and the panel is\nlocated at page level, where it renders \u2014 not inside the message list.

* 🧩 fix: Give the Mermaid Row Its Own Filename and Download

A code-execution `.mmd` arrives wrapped in a header that prints the filename and
a download button, and that header stayed put when the diagram collapsed into
its trigger row — so the chat showed `flow.mmd` twice and left the download
outside the row that every other file-backed artifact keeps it in.

`Mermaid` now takes the file's download action and hands it to `ArtifactRow`,
and reports whether it is currently rendered as that row; `ToolMermaidArtifact`
drops its header while the row owns both. Opening and closing the diagram
therefore moves the filename and the download between exactly one place each.

* 🔖 test: Match a File-Backed Diagram's Own Trigger Id\n\nThe row ownership scenario looked for a \ trigger id, which\nonly a model-authored fence gets; a code-execution diagram's row carries the\nattachment's artifact id.

* 📱 test: Dismiss the Artifact Sheet Before Using the Row\n\nOn a phone the artifact panel opens as a sheet over the message list, so the\nrow's download button sits behind it. The scenario now closes the panel with its\nown control first, which also shows the trigger stays a row after closing.

* 🔔 fix: Raise One Toast per Failed Source Download\n\n\ already toasts "Error downloading file" before reporting a\nfailed delivery, and the export menu then raised its own — two notifications for\none press, on every ordinary 4xx/5xx, because React Query's refetch resolves\nwith an error result rather than throwing.\n\nA reported failure now only updates the menu's live region, which keeps the\nexport's own phrase for a screen reader; a thrown task still raises the toast,\nsince nothing else has spoken for it.

* 🔕 fix: Let the Download Layer Own Every Failure It Reports

The previous round split the failure notification by cause and left a hole in
the other direction: `useAttachmentLink` toasted only its empty-response
branch, so a thrown fetch — and the artifact hook's own blob failure — returned
`false` with nobody having spoken, and the export menu's live-region-only
announcement reached no sighted user.

One rule instead of two branches: whichever layer returns `false` has already
told the user. `useAttachmentLink` toasts its thrown branch as well, and
`useArtifactDownload` toasts when the blob path throws or there is nothing to
serialize. The mermaid export menu keeps announcing the export's own phrase in
its live region, so one press still raises exactly one toast — this time for
every failure, not just the polite ones.

* 🪄 fix: Hold the Row Slot and the Frame Before Blocking Work

Two fixes on the same theme — a row or a control that moves at exactly the
moment it is meant to stay put.

Writing salience-sorted resolved entries back into their arrival slots still
moved a pending row once it resolved: the placeholder joined the sort and could
pass an empty artifact that had been sitting above it. `attachmentSalience`
reads only `bytes`, which resolution does not change, so one sort over the whole
panel row — pending entries included — is stable across the transition and is
also less code.

The export deferral used `setTimeout(…, 0)`, which only moves the blocking SVG
work to another task; the timer can still run before the browser paints the
loading row, which is the whole point of deferring it. It now waits for an
animation frame and then a task, falling back to a timer when the tab is hidden
and serves no frames.

* 🏷️ fix: Keep the Recovered Filename on the Mermaid Row\n\n\ turns a sandbox-generated \ back into\n\, but that name lived only in the wrapper header. The moment the\ndiagram collapsed into its trigger row, the row title and its download button's\naccessible name fell back to \ — the internal filename.\n\n\ now takes the caller's display name for the row, and\n\ passes the one it already computed.

* 🗂️ fix: Open Each Artifact on the Tab Its Row Promises

A code-only artifact forces the panel onto Code, and that constraint was written
back into the panel's single `activeTab`. The next HTML, Markdown, plain-text,
React or diagram artifact then opened on Code while its trigger row announced
"Opens as a rendered preview" — the row was telling the truth about the artifact
and a lie about the click.

The constrained tab no longer leaks: the panel resets to the preview tab when a
different, unconstrained artifact is opened, so a manual Code choice lasts as
long as that artifact stays open and never follows the user to the next one.
`displayedTab` already derived the forced tab for rendering, so nothing else
depended on the write-back.
2026-09-14 15:08:07 -04:00
Marco Beretta
f077e8c967
🗯️ fix: Give Failed Turns Actionable Guidance (#15896)
* 🧯 refactor: State Failed Turns in Copy a Reader Can Act On

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

Co-authored-by: Danny Avila <danny@librechat.ai>
2026-09-14 10:37:22 -04:00
Marco Beretta
d8c953be30
📜 style: Scroll the Sidebar as One Surface (#15914)
* 📜 style: Scroll the Sidebar as One Surface

Projects, Pinned and the chats list each owned a scroll pane, so only the
chats list scrolled while the sections above it stayed pinned. The sidebar
now has one scroll viewport holding all three: the virtualized chats list
renders at its natural height and is windowed by that viewport instead of
scrolling itself.

`useOuterScrollWindow` translates the viewport's scroll position into the
list's coordinates. It re-measures on scroll and observes both the viewport
and the content wrapper, because a section collapsing above the list moves
the list without resizing either the viewport or the list.

* 🧪 test: Cover the Sidebar's Single Scroll Surface

Four scenarios in the mock harness: the whole sidebar rides one wheel
gesture, older chats keep loading as it reaches its end, collapsing a
section above the chats leaves the visible rows painted, and a long
pinned list scrolls with the sidebar instead of inside its own box.

The chat list grid no longer matches its container's height — it renders
at the height of the rows it holds — so the width-tracking spec measures
width alone and seeds the rows it measures.

* 🪟 fix: Keep the Windowed List Honest Without ResizeObserver

A section collapsing above the chats list moves it without resizing the
viewport or the list and without a scroll event. Where ResizeObserver is
missing, the fallback only listened for window resizes, so the list kept
windowing against the old offset and could paint the wrong rows. It now
watches the content wrapper the same way the observer does: its mutations
and the bubbling transitionend of its height tween.

The hook gets its own spec — offset translation, clamping at the top,
frame coalescing, the collapse re-measure, the fallback trigger and
listener cleanup — and the scenario specs reach the drawer on emulated
touch devices, where the header's opener appears only once the chat has
rendered and a wheel gesture is not what a person produces.

* 👁️ fix: Window the Chats List on What the Reader Can See

The list was handed the whole sidebar's height as its window, so with a
screenful of projects or pins above it, react-virtualized counted a
viewport of chat rows as rendered at the top of the list and the
eight-row pagination threshold was crossed before a single chat had been
exposed — a second conversations request nobody had asked for, on the
load path the Lighthouse lane guards. The window is now the slice of the
list the viewport actually shows: zero while it is below the fold, the
viewport's height once it fills it.

Searching also kept the shared surface's scroll position while replacing
what it held — Projects and Pinned leave and the chats become results —
so results long enough to escape the browser's clamp opened partway
down. The surface returns to the top whenever it swaps contents.

* 🧪 test: Seed the Pagination Scenario's Pins Out of the First Page

* 🧪 test: Claim the Settled Layout in the Pagination Scenario

* 🩹 fix: Keep a Pixel of Window So an Unseen List Can Be Reached

A list handed a zero window renders nothing, and react-virtualized only emits its inner container when it has children, so the list collapsed to no height and the surface had nothing to scroll toward: the chats below a screenful of pins could never be reached. The window keeps a single pixel, which renders the first row and restores the list's own height without claiming a screenful is on display.

* 🧪 test: Scroll Until the Chats List Answers

* 🚦 fix: Ask for Another Page Only Once the Chats Are in View

A list below the fold still renders its first row — that pixel of window
is what gives it a height to be scrolled to — and on a page whose chats
are nearly all pinned, that single row already sits inside the eight-row
threshold, so the list asked for another page before anyone had looked at
it. Reaching the end of what is rendered now counts only while the list
is on screen; the hook reports that separately from its height, and a
page holding no chats at all is still drained by the all-pin effect.

* 🔎 fix: Ask the Layout Whether the Chats Are in View

Visibility was a value sampled on a frame, and a commit that swaps what
the sidebar holds — leaving a search restores the sections and the
unfiltered page together — moves the list before any observer runs, so
rows reported during that commit were judged against the layout before
it. The hook now answers from the layout as it stands when asked, and
the pagination gate asks.
2026-09-14 16:06:59 +02:00
Danny Avila
4216de41c2
🚛 fix: Move Sealed Chats to New Code Environments (#15902)
* 🧭 fix: Let a Sealed Chat Follow Its Agent to a New Machine

A conversation's code-environment decision is sealed on its first turn, but the
environment an agent uses stays editable. Pointing an agent at a different
attached machine left every chat sealed to the old one with no valid move: the
client showed an unusable workspace chooser, and any other selection was
rejected by the server as locked. Forking copied the stale seal.

The owner can now move such a chat explicitly. The composer names the machine
the chat used and the one its agent uses now, and moving it goes through an
owner-scoped endpoint that compare-and-swaps the persisted decision after
validating the new workspace against the live worker. A move never switches the
workspace of an environment the decision already covers, never upgrades a chat
that continues without an attached environment, and is refused while a
generation is in flight.

A saved chat also no longer auto-selects a sole workspace for an environment its
decision never covered, which submitted a selection the server always rejected.

* fix: Hold Moves Through Terminal Saves and Move Every Target at Once

A terminal claim marks a generation complete before its response save lands,
and that save still writes the decision the run started with, so a move is now
refused until terminalPersistencePending clears.

The API advertises codeEnvironmentMoveVersion, and the client offers a move only
when it is present, so a new client never exposes an endpoint an older API lacks.

The move menu picks one workspace per new environment, with a sole workspace
preselected, and a single confirm sends the complete target set in one request,
so a partial move can no longer leave a half-migrated decision. A new machine
that advertises no workspace shows its unavailable state instead of an empty
section, and the confirm stays disabled.

* fix: Keep Runs From Rewriting Moved Decisions and Gate Moves by Policy

Every agent turn used to persist the decision it started with, so a run from any
ingress that settled after a move could write the old decision back: the chat
controller reads the conversation before its generation job exists, and
Responses API runs never enroll one. Runs now persist a decision only for a
conversation that does not store one yet, and a legacy row records only the mode
it inferred, so no admission or persistence order can revert a move.

Moves are now an operator setting, statefulCodeSessions.conversationMoves.enabled,
off by default. The API advertises codeEnvironmentMoveVersion and accepts moves
only where the effective policy enables them.

A saved chat carrying attached selections no longer auto-selects a sole workspace
even when selection-less decisions are not advertised, because the server seals
those selections either way.

* fix: Fence Moves Across Remote Runs and Let Moves Drop Unused Machines

A Responses API run is keyed by its response id, so the conversation stream
alone could not show it still working on a chat. A move is now refused while any
generation that can still act for the conversation exists, using the same
conversation-scoped enumeration conversation deletion drains.

A move now validates every workspace it persists, not only the added ones, so a
successful move never hands back a decision whose kept workspace is gone.

A chat sealed to machines its agents no longer all use could not be sent or
moved: the client trimmed the unused selection and the server rejected the
trimmed set as locked. A saved chat now treats that seal as unresolvable, offers
a move that drops the unused machine, and the server accepts drop-only moves.

* fix: Own the Decision Fallback in TypeScript and Settle Move Caches

The fields a run may persist when it never resolved a decision were chosen by a
branch in AgentClient; resolvePersistableCodeEnvironmentDecision now owns that
fallback too, under the same never-overwrite rule, and the CJS method only wires
the request into it.

Workspace choices made in the move menu belong to the chat they were made in, so
another relocatable chat targeting the same machine starts undecided.

A successful move cancels conversation, pinned, and list reads already in flight
before writing the moved decision, so a response from before the move cannot
restore the replaced decision in the cache.
2026-09-14 00:58:08 -04:00
Danny Avila
c2f3d0c07b
🎨 style: Color Image Tool Labels With the Activity Rows' Secondary Role (#15900)
The image generation and edit row set no text color, so its label inherited
`text-text-primary` from the message container. Every sibling row renders its
label in `text-text-secondary`, including this row's own icon. A finished,
failed or cancelled image label, and a running one under reduced motion where
the shimmer paints `currentcolor`, read brighter than the rows around it.

The row container now carries `text-text-secondary`, the way the generic tool
row's wrapper and the tool group header set their color.
2026-09-13 23:13:13 -04:00
Danny Avila
f3991f2949
🔡 style: Size Image Tool Labels Like Every Other Activity Row (#15898)
The image generation and edit label carried `progress-text-content` beside
`tool-status-text`. The former sets `font-size: inherit` and is declared later
in style.css, so it won the cascade. Outside the `progress-text-wrapper` that
class is meant for, the label inherited the page's 16px/24px instead of the
row role's 0.9x of the chat font size. It rendered larger than its sibling rows
at the default size and ignored the font-size preference at every other size.
2026-09-13 23:12:43 -04:00
Marco Beretta
e95e696d70
🧾 fix: Count the Tool Results a Tool-Limit Stop Retains (#15893)
Some checks are pending
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Codegraph E2E Votes / vote (full suite) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Client build recovery regression (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
Docker Dev Images Build / publish (push) Waiting to run
Sync Helm Chart Tags / Ignore non-main push (push) Waiting to run
Sync Helm Chart Tags / Sync chart tags (push) Waiting to run
* 🧾 fix: Count the Tool Results a Tool-Limit Stop Retains

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

Co-authored-by: Danny Avila <danny@librechat.ai>
2026-09-13 22:20:25 -04:00
Marco Beretta
8e6e6f062d
🪧 fix: Emit the Configured-Footer Answer With the HTML Shell (#15886)
* 🪧 fix: Emit the Configured-Footer Answer With the HTML Shell

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

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

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

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

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

The shell answers from the deployment's own configuration, which a per-tenant,
role or user override of `interface.privacyPolicy` or `termsOfService` can
disagree with — `/api/config` resolves the caller's and the client prefers it.
That contract was overstated in three comments ("a deployment-lifetime fact",
"the same one the config will give"); they now say what the answer is and what
resolves the rest. Two scenarios cover the disagreement end to end: a document
served without the answer, and a policy link only this caller's config carries.
2026-09-13 21:53:54 -04:00
Marco Beretta
91e00bbe6e
🧷 fix: Mark a Failed Compaction So Its Rerun Controls Stay Withheld (#15883)
* 🧷 fix: Mark a Failed Compaction So Its Rerun Controls Stay Withheld

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

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

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

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

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

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

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

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

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

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

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

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

The empty-summarizer scenarios switch the shared fixture summarizer to blank
output, so the reset moves to `afterEach` and runs even when the helper throws
before its caller's `finally`.
2026-09-13 21:53:29 -04:00
Marco Beretta
c640d80539
🪟 fix: Opaque Header Controls Over the Chat Gradient (#15894)
* 🪟 fix: Opaque Header Controls Over the Chat Gradient

The mobile sidebar toggle let the conversation show through itself: the chat
header is a gradient fading to transparent with messages scrolling under it,
and the shared `header-action` variant carried `bg-transparent` while every
other control in that row sits on `bg-presentation`.

* 🔒 fix: Keep an Explicit Button Shape Over the Header Compound

A compound variant is emitted after the `shape` recipe, so the `header-action`
+ `size: 'sm'` corner repair outranked a caller that asked for
`shape="theme"` or `shape="round"` — `cn` kept the later `rounded-xl` and
dropped the requested radius. Gate it on `shape: 'unset'`, the way the
`subtle` compound already is, so it only repairs the default geometry.

Adds the mobile header row's acceptance scenarios to the mock harness: the
toggle's interior does not change as the conversation scrolls under it, its
fill and corner match the new-chat and overflow controls beside it, and the
drawer's close toggle is the same control by fill, corner and tap target.
All three fail against the previous transparent fill.

* 🧪 test: Rewind the Header Scenario Before Scrolling It

The scroll scenario sampled the toggle from wherever a freshly opened
conversation happened to land. That is the app's business — the newest message
with auto-scroll on, the top of a seeded transcript without it — and a landed
end leaves a wheel delta in that direction nothing to move, which would fail the
"the conversation did not move" guard rather than measure the fill.

Rewind to the top first, then bring the transcript down under the header, so the
wheel always has a known distance to travel. The guard stays: a run where the
conversation does not move still fails instead of passing vacuously.

* 🧪 test: Read the Header Toggles With the Pointer Off Them

`click()` leaves the pointer on the opener's coordinates, and the drawer slides
its own toggle onto those same coordinates, so one of the pair could be reading
`hover:bg-surface-active-alt` while the other sat on `bg-presentation` — an
equality that depended on when the 300ms slide settled.

Move the pointer off both controls, wait for the drawer, and assert the pointer
really is clear: each surface now reports its own `:hover` state, so a run that
measures a hovered control fails on that rather than on the colour.
2026-09-14 00:58:37 +02:00
Marco Beretta
566e0a8266
🪢 fix: Withhold the Editor's Rerun Where No User Turn Can Be Replayed (#15887)
A rerun replays the edited message's parent as the turn's user message, so a
response with no user turn behind it has nothing to submit. The editors gated the
action on `parent?.isCreatedByUser !== false`, which treats an unresolved parent as
replayable: a reply the import left at the root kept an enabled Rerun, bound to
Ctrl/Cmd+Enter, that both handlers then refused with no feedback.

Both editors now resolve that parent through `findRerunParent`, at render and again
at submit, so the button and the submission cannot disagree. Where the action is
withheld the footer's existing status slot says why instead of going blank. Save,
Cancel and Ctrl/Cmd+S are untouched.

The hover row carried the same shape: `parentIsUserMessage` was undefined for an
absent parent, leaving Regenerate and Continue enabled while `regenerate` only
logged. It now separates a missing thread — a search row, which still withholds
nothing — from a parent that is not in the thread.
2026-09-13 12:54:01 -04:00
aruj0
d6f8b2e92a
🏷️ fix: Keep a Configured Sender Label From Revealing the Model on Hover (#15489)
A conversation whose sender is a label someone configured shows that label as the
header's name. Since #14851 the header's hover crossfade swaps the raw `message.model`
back in, and the sr-only "Model:" text announces it regardless of hover.

Ask the message, not the settings. `resolveSender` writes an agent's name, then the
`getEphemeralSender` chain — a preset's `modelLabel`, a model spec's `label`, an
endpoint's `modelDisplayLabel` — and falls back to `getResponseSender` only when none
is set, so the persisted `sender` is the one thing that records which it was. The new
`isConfiguredSender` compares it against what `getResponseSender` would produce for the
same endpoint and model: equal means the header is showing a model-derived name and the
hover may reveal the model, different means it is standing in for one.

That settles three things a settings lookup cannot. Labels that live in config a caller
may not hold — a spec that sets `label` and leaves `preset.modelLabel` unset is the
ordinary shape, and the share publisher cannot read the spec list. Labels an endpoint
ignores — Anthropic keeps writing `Claude` whatever `chatGptLabel` says, and it matches
here without anything enumerating which endpoints honour what. And labels changed since
the message was written — the row still shows the sender it was written under, so
clearing a label must not start revealing the model behind the rows that carry it.

Equality is the test, so the ordinary way to be wrong is a stored name that no longer
matches what the current heuristics produce, which withholds a model rather than
revealing one. Three cases are decided before any comparison: a user turn is headed by
its author and has no model to withhold; agents and assistants are named by whoever
authored them, so the header shows that name whether or not the response stored a
sender; and an endpoint that cannot be named — an older message saved without one —
says nothing either way, where reading silence as a label would withhold the model from
every unlabelled row it reached.

`getHeaderHoverLabel` takes that answer and produces no hover label when it is true, so
the header renders the plain label with no swap and no sr-only model text. Without a
configured sender the behaviour is unchanged.

- Chat rows: `useMessageActions` and `useMessageHelpers` decide once per row from the
  message they already hold, so MessageRender, MessageParts and ContentRender consume it
  like any other derived display state.
- Share links: the view has no conversation in scope, so `getSharedMessages` reads the
  answer off the very messages it is returning, collected in the pass `anonymizeMessages`
  already makes rather than a second traversal. Only messages the link actually publishes
  have a say, and nothing about the link is re-derived from the conversation afterwards.
  `ShareContext` — already the carrier for share-scoped values such as `shareId` — hands
  it to the header.

The flag travels rather than the label text: each surface only needs the decision, and
the text is already carried by `message.sender`, which the share content preflight
inspects.

Search rows are left alone. `GET /api/messages?search` returns each hit's stored sender
and endpoint but overwrites `model` with the conversation's current one, so a row cannot
be classified from what it carries without changing what that payload means.
2026-09-13 11:57:12 -04:00
Danny Avila
9cf33cc8be
🧿 fix: Bind Login Flows to the Browser That Started Them (#15880)
* 🧿 fix: Bind Login Flows to the Browser That Started Them

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

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

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

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

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

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

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

* 🧿 fix: Keep Separate Bindings for Racing First Logins

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

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

The same-origin guard logged the request Origin and path verbatim. A non-browser client fully controls the Origin header, and the console transport uses a printf format that does not escape control characters, so a crafted value could forge log lines. Strip ASCII control characters (CR, LF, NUL and the rest) before logging, matching the pattern apiNotFound already uses.
2026-09-13 11:47:29 -04:00
Marco Beretta
9bf51fc302
🧷 style: Sidebar Row Controls, Pinned Unpin Badge and Drag Rules (#15870)
* 🔘 style: Seat Sidebar Row Actions One Radius Inside Their Row

Every control that sits on a sidebar row took the base `rounded-lg`, the same
radius as the row hosting it, so a hovered button filled corner to corner with
its row. `row-action` and `section-action` now carry `rounded-md`, one step
inside the rows, which stay as they were.

Three controls also diverged from the recipe they were built on. `ConvoOptions`
and the Projects heading action overrode the variant's hover fill with
`surface-hover`; the rename form's save and cancel buttons answered the pointer
with `hover:opacity-70` and no fill at all. All four now take the shared hover.

The project row's two actions are the exception that earns its own recipe: they
sit on a row that fills on hover, where the variant's hover surface reads as a
second, weaker hover stacked on the first. They take `surface-active` instead,
under the pointer and while the menu one of them owns is open, and sit 4px apart
like a pinned chat's own pair.

* 🧲 fix: Give Both Pinned Row Kinds One Unpin Badge, and Stop Its Flicker

Pinned chats and pinned agents/models sit in one list and are dragged against
each other, but their unpin badges were two controls: the chat's was
`text-text-primary` and always visible, the favorite's was a hand-rolled copy of
the shared row action, `text-text-secondary`, revealed on hover. `UnpinButton`
is now the single badge both rows render. It keeps the favorites' reveal, holds
open while the row's overflow menu is, and is inert while hidden so it cannot
swallow a click meant for the row.

The reveal is asked for in JS rather than through an `@media (hover: hover)`
variant: the variant has to beat the `group-hover` rules that reveal the badge,
and it loses that cascade for `opacity` while winning it for `pointer-events`,
which left the badge visible and unclickable.

Two things made a row's controls flicker under the pointer:

- The overflow slot took its width from its content, and the menu mounts a tick
  after the row is hovered. The unpin badge beside it slid 28px left at that
  moment, out from under the pointer, mid-fill; whatever landed there started
  its own. The slot now reserves its width from the row's hover, and `shrink-0`
  keeps a growing sibling from squeezing it.
- `hasInteracted` unmounted that menu on every leave, so each entry mounted a
  fresh button one frame late into an already-revealed slot, restarting its fill
  from transparent. A row that has been reached now keeps its control for as
  long as the row lives; virtualization still drops the whole row.

* 🧺 feat: Unpin a Chat by Dropping It on Chats, and Keep Pinned Kinds Apart

Dropping a chat on the Chats section filed it out of its project but left a
pinned one pinned, so the section it landed in was not the section it went to.
The drop now also unpins, and accepts a pinned chat that is already in the root
list; a chat that is both filed and pinned comes out of both, each call a no-op
for the half that already holds.

Pinned chats and pinned agents/models could be dragged through each other, which
the list cannot honour: the two are ordered independently and a row dropped into
the other group snapped back. Each row now accepts only its own drag type, so
the other kind never previews a displacement, and Alt+Arrow refuses the same
step. An order saved while the two interleaved is read back grouped, or a row
would be walled in by neighbours it is not allowed to swap with.

* 🧹 fix: Unnest the Row Action Width Ternary and Correct the Pinned Doc

The rebase onto `dev` left two things the branch's own checks catch: the width
branch that reserves a chat row's action slot had grown a nested ternary, which
the repository's ESLint forbids, and `dnd.ts` carried an import out of order.

The section's own doc comment still promised that favorites and conversations
"interleave freely", which this branch stopped being true: a row only reorders
against its own kind, and a stored order is read back grouped.

* 🪃 fix: Keep a Pinned Reorder That Was Released on a Row

Reordering the Pinned section with the pointer never survived the release. The
rows shifted under the drag, and the moment the button came up they snapped back
to where they had started; nothing was written, so a reload showed the old order
too. Only Alt+Arrow could actually reorder the list.

A row is a drop target — that is what makes the hover that reorders the list
arrive at all, since the HTML5 backend reports hover only for targets that could
receive the drag. react-dnd then counts that target as having handled the drop
whether or not it carries a `drop` handler, so `monitor.didDrop()` was true for
every release on a row, and the drag's `end` reads that as "this chat was filed
somewhere else" and discards the arrangement the drag built.

The row now answers the release with a result that names it, and `end` treats a
handled drop as a filing action only when the result is not that one. The same
change stops a row swallowing the drop of an unpinned chat that lands on it:
that drop reaches the section underneath, which is what pins the chat.

Covered by `dropping-a-chat-on-a-pinned-row-pins-it` and the same-kind control
inside `a-pinned-chat-cannot-be-dragged-through-a-pinned-model`, both in
`e2e/specs/mock/scenarios/pinned-drag-rules.spec.ts`.

* 🧪 test: Drive the Sidebar Row Rules in a Real Browser

Twelve scenarios in the mock harness, one per behaviour this branch claims: the
radius and fill every row control draws inside its row, the one unpin badge both
pinned row kinds carry and when it shows, the controls holding still while the
pointer crosses a row, the touch tap that reaches the badge directly, the drop on
Chats that unpins, the drop on a pinned row that pins, the kind boundary a drag
and Alt+Arrow both refuse, and the stored interleaved order that loads grouped.

They seed pinned chats straight into Mongo and set favourites and the pinned
order through the routes the star and the drag use, so the server's own cache
invalidation runs. Pointer-only scenarios skip on a pointer that cannot hover and
the touch scenario skips where it can, which is what lets the same file cover the
desktop and mobile projects.

`dragRowOnto` steps the pointer rather than jumping: the list reorders on
`dragover` once the pointer has crossed the hovered row's midpoint, and a single
move never delivers enough of them.

* 🧭 fix: Sequence the Two Halves of a Drop on Chats, and Reach the Mobile Drawer

Dropping a chat that is both pinned and filed in a project asked for the two
writes at once. The pin route answers with the conversation as it stands after
its own write, and the sidebar publishes that answer into every list, so a pin
that overlapped the project write could put the old `chatProjectId` back over
the lists the assignment had just corrected — and a failed assignment still left
the chat unpinned, out of the section it had been dragged from and still in the
project it was supposed to leave.

The unpin now waits for the assignment and runs only if it took, so a failure
leaves the chat exactly where it was and the published snapshot is the one taken
after both writes. `useAssignDroppedConversation` reports that outcome through a
named `AssignDroppedConversation` type, and the project row's drop keeps handing
back nothing, since the pinned list reads the drop result to tell a reorder from
a filing action.

On a narrow viewport the sidebar is a drawer that slides out of view rather than
unmounting, so its rows answer every query while nothing on them can be tapped.
The scenario helpers open it through the chat header the way a person does,
which is what lets the touch and keyboard scenarios run in the mobile project.

* 📝 docs: Say What the Kept Overflow Control Actually Costs

The comment beside `hasInteracted` claimed virtualization bounded the controls a
hovered row leaves mounted. It does for the chats list, which drops a row as it
scrolls out, but not for the Pinned section: that one mounts every pinned row at
once, so a pointer crossing it leaves one `ConvoOptions` per row it touched,
standing until the section unmounts. The bound there is the number of chats the
user pinned, which is worth stating rather than implying it is zero.

* ⏱️ test: Give the Sidebar Scenario Hooks the Time Their Seeding Takes

`test.setTimeout` called inside a test body does not reach the hooks around it,
and the slow part of these scenarios is in a hook: seeding a pinned list, then
reloading and waiting for the section. On a loaded machine the `beforeEach` hit
the default 30s and failed a scenario whose own budget was 60s. The timeout is
configured once per file instead, and the per-test calls it duplicated are gone.

* ⏳ test: Allow for the Cold Start the First Sidebar Scenario Pays

The first test of a run loads the app for the first time against a database that\nmay be a network hop away, and under reviewctl verify that first load pushed the\nseeding hook past 60s. The file budget is 120s and the navigation waits are 30s,\nwhich is the cold start plus room, not a licence for a slow assertion: every\nassertion here still resolves in single-digit seconds once the app is warm.

* 🧱 test: Tell an Unlaid Sidebar From a Closed One

The helper that brings the sidebar on screen read a missing bounding box as "off\nscreen" and reached for the chat header's opener, which desktop widths do not\nrender: the click waited out the whole test budget while the panel it was waiting\nfor was already open beside it. Placement is now three states — on screen, slid\nout of view, not laid out yet — and only a drawer that is really closed, on a\nviewport that really has an opener, is clicked.

* 🧮 fix: Keep Each Pinned Kind in Its Own Slots, and Never Report a Pending Write as Done

Two ways the drop and order bookkeeping could still move a row nobody touched.

A stored order written before the two kinds were kept apart can interleave them,
and `mergeVisibleOrder` substituted visible keys across that interleaving. With
part of the pinned list still draining, reordering two visible chats could carry
an undelivered chat across the favorite between them, so the row moved within its
own group once the rest of the list arrived. The stored order is now grouped the
way the section reads it back, and each kind is substituted inside its own run.

`useAssignDroppedConversation` treated a pending assignment's destination as an
outcome: dropping the same chat on Chats again while its first write was still in
flight matched `effectiveProjectId`, reported success, and unpinned the chat — and
if that first write then failed, the chat stayed in its project with its pin gone.
A write already heading where the drop asks now reports "not filed", so the drop
that started it keeps ownership of what follows.

Covered by `dnd.spec.ts` (`keeps each kind in its own slots when a legacy order
interleaves them`), `unpinDropped.spec.tsx` (`does not unpin again while an
assignment to the same place is in flight`) and the `PinnedSection` hidden-key
test, which now states the normalized order it expects.

The pinned scenarios also wait for the rows to advertise their reorder shortcut
before dragging: a move is refused until the saved order has arrived, so a drag
issued before that passed or failed on how fast the query answered.

* 🔗 fix: Wait for the Write a Drop Asked For, Whoever Started It

The pending-assignment guard assumed the write in flight belonged to another\ndrop, which would unpin the chat when it landed. The row menu populates the same\nmap and unfiles a chat without unpinning it, so a drop onto Chats made while that\nmenu action was in flight did nothing at all: an accepted drop left the chat in\nthe Pinned section.\n\nA pending entry now only stops this path from reading \ as\n"already there". The drop issues its own write and waits for that one; the\nmutation queues writes per conversation, so it lands after the one already out\nand repeats what it asked for, which the server takes as the no-op it is. The\nunpin still runs only on a write this drop saw succeed.

* 🛰️ fix: Let the Server Say Whether a Dropped Chat Is Out of Its Project

Three rounds of review found three ways the same guess went wrong, so the guess
is gone. Deciding locally whether the filing half of a Chats drop "already
holds" meant reading one of three things that are not the answer: a pending
write, which is a request that can still fail; a cached project, which another
tab may already have changed; or the drag item's own copy, older still. Each one
could let the drop unpin a chat that stayed in its project, and a chat that is
pinned nowhere and filed in a project is in neither list the sidebar shows.

The drop now always sends the assignment and acts on what comes back. Repeating
an assignment the chat already has is the no-op update it looks like, and the
mutation queues writes per conversation, so this one lands after anything
already out. The success notice reads the two project ids in the response rather
than the fact that a request was sent, so a write that moved nothing stays
quiet — which is what a pinned chat with no project gets when it is dropped on
Chats.

`unpinDropped.spec.tsx` covers the three: the unpin waits for the write, a failed
write keeps the pin, and a chat already out of every project is still confirmed
with the server and unpinned without announcing a move that did not happen.

The scenario drag helper also steps its pointer more finely. The list shifts rows
as it reorders and reads the pointer offset when the hover fires; a pointer that
arrived in one jump got a single reading, sometimes taken mid-render, and the
reorder it asked for did not always happen.

* 🧷 test: Press Only a Row the List Has Connected for Dragging

The pinned list disconnects its drag sources while the saved order reconciles,\nand a press on a disconnected row is not a refused drag — it is a click, so the\nrow opens instead of moving. Against the lab database, where that reconciliation\ntakes long enough to overlap the gesture, the Chats-drop scenario failed with the\ndragged row still pinned and now the active chat.\n\nreact-dnd marks a connected source \, so the helper waits for that\nbefore pressing.
2026-09-13 16:40:00 +02:00
Danny Avila
f43301f818
🔭 feat: Conversation Trace Viewer (#15869)
* 🔭 feat: Conversation Trace Viewer

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

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

* 🛂 fix: Address Trace Viewer Review Round 1

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* 🚰 fix: Release Failed Langfuse Response Bodies

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

Squash of #15822 onto dev, preserving authorship:

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

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

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

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

---------

Co-authored-by: TomasPalsson <tomas2212042710@gmail.com>
2026-09-12 23:00:10 -04:00