Commit graph

189 commits

Author SHA1 Message Date
Marco Beretta
3c72c3fb4a
🐢 perf: Collapse Settled Reasoning Text in AnimatedText (#16403)
Some checks are pending
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Codegraph E2E Votes / vote (full suite) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Client build recovery regression (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
Sync Locize Translations & Create Translation PR / Sync Translation Keys with Locize (push) Waiting to run
Sync Locize Translations & Create Translation PR / Create Translation PR on Version Published (push) Blocked by required conditions
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
* perf: Collapse Settled Reasoning Text in AnimatedText

AnimatedText re-split and re-classified the entire accumulated reasoning
string on every streamed token and rendered one element per word, making
a long reasoning stream quadratic. Classification is now append-only: the
leading run of words that finished fading is committed as a single text
node and never re-split, and only the unsettled tail is classified.

* perf: Probe the Settled Reasoning Prefix Instead of Rescanning It

The append check compared the whole settled prefix on every token, which
kept the stream quadratic in character comparisons. It now probes the
prefix head and the region at its boundary, and the settled region is
rendered from the current text so a rewrite can never show stale
characters. Adds a long reasoning stream scenario to the mock harness.

* perf: Settle Spaceless Reasoning Runs Before Their Final Segment

A CJK or Thai reasoning stream never reaches whitespace, so the settled
prefix could not advance and the whole run was re-segmented per token.
Inside a spaceless last word everything before its final segment is now
treated as stable; re-segmenting there only changes fade granularity.

* perf: Bound the Unsettled Reasoning Tail by Length

Settling at part boundaries left any run that never reaches whitespace
(unspaced Hangul, a spaceless script without Intl.Segmenter, long URLs)
in the tail, re-classified on every token. The unsettled region is now
capped at 64 characters regardless of segmentation, replacing the
spaceless-specific rule; only non-animated text is ever cut, so a cut
inside a part is invisible. Tests measure the classified length per
render instead of the DOM shape.

* fix: Keep the Settled Reasoning Cut on a Glyph Boundary

The length cap could cut inside a surrogate pair or a combining or ZWJ
sequence, splitting one glyph across two text nodes. The cut now steps
back past continuation code units.

* fix: Cut the Settled Reasoning Prefix at Grapheme Boundaries

Code-unit rules missed emoji modifiers and regional-indicator flags. The
cut now takes the last grapheme boundary from Intl.Segmenter over the
unsettled tail, which starts at a committed cluster boundary and is
bounded by the cap; the code-unit rule remains as the fallback.

* fix: Skip the Reasoning Tail Cap Without a Grapheme Segmenter

The code-unit fallback could still split emoji modifiers and flags. With
no Intl.Segmenter there is no safe cut, so the cap is not applied and the
tail stops at the last word, as it did before.

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-26 22:08:22 -04:00
Danny Avila
0c47ce92a8
💭 feat: Bring the Streaming Thought Peek Back Under a Collapsed Live Card (#16394)
* 💭 feat: Bring the Streaming Thought Peek Back Under a Collapsed Live Card

#14546 previewed streaming reasoning as its trailing sentences in a short
fading window under the thought's header. The live fold (#16118) put that
thought inside a collapsed card, which unmounts its rows, so the peek went
with them and one throttled sentence on the header stood for a paragraph
of live reasoning.

A collapsed live card whose tail is a streaming thought now renders the
same peek under its header, outside the fold, in the cursor's place. It
gives way to the rows when the card opens and to the cursor when a call,
not a thought, is at the tail.

* 🧪 test: Watch Live Reasoning Stream Through the Real App

A mock-lane scenario streams three sentences of reasoning at a readable
pace; the spec samples the collapsed card's header and asserts every line
was the generic one or a whole sentence, sees the thought peek under the
card, opens the card mid-stream and checks the header became a title, then
checks the settled thought's header sits at the shared row scale.

The peek strips the thought's tags itself: handed the stream straight from
a live card, it had shown a literal `<think>` before the first words.

* 🎨 style: Sort Activity Phase Imports After Branch Rewrite

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-26 22:00:24 -04:00
lia-by-librechat[bot]
b04226eb3f
🫸 fix: Right-Align User Message Images (#16404)
* 🫸 fix: Right-Align User Message Images

* 🧪 test: Verify User Image Alignment in Browser

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-26 21:56:15 -04:00
Danny Avila
a047548fa7
🪜 feat: Title an Open Activity Fold and Reach Failed Calls in One Click (#16390)
* 🪜 feat: Title an Open Activity Fold and Reach Failed Calls in One Click

An open phase or tool group now reads as the title of the rows under it:
the header steps up to primary semibold, pins the stable label instead of
the live line, and sticks to the top while its rows scroll. Rows step in
24px under a hairline rail hung from the header glyph, one level per fold.

A failure is one click away from anywhere. A "N failed" pill beside the
header opens the fold and every failed row's output; a collapsed card peeks
its first failed call and error line under the header; the failed row
carries a red stripe, the error's first line as its subtitle, and names its
subject by the model's intent as the live header and peek already do.

The reveal travels down a FailedRevealContext counter that a group relays to
its own rows only once they have mounted, so a request made on a closed
card reaches a row three lazy disclosures below it.

* 🧪 test: Drive the Activity Fold Through the Real App and Fix What It Showed

A mock-lane spec runs a phase whose middle batch holds a call that failed
schema validation beside a slow one, watches the fold stream, then reaches
the error from the peek, from the pill, and again after a reload, in both
themes, with no console or page errors.

Three things the real app showed that the harness had not:

- The client counted only two of the server's three failed-output shapes,
  so a schema-validation failure that the server labelled `partial` rendered
  as a completed card with no pill. `isError` now mirrors
  `completedToolExecutionStatus`.
- A row's label lost its last letters to an ellipsis whenever its subtitle
  overflowed: the weighted shrink left the label a fraction of a pixel short.
  The subtitle now takes all of the shrink and the label caps at the row.
- The peek named an MCP call by its server while the row named the tool.
  Both now name it the way the row does, and the error line drops its bare
  `Error:` prefix the red glyph already speaks for.

* 🎯 fix: Answer a Failed-Call Reveal From Every Card's Disclosure Control

The reveal was consumed by the generic ToolCall row alone, so a failed
bash, code, memory, file or skill card, each rendered through its own
component, opened its group and stopped. The consumer now lives in
ProgressText, the disclosure control every card renders: a failed, openable,
closed row opens through the card's own toggle, and the one row the request
lets take focus lands the reader on its labeled button rather than on an
unnamed wrapper. The request carries a one-shot focus claim, relayed
through nested providers, so a phase with several failures opens all of
them and focuses only the first in document order, the one its peek named.

Also from the same review: an error line is derived only from output that
is an error, so a step failed by its run status or a status attachment no
longer shows ordinary output in red; a standalone group shows its failure
count once, on the pill, keeping the text for the accessible name; and the
label and subtitle share one shrinking box so the verdict, duration and
chevron after them never lose width.

* 🎯 fix: Make Failed Activity Cards Reachable From Fold Controls

* 🛡️ fix: Keep Legacy Search Errors Hidden Outside Failure Summaries

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-26 21:25:30 -04:00
lia-by-librechat[bot]
84e3ea9ed9
🧗 fix: Keep Manual Compactions on the Active Branch (#16386)
Co-authored-by: Lia <lia@librechat.ai>
2026-09-26 06:55:16 -04:00
Marco Beretta
764a4393f4
📏 fix: Constrain the Agent Selector to 480px and 10 Own Agents (#16256)
* fix: constrain agent selector to 480px and 10 unsearched agents

The Agents panel selector dropdown now caps at 480px tall with the option
list scrolling inside, and lists at most 10 agents while the search field
is empty; typing lifts the cap so search still reaches every agent.
ControlCombobox gains optional popoverMaxHeight and unsearchedLimit props,
so every other selector keeps its current fixed 300px list.

* fix: make the agent selector cap configurable, viewport-safe, and selection-preserving

The unsearched list cap now reads interface.agentSelectorLimit from
librechat.yaml (default 10), the popover cap yields to Ariakit's
available height so a short viewport never pushes options offscreen,
and a selected agent ranking past the cut keeps the last slot instead
of disappearing until searched for.

* fix: forward agentSelectorLimit through the interface loader and guard it at the client

loadDefaultInterface whitelists interface fields, so the new knob never
reached /api/config without explicit forwarding; and values that bypass
interfaceSchema (raw yaml reads, principal-scoped admin overrides) are
normalized back into 1..100 at the client so a bad override cannot empty
the selector.
2026-09-23 22:21:08 -04:00
lia-by-librechat[bot]
e4fe31623e
🚉 fix: Keep Queue Controls with the Starting Turn (#16268)
* 🚉 fix: Keep Queue Controls with the Starting Turn

* 🚉 fix: Stabilize the Pending-Turn Portal Callback

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-23 21:21:51 -04:00
lia-by-librechat[bot]
80e55b4e96
🥢 ci: Select Quote Text Across the Streaming Fade's Word Spans (#16189)
The quote specs resolved a needle inside a single text node, which the
smooth-streaming fade makes untrue for the whole window between a reply
being fully readable and its turn settling: `animate.tsx` wraps every
word of the animated message in its own span, so `E2E opening paragraph`
lives in three sibling text nodes and the lookup threw
`No text node contains: E2E opening paragraph`.

The lookup now matches each message's flattened text and maps the match
back onto the nodes it came from, and the cross-message test checks the
selection is still crossing two messages when it asserts the popup stays
away, so a collapsed selection can no longer pass it by default.

Co-authored-by: Lia <lia@librechat.ai>
2026-09-22 04:08:56 -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
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
2db8d91745
⚡ perf: Preserve Message References in the Content Handler (#16072)
* ⚡ perf: Preserve Message References in the Content Handler

* test: cover content handler message reconciliation

* fix: preserve thread metadata for incomplete content events

* fix: retain fallback response thread identity

* fix: select parent from response thread

* fix: retain untagged conversation messages

* fix: preserve history while resolving parent

* fix: refresh cached response metadata

* fix: honor synchronized parent metadata

* fix: scope parent fallback to response thread

* fix: avoid cross-thread parent fallback

* fix: keep content handler selection semantics
2026-09-20 19:27:36 -04:00
Marco Beretta
5f4a07f40b
⚡ perf: Exclude Agent Version History From Default getAgent Reads (#16070)
* ⚡ perf: Exclude Agent Version History From Default `getAgent` Reads

getAgent now defaults its projection to { versions: 0 }; loadAgent/loadAddedAgent
and canAccessAgentFromBody use getAgentWithVersionCount so the version count stays
exact without transferring the unbounded versions array on every chat request.
Callers that need history (v1 update/revert handlers) request it explicitly.

* fix: tighten agent version projection types

* fix: type projected agent version counts

* fix: type default agent projection

* style: format agent projection overload

* fix: expose projected agent return type
2026-09-20 19:27:21 -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
50d46a38a5
📍 test: Add Deployed Smoke Profile (#16135)
* test: add deployed instance Playwright smoke profile

* test: normalize deployed smoke account state

* test: harden deployed smoke lifecycle

* test: secure deployed smoke cleanup
2026-09-20 12:34:02 -04:00
lia-by-librechat[bot]
8c41809685
⚓ fix: Keep a Resumed Compaction Anchored to the Turn It Summarizes (#16037)
* ⚓ fix: Keep a Resumed Compaction Anchored to the Turn It Summarizes

A compaction submits no user turn: its user-message slot names the leaf it
summarizes up to. The resume paths adopted that identity-only projection as a
ROW, rewriting the answer being summarized into an empty, parentless user
message, which buildTree files as a phantom root: the thread folded and the
pane could return on another branch. Treat the slot as an anchor everywhere
rows are written, and let the anchor name the branch to restore.

* Recognize a compaction anchored on a user leaf

Compact runs on whatever leaf the branch ends with and canCompact does not restrict its author, so the anchor is a user message as often as an answer. Detecting it by not-user-created recognized only the assistant-leaf kind: the other was rebuilt as an ordinary turn, so the sync path merged the identity-only projection over the stored row and blanked the prompt still on screen, and a failed abort appended a second row under its id. Judge the anchor by the projection shape instead, and carry the resolved answer on the resumed submission so a flagless re-attach agrees.

---------

Co-authored-by: Lia <lia@librechat.ai>
2026-09-20 12:25:15 -04:00
lia-by-librechat[bot]
d281c31d54
🫛 test: Separate an Authoring Run From a Skills-Off Run (#16128)
Co-authored-by: Lia <lia@librechat.ai>
2026-09-20 08:25:07 -04:00
lia-by-librechat[bot]
5afee47dff
🎫 perf: Limit Redis Script Caching to Atomic Claims (#16116)
* refactor(redis): import script cache proposal from #16069

Squashed copy of PR #16069 at 7e994194c2, rebased onto current dev without changing the original branch.

Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com>

* refactor(redis): cache independent claims without queueing streams

---------

Co-authored-by: Lia <lia@librechat.ai>
Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com>
2026-09-20 06:24:52 -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
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
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
Dustin Healy
ec1304f684
🛅 fix: Preserve Agent Management Upload IDs (#15840)
* fix: preserve agent management upload IDs with E2E coverage

* test: clean up agent management upload fixtures
2026-09-14 15:24:47 -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
b204216c64
🧷 fix: Keep a Failed Summary From Bounding the Conversation History (#15913)
* 🧷 fix: Skip Failed Summaries When Resolving the Conversation Checkpoint

* 🧷 fix: Keep a Failed Summary Out of the Model-Facing History Boundary

* 🧭 refactor: Own the Summary Checkpoint Predicate in packages/api

* 🧯 fix: Reject Unfinished Summaries Everywhere and Recount Stripped Turns

* 🧬 fix: Version Event-Actor Summary State So Legacy Prefixes Cannot Warm

* 🏷️ fix: Stamp Inherited Summaries Where Actor State Is Assembled

* ⚖️ fix: Drop Unusable Summaries While Building the Prompt

* 🧷 fix: Repoint Prompt Content Instead of Splicing Stored Parts

* 🧭 fix: Treat a Streamed Summary Without a Boundary as Unfinished

The server has stamped `failed` on an errored summarize round only since
#14546, and `summarizing` never reaches storage, so every round that errored
on v0.8.7 or rc2 was persisted as a plain summary holding its partial deltas.
The flag checks cannot tell that row from a checkpoint, so upgraded
conversations kept losing the history before it.

The aggregator settles it structurally, identically in every SDK release
that has shipped compaction (3.1.63 through 3.8.6): deltas stream `content`
blocks into the part, and only a completed round replaces the part with the
final block, which is the sole writer of `boundary`. A `content`-block summary
without a boundary therefore never finished. `isUsableSummaryPart` and the
shared `isCompactedLeaf` both apply that rule; bare-`text` rows predate the
aggregator and stay governed by the flags.

Fixtures that stand for completed summaries now carry the boundary a real
run writes, and the flag fixtures keep one so they still test the flags.

* 🔁 fix: Strip Unusable Summaries From Responses API Continuations

`previous_response_id` loads the stored conversation and hands each message's
`content` array straight to `formatAgentMessages`, whose summary scan takes
the last summary part carrying text as the history boundary. The chat client
strips unusable summaries before that scan; this entry point did not, so a
conversation continued through the Responses API still lost everything before
a failed round. The same packages/api helper now runs ahead of the formatter.

* 🧭 refactor: Own Event-Actor Summary Selection in packages/api

`getLatestEventActorSummary` decides which summary a warm continuation
carries forward, how a missing token count is recorded, and how the state is
stamped. That is compaction behavior, and every helper it relies on already
lives in `packages/api/src/agents`, so it moves beside `isUsableSummaryPart`
and the controller imports it.

* 🧪 test: Give the Finished Compaction Leaf the Boundary a Completed Round Writes

`isCompactedLeaf` now requires the boundary only a completed summary block carries, so the client fixture for a finished compaction needs one, and a boundaryless leaf joins the interrupted compactions that can be retried.

---------

Co-authored-by: Danny Avila <danny@librechat.ai>
2026-09-14 10:22:47 -04:00
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
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
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
Dustin Healy
19eb24921e
🔠 feat: Render Safe Upstream Model Errors (#15837)
* ✨ feat: Surface Upstream Model Errors

* 🧪 test: Cover Upstream Error Rendering

* 🛡️ fix: Harden Upstream Error Fallbacks

* 🛡️ fix: Defer Upstream Error Fallbacks
2026-09-12 20:23:54 -04:00
Joseph Licata
f25242df98
🦘 feat: Share Run-Scoped Files With Subagents (#15848)
* feat: add run-scoped file sharing for subagents

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

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

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

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

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

* test: align file-sharing fixtures and integration cleanup

* test: repair LibreOffice conversion fixtures

* test: verify deployment skill bytes across checkout formats

* fix: align subagent file budgets and refresh boundaries

* chore: update agents SDK to 3.8.6

* refactor: move code output processing into API workspace

* fix: enforce shared file budgets for parents and teams

* fix: declare the shared file encoder interface
2026-09-12 20:14:22 -04:00
Marco Beretta
246e7e5de7
💠 fix: Paint Native Tool Verification Badges (#15862)
* 🪪 style: Give Native Tools a Painted Verified Mark

The native badge on a tool card was lucide's BadgeCheck filled with status-success-strong: green, the same hue the card already uses for selected, and stroked in currentColor, so the white check color also outlined the badge and left a white halo on any surface that is not the card's own white — hover, selection, dark mode.\n\nVerifiedIcon paints the badge instead of stroking it and carries the check as the only stroked path, and status-verified gives provenance its own blue across all four themes.

* 🩹 fix: Hold the Verified Mark at 3:1 on Every Card State

The dark fill was tuned against surface-secondary, but ToolCard repaints to surface-tertiary (#2f2f2f) on hover, where #0b74d4 fell to 2.85:1 — below the non-text floor, and invisible to the spec, which asserted the panel only. The fill moves to #1a7fd8 and the contract now covers every background the card takes. Both of the mark's relationships are graphical objects under WCAG 1.4.11, so the check is held at 3:1 rather than AA: no hue clears 3:1 on the hover surface and 4.5:1 under a white check at once.\n\nA theme that predates the token names status-success-strong and not status-verified, and would otherwise wear LibreChat's stock blue beside its own text-on-status and card surfaces. resolveTheme and the legacy mapColors adapter now carry the mark onto the fill it had before the token existed, following the six derived-token fallbacks already there.

* ✅ test: Exercise the Verified Mark in the Tool Library

Four scenarios in the mock harness, each named by the behavior it observes: the mark a native card wears, its silhouette under the dark hover repaint that the retune fixes, a pre-token deployment palette carrying it on the theme's own success fill, and a third-party MCP server card carrying no mark at all. The contrast assertions read the rendered colors rather than the tokens, so a regression in the component or in theme application fails them.

* 🧪 fix: Teach the Marketplace Dialog Spec About VerifiedIcon

The suite hand-lists the @librechat/client surface it mocks, so ToolCard's new icon resolved to undefined and every render in the file threw.

* 🧪 fix: Reach the Agent Builder on a Narrow Viewport

The scenario run covers mobile emulation, where the side rail is collapsed and the panel opens from the header's Control Panel toggle; the helper only knew the rail. The MCP scenario also minted its access token before the app had loaded, so the refresh request had no origin to resolve against.

* 🧪 fix: Run the Verified-Mark Scenarios on a Touch Viewport

Mobile emulation has no side rail: the panel switcher lives inside a sidebar that starts off-canvas, so the helper opens the sidebar and picks the Agent Builder entry from the switcher's menu. A touch viewport also has no hover state, so the hover scenario measures whatever background the card actually takes there and still holds the mark to 3:1 against it.

* 🩹 fix: Keep Pre-Token Themes on the Fill the Mark Inherited

The first fallback only fired when a theme restated status-success-strong, so a partial palette that customizes surfaces or text-on-status and inherits the green still landed on the stock blue. resolveTheme now derives the omission for any custom theme from the resolved success fill, and the legacy adapter takes the mode's bundled palette from ThemeProvider so it can do the same for a theme that names neither.\n\nThe scenario helper picked its path from a one-second probe for the desktop rail, which turns a slow first paint into the mobile branch; it now decides on viewport width and keeps the suite's full assertion timeout in each branch. The mock project is Desktop Chrome, so a touch scenario asks for a touch context explicitly rather than leaving that layout unexercised in CI.

* 🧪 fix: Match the App's Inclusive Layout Breakpoint

useSidebarState switches on (max-width: 768px), so a 768px-wide context renders the sidebar switcher while the helper's strict comparison went looking for the desktop rail.

* 🩹 fix: Scope the Verified Fallback to Themes That Painted the Mark

Two rounds pulled the same predicate in opposite directions: keying it on a theme restating status-success-strong missed palettes that only repaint the check or the card, and keying it on any custom color at all gave a new partial theme a green mark identical to the selected cue. Both are answered by asking what the theme actually painted — the fill the mark wore, the text-on-status check it carries, or the surfaces ToolCard takes — which is the same shape as the series-scale fallback above it. A theme that repaints none of those keeps the bundled blue.

* 🧪 fix: Wait for the Shell Before Reading the Sidebar State

isVisible() answers immediately, so a slow first paint read as an already-open drawer and the helper then waited on a switcher sealed inside it. It now waits for whichever of the opener and the switcher the shell paints first, which is the same assertion timeout the desktop branch gets.

* 📝 fix: Keep the Token Catalog Entry Catalog-Sized

The entry restated the icon's construction, the contrast rule and the pre-token fallback, all of which live on the token's own doc comment and in semanticTokens.spec.ts; the catalog around it is one line per role.

* 🔦 fix: Let a Crashed Lighthouse Run Be Retried

The audit shells out to Lighthouse three times and fails the lane if any single process exits nonzero, so a NO_NAVSTART — Lighthouse losing the trace of a page load, whose own message is "run Lighthouse again" — sinks a pull request that has nothing wrong with it. That is what happened on this branch: runs 1 and 2 wrote reports, run 3 crashed, and the identical head passed on rerun.\n\nEach run now gets a second attempt before the failure propagates. The repeat is per run, so the median is still taken over three completed reports, and a page that genuinely cannot be traced fails both attempts and still fails the lane.

* 🧪 fix: Read the Drawer State From Its Inert Marker

The readiness wait accepted the panel switcher, which is mounted whether or not the drawer is open — translated off-canvas and inert — so a shell that painted the sidebar before the chat header could satisfy it with the drawer closed and leave the helper clicking an off-viewport control. The drawer's own inert attribute is the state, so the helper waits for the drawer to attach and reads it there, with no timing probe on either side.

* 🧪 fix: Open the Drawer Before Trusting the Restored Form

A narrow context that had already selected the builder restores the form inside the closed drawer, and a translated element passes a visibility check, so the early probe accepted a form sitting under an inert drawer and handed it to the caller. The layout decision now comes first and the drawer is opened before anything inside it is read.
2026-09-12 16:03:03 -04:00
Danny Avila
767ee591d0
📴 fix: Stop Hidden Code Spinners (#15846)
* fix: keep quote selection updates outside React renders

* fix: stop animating hidden code execution spinners

* test: guard idle transcripts against continuous animations

* test: Assert accepted paste behavior independently of placeholder resize
2026-09-11 21:37:49 -04:00
Marco Beretta
1bea7e4c9e
🧽 style: Composer, Welcome Screen and Context Panel Polish (#15838)
* 🕵️ style: Mark Temporary Chat with the Incognito Icon

The dashed speech bubble (`MessageCircleDashed`) read as a generic chat glyph
rather than a retention cue, and its dashes break up at 16px. Every temporary
chat surface now uses lucide's `hat-glasses`, the hat-and-glasses incognito
mark: the header toggle, the read-only indicator chip once a conversation has
started, the overflow menu row, and the landing empty state.

`hat-glasses` landed in lucide 0.528.0, so `lucide` and `lucide-react` move
from `^0.525.0` to `^0.528.0` in `client` and `packages/client` (dependencies
and peers). That is the smallest bump that carries the icon; lucide redraws
existing icons between minors and the whole UI draws from it, so jumping to the
current 0.577 would bring unrelated visual churn.

`useChatBadges` imported the old icon without using it; the import is dropped.

* 🧹 style: Keep the Model Disclaimer on the Landing Page Only

The footer disclaimer rendered under the composer in every conversation, where
it repeats itself on each turn and costs a line of the thread. It now renders
only on the landing page, where it is first seen.

`Footer` is untouched, as are its other hosts: the auth screens and the public
shared-link view still render it. The component is a zero-height `relative`
wrapper around an `absolute bottom-0` bar, so dropping it from the conversation
branch shifts no layout.

* 📱 fix: Run the Mobile Composer to the Screen Edges

Below `sm` the composer is full-bleed — no horizontal padding, squared off at
the bottom, flush with the viewport floor — but it was inset on two sides there:

- `.scrollbar-gutter-spacer` reserved the message column's scrollbar band (8px)
  on the composer's trailing edge. That lines the composer up with the thread on
  desktop, but on mobile it only cut a dead strip off its right side, so the
  padding now applies from `sm` up. Its two users, the composer band and the
  scroll-to-bottom control, move together, so the control still stacks over the
  send button.
- The composer surface carried `pb-4` under its action row below `sm`
  (`sm:pb-0` above), leaving 16px of empty surface between the buttons and the
  bottom of the screen.

Desktop metrics are unchanged: the band still reserves the gutter, the composer
still clears the floor by `sm:mb-10`, and the surface still resolves to `pb-0`.

* 🔅 style: Mute the Landing Page Disclaimer

The footer sat in `text-primary`, the same weight as the greeting above it, so
the least important line on the landing page read as one of the most prominent —
hardest to ignore in the light theme, where it lands at 16.1:1 on white.

It now takes `text-muted`, the quietest text token that still clears AA for
12px copy on `bg-presentation`: 5.11:1 on white and 7.93:1 on the dark canvas.
The contrast modes collapse every text token to pure black or white, so
`high-contrast-light` and `high-contrast-dark` keep the disclaimer at 21:1.

The links move with it instead of keeping the brighter `text-secondary`: the
underline carries the affordance, and a link that outshines its own sentence
puts the emphasis back where this change takes it from.

The text stays at the bottom of the page. The landing hierarchy is the composer
and its title first, the sidebar second, and moving the disclaimer under the
text field would place it above both.

* 💠 style: Draw the Empty Prompts Panel Like Its Neighbours

The prompts side panel hand-rolled its own empty card — the same circular icon,
title and caption as the bookmarks, memories and schedules panels, but written
out again and a shade off: `border-border-medium` where the shared card uses
`border-border-light`.

It now renders the `EmptyState` primitive the other panels use, which is where
that appearance is owned. The strings, the icon and the list's own `my-2` are
unchanged, so the panel reads the same apart from the border it was never meant
to differ on.

* 📐 fix: Close the Gap Under the Composer in a Conversation

From `sm` up the composer band left 40px under itself, the height of the
disclaimer that used to sit there. A started conversation no longer carries one,
so the composer floated a line above the viewport floor with nothing in the gap.

The clearance now follows what is underneath. `ChatView` owns that fact — it is
the same `isLandingPage` it gates the footer on — and passes it to `ChatForm`:

- landing, centred composer: `sm:mb-28`, unchanged
- landing, composer at the bottom: `sm:mb-10`, the clearance the disclaimer
  needs, unchanged
- started conversation: `sm:mb-4`, enough to show the surface's own shadow

Below `sm` the composer still runs to the viewport floor in every state.

`ChatForm` cannot answer this for itself: deriving it from
`conversation?.messages?.length === 0` reads false while `messages` is
undefined, which silently drops the un-centred landing page to the conversation
clearance and overlaps the disclaimer.

`SubagentThreadPanel` states that its own bottom padding matches the main
composer's so the two surfaces end on one line when the panel is open beside a
thread, so it moves with it.

* 🎞️ fix: Slide the Composer Between Welcome Screen and Conversation

With "Center Chat Input on Welcome Screen" off, the welcome composer sits at the
bottom with the disclaimer's clearance under it and a conversation's sits 24px
lower. React keeps the same form node across that navigation, so the band had
everything it needed to travel and jumped instead: `margin-bottom`, the property
that carries it, was not in the transition list — only `max-width` was, from the
chat-width preference.

`margin-bottom` now transitions with it, 300ms on Tailwind's default easing, in
both directions and from the centred welcome composer as well. Reduced motion
gets the new position outright (`motion-reduce:transition-none`): this is a
slide across the page, not decoration.

* ↔️ fix: Hold the Composer Still Across the Welcome Screen

Opening a conversation from the welcome screen slid the composer 4px to the
left. A conversation's composer band reserves the band the message column holds
back for its scrollbar (`.scrollbar-gutter-spacer`, 8px here), which is what
lines the composer up with the messages; the welcome screen reserved nothing, so
its composer was centred on the full region and half the gutter off from where
it was about to land. Now that `margin-bottom` animates, the sideways step ran
alongside the downward one.

The gutter is reserved once per state, wherever the centring happens: the
conversation keeps it on the band around the composer, and the welcome screen
takes it on the column that centres greeting and composer together, so both move
as one and the composer lands where the message column will put it.

Measured across the navigation — 1280 and 1024 wide, centred and bottom
composer, sidebar open and collapsed: the surface keeps its exact left edge and
width. Below `sm` the reservation does not apply and the composer stays
full-bleed on both sides of the navigation.

* 📏 fix: Measure the Scrollbar Gutter Before the Welcome Screen Reserves It

The welcome screen holds back the band the message column reserves for its
scrollbar, so the composer lands where the message column will put it. On a
fresh load no message column has mounted, so `useScrollbarGutter` has published
nothing and the spacer fell back to `--scrollbar-size`: a fixed 8px, correct
only where the app's own `::-webkit-scrollbar` width applies. On an
overlay-scrollbar platform the real band is zero, so the welcome screen started
4px off-centre and the composer stepped sideways as soon as the first
conversation measured the band for real — the jump this change set out to
remove, inverted.

The gutter is now seeded from a detached probe built like the column itself
(`overflow-y: auto` with `scrollbar-gutter: stable`), which answers the same
question for the platform in front of the user: the scrollbar width, and zero
where scrollbars overlay. A mounted column measures itself and is
authoritative, so the seed only fills the gap before the first one exists and
never overwrites a published measurement.

Reported by Codex on PR #15838:
https://github.com/danny-avila/LibreChat/pull/15838#discussion_r3991992182

* 🧪 test: Cover the Composer and Welcome Screen Behaviours

Nine browser scenarios for what this change promises, in the mock harness
against the in-process fake model, tagged so each one is addressable:

- `welcome-screen-disclaimer-only`, `welcome-disclaimer-readable-while-muted`:
  the disclaimer stays on the welcome screen, leaves the conversation, and
  clears AA contrast against the canvas it is painted on — the dark project
  measures the dark palette, the light one the light palette.
- `composer-holds-position-into-conversation`,
  `composer-holds-position-with-overlay-scrollbars`: the composer keeps its left
  edge and width across the navigation and lines up with the message column,
  both with the app's own scrollbars and on a platform whose scrollbars reserve
  nothing.
- `composer-slides-down-into-conversation`,
  `composer-settles-instantly-under-reduced-motion`: the clearance change runs as
  a `margin-bottom` transition on the composer's own form, and runs no
  transition at all under `prefers-reduced-motion`.
- `mobile-composer-reaches-screen-edges`: below `sm` the surface spans the
  viewport and its action row is the last thing in it.
- `temporary-chat-marked-with-incognito-icon`: turning the mode on marks the
  toggle and the welcome screen with the outline incognito mark.
- `empty-prompts-panel-matches-other-panels`: the empty prompts card and the
  empty bookmarks card are drawn identically.

Each scenario skips the projects whose viewport it does not describe, rather
than asserting a desktop layout under mobile emulation.

* 🩹 fix: Seed the Gutter Before Paint and Keep Configured Footers

Three findings from the review round on eec4b37, one root cause each.

The gutter seed measured in a passive effect, so the welcome screen's first
frame still reserved the `--scrollbar-size` token and recentred by 4px once the
real band was known — the load-time half of the shift this reservation removes.
It measures in a layout effect now, before the browser paints.

Scoping the disclaimer to the welcome screen also unmounted the only
authenticated-chat renderer of `customFooter`, and of a deployment's privacy
policy and terms links. `Footer` takes `configuredOnly`: the generic disclaimer
is dropped, operator content is kept, and with nothing configured it renders
nothing rather than an empty bar. The conversation renders it again under that
scope.

The mobile composer spec gated itself on viewport width, and the repository's
mock config has one Desktop Chrome project, so CI skipped it and reported
nothing. It declares the viewport it describes with `test.use`.

Two scenarios cover the first two:

- `welcome-composer-paints-in-its-final-position`: samples the composer's x from
  the document's first frame on a platform whose scrollbars reserve nothing, and
  fails on any later correction.
- `configured-footer-stays-in-a-conversation`: serves a configured
  `customFooter` through the startup-config route and finds it on both the
  welcome screen and inside a conversation.

Findings:
https://github.com/danny-avila/LibreChat/pull/15838#discussion_r3992539826
https://github.com/danny-avila/LibreChat/pull/15838#discussion_r3992539834
https://github.com/danny-avila/LibreChat/pull/15838#discussion_r3992539845

* 🧹 test: Drop the First-Paint Sampler, Keep the Layout Effect

The sampler recorded the composer's x from the document's first frame to catch a
late recentring on a platform whose scrollbars reserve nothing. It cannot fail:
with the seed measured in a passive effect it still recorded a single position
in all three projects, because React flushes that effect before the browser
paints the commit it belongs to. A test that passes with and without the
behaviour it describes pins nothing.

The measurement stays in a layout effect: a value the layout reads belongs
before paint by construction, whatever a given runtime's flush order happens to
be. The reservation itself is covered by
`composer-holds-position-with-overlay-scrollbars`, which does fail without it —
4px, the half-band Codex reported.

* 🧷 fix: Clear the Configured Footer and Remeasure the Band on Contrast

Two findings from the round on d942b7c, one invariant each.

Keeping a configured footer in conversations left the composer reserving 16px
above an absolutely positioned bar about 32px tall, so the bar painted over the
composer's action row and would have taken its clicks. The clearance follows
what actually renders beneath the composer now, not which page it is: `ChatView`
reads `useConfiguredFooter` once and both decisions — whether to render the
footer, and how much room to leave for it — come from that same answer.
`ChatForm` takes `footerBelow` and keeps the welcome screen's rhythm for the
welcome screen.

The band is not a constant of the platform either: the contrast modes widen the
app's own scrollbar to 0.75rem, and a reader can turn contrast on — or have the
OS turn it on — while the welcome screen is the only thing mounted, with no
message column to republish. The seed remeasures when `ThemeProvider` flips a
class on the document element, which is the thing that changed the band.

Two scenarios, both failing before the fixes:

- `configured-footer-clears-the-composer`: with `customFooter` configured, the
  bar sits at or below the composer's bottom edge and the composer still takes a
  click at its own bottom row.
- `composer-holds-position-across-a-contrast-switch`: contrast turned on while
  the welcome screen is up, then a conversation opened; the composer keeps its
  left edge and width.

Findings:
https://github.com/danny-avila/LibreChat/pull/15838#discussion_r3992984510
https://github.com/danny-avila/LibreChat/pull/15838#discussion_r3992984517

* 🪡 fix: Align the Subagent Panel With the Conversation's Footer

The panel's bottom band states that it matches the main composer's clearance so
the two surfaces end on one line beside each other. That clearance became
footer-dependent in the previous commit, and the panel kept a fixed `pb-4`, so a
deployment with a configured footer ended them 24px apart.

The panel reads the same answer the composer reads — `useConfiguredFooter` — and
clears the bar when there is one. Three consumers now share one source for the
question "does a footer render beneath this surface": `ChatView`, `ChatForm`
through `footerBelow`, and this panel.

The panel's own alignment has no browser scenario: reaching this surface needs
an agent with subagents, a dispatched task and an open control footer, which is
a fixture of its own. The shared cause is covered by
`configured-footer-clears-the-composer` on the main composer.

Reported by Codex on PR #15838:
https://github.com/danny-avila/LibreChat/pull/15838#discussion_r3993177163

* 🧵 fix: Hold the Footer Clearance Through a Cold Load and a Stale Band

Three findings from the round on 55106cd.

Whether a conversation carries a footer is an answer from the startup config,
and on a cold `/c/<id>` load it arrives after the composer is painted.
`useConfiguredFooter` now reports `{ present, resolved }`, and the two readers
use them differently on purpose: nothing renders until the answer arrives,
because there is nothing to render, but the clearance is held from the first
frame, because guessing "no footer" moves the composer twice.

The measured scrollbar band outlives the chat screen on purpose, and the screens
it outlives can change it — the auth layout carries a theme selector, and a
contrast switch there widens the app's own scrollbar while no chat column is
watching. The seed measures on every mount now instead of trusting a value it
did not publish.

`@librechat/client`'s peer range kept its previous line as well as the new one
(`^0.525.0 || ^0.528.0`): only `/client` consumes `HatGlasses`, and the shared
package still builds against either, so raising the published minimum would have
rejected downstream installs for an icon it does not use. Its devDependency
stays on 0.528, which is what it is tested against.

Two scenarios, both failing before the fixes:

- `configured-footer-clearance-survives-a-cold-load`: the startup config is
  served 700ms late with a custom footer, and the composer's bottom is sampled
  from the document's first frame; any correction fails it.
- `welcome-screen-remeasures-a-stale-gutter`: a 40px reservation is left behind
  before the app boots, as another screen would, and the welcome screen has to
  replace it rather than inherit it.

Findings:
https://github.com/danny-avila/LibreChat/pull/15838#discussion_r3993328716
https://github.com/danny-avila/LibreChat/pull/15838#discussion_r3993328723
https://github.com/danny-avila/LibreChat/pull/15838#discussion_r3993328726

* 🧠 fix: Remember the Footer Answer Instead of Guessing It

Reserving the footer's band while the startup config was in flight fixed the
cold load of a deployment that configures a footer and broke the cold load of
one that does not: the composer took `sm:mb-10`, then dropped 24px when the
answer said there was nothing to clear. Both defaults are wrong for one of the
two deployments, because the layout was being derived from an answer that does
not exist yet.

`useConfiguredFooter` remembers the answer instead. A deployment's footer
configuration is a deployment-lifetime fact, so the last answer it gave is the
right thing to lay out against while `/api/config` is in flight; it is recorded
once the query resolves. Every load after the first is exact in either kind of
deployment, and a first-ever visit falls back to LibreChat's default — no
configured footer — and settles once if the deployment disagrees.

`ChatView` and the subagent panel drop the `!resolved` term: `present` already
carries the remembered answer, so the value is the same before and after the
config answers.

Scenarios, both sampling the composer's bottom from the document's first frame
with the config served 700ms late:

- `configured-footer-clearance-survives-a-cold-load` now primes the answer with a
  first visit and asserts the load after it, which is the load a returning user
  gets.
- `default-clearance-survives-a-cold-load` covers the other branch: a deployment
  that configures nothing must not move either.

Reported by Codex on PR #15838:
https://github.com/danny-avila/LibreChat/pull/15838#discussion_r3993438258

* 🛟 fix: Treat a Failed Startup Config as No Answer

React Query reports a request that exhausted its retries as fetched, with no
data, so reading `isFetched` turned a failed `/api/config` into a confirmed
"nothing configured": a deployment remembered as having a footer lost the
clearance that footer needs, and the memory was overwritten with the guess, so
the composer moved again on the next load that succeeded.

`useConfiguredFooter` reads `isSuccess`. A failure now answers nothing: the
remembered deployment state stands, and nothing is recorded until a response
actually arrives.

`config-failure-keeps-the-remembered-footer` covers it: a first visit records a
configured footer, a second visit is served 500s until the retries run out, and
the composer's clearance has to be the one it had.

Reported by Codex on PR #15838:
https://github.com/danny-avila/LibreChat/pull/15838#discussion_r3993554041

* 🧽 test: Drop the Config-Failure Scenario, Keep the Success Check

The scenario recorded a configured footer, served `/api/config` 500s until the
retries ran out, and then asserted the next successful load lays out once. It
cannot fail: without a startup config the app renders no chat at all, so
`useConfiguredFooter` is never mounted on the failing visit and nothing is
recorded either way. The negative control — reading `isFetched` again — passes
it in all three projects.

The reported corruption therefore has no reachable path: the hook only observes
a failed query while the chat is mounted, which requires a config that answered
once, and React Query keeps that answer as cached data through a later failure.

`isSuccess` stays. "A failure answers nothing" is what the code should say, and
saying it costs nothing; the test that pretended to prove it does not stay.

Reported by Codex on PR #15838:
https://github.com/danny-avila/LibreChat/pull/15838#discussion_r3993554041

* 🧱 refactor: Own the Footer Memory in Jotai and Take the Landing Preference In

Two repository-policy findings from the round on 5d535a6.

The remembered footer answer was a raw `localStorage` read and write, which is
the persistence path the client state rules replaced: it is feature-owned state
that the chat surface both writes and reads, so it is a Jotai storage atom now
(`configuredFooterAtom`, beside the feature that owns it). `getOnInit` is what
makes it usable — the value has to be there on the first render, or it is the
guess again — and only a successful config response writes to it.

`ChatForm` also still subscribed to `centerFormOnLanding` directly, an
app-level persisted preference the chat feature only consumes. `ChatView`
already reads it for `Landing`, and now passes it in beside `isLandingPage` and
`footerBelow`, so the composer's clearance is computed entirely from what the
host handed it.

Findings:
https://github.com/danny-avila/LibreChat/pull/15838#discussion_r3993728399
https://github.com/danny-avila/LibreChat/pull/15838#discussion_r3993728405

* 🔍 fix: Give the Context Popover Its Own Foreground

The popover is portaled to the body with a surface colour and no text colour, so anything inheriting \ there took the user-agent default black: the insights toggle rendered at 1.3:1 on the dark canvas and was invisible until hovered. The panel now names \ beside its surface, as the shared hover-card surface already does.

* 🧮 fix: Show the Cached Share Beside Its Tokens

The cached and cache-write rows were built without a max, and the row renders its share only when one is given, so both printed a bare token count while every row around them carried a percentage. Both now key the window, and the cached test pins the share.

The insights toggle also names its resting colour here: the ghost variant defines only a hover colour, and every other glyph in the panel names a role.
2026-09-11 21:23:17 -04:00
Marco Beretta
e2f5772961
🧮 feat: Surface Retained Tool-Message Context Usage (#15796)
Some checks are pending
Docker Dev Images Build / publish (push) Waiting to run
Sync Helm Chart Tags / Ignore non-main push (push) Waiting to run
Sync Helm Chart Tags / Sync chart tags (push) Waiting to run
* feat: surface retained tool-message context usage

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

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

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

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

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

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

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

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

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

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

Fourth round on the retained tool-message context work:

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

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

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

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

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

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

* test: exercise the context split through the mock harness

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

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

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

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

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

* fix: add pinnedOrder to IUser type and sort imports

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

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

* fix: address review findings on unified pinned section

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

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

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

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

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

* fix: address PR review bot findings

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

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

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

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

* fix: address second round of PR review bot findings

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

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

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

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

* fix: address third round of PR review bot findings

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

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

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

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

* fix: address fourth round of PR review bot findings

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

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

* fix: address fifth round of PR review bot findings

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

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

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

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

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

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

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

* fix: address sixth round of PR review bot findings

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

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

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

* fix: gate pruning on a delivered favorites list

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

* fix: address eighth round of PR review bot findings

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

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

* fix: address ninth round of PR review bot findings

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

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

* fix: address tenth round of PR review bot findings

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

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

* fix: address eleventh round of PR review bot findings

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

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

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

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

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

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

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

* fix: publish the session identity from the user atom

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

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

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

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

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

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

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

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

Leaves AuthContext and the user atom untouched.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* fix: let favorites membership reconcile between tabs

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

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

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

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

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

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

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

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

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

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

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

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

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

* fix: preserve pinned order until favorites membership catches up

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

* fix: preserve reconciled keys during active pinned arrangements

* style: sort pinned order regression imports

* fix: reconcile favorite rollbacks before pinned-order pruning

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

* 🧊 fix: Withhold Rerun Controls on Compaction Turns

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* 🎨 fix: Ask the Editor What It Can Edit

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

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

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

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

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

* 🧹 style: Sort the New Imports in Both Editors

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

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

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

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

* 🧪 test: Exercise the Compaction Controls in the Browser

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

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

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

* feat(insights): improve agent filter controls

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

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

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

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

* fix: Use artifact titles for download filenames

* fix: Match artifact filenames to downloaded content

* fix: Preserve raw artifact extensions and GFM headings

* fix: Download complete artifact files and retain filename provenance

* fix: Distinguish cached artifact exports from originals

* fix: Name unnamed artifact originals by their media type

* fix: Recognize legacy CSV MIME in artifact filenames

* fix: preserve context insights across reloads and configuration changes

* fix: retain primary call details when resuming context snapshots

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

* fix: keep resumed output compatible with older clients

---------

Co-authored-by: Ravi Kumar L <upman@users.noreply.github.com>
Co-authored-by: Danny Avila <danny@librechat.ai>
2026-09-11 15:53:29 -04:00
Ravi Kumar L
980f3ede77
🩻 feat: improve agent filter controls for insights (#15807)
Some checks are pending
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Codegraph E2E Votes / vote (full suite) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Client build recovery regression (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
Sync Locize Translations & Create Translation PR / Sync Translation Keys with Locize (push) Waiting to run
Sync Locize Translations & Create Translation PR / Create Translation PR on Version Published (push) Blocked by required conditions
* feat(insights): improve agent filter controls

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

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

* test(e2e): allow steer consumption before arm response
2026-09-11 10:54:37 -04:00
Marco Beretta
afaf22f608
🧊 fix: Withhold Rerun Controls on Compaction Turns (#15797)
* 🧊 fix: Withhold Rerun Controls on Compaction Turns

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* 🎨 fix: Ask the Editor What It Can Edit

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

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

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

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

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

* 🧹 style: Sort the New Imports in Both Editors

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

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

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

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

* 🧪 test: Exercise the Compaction Controls in the Browser

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

`SeedMessage` carries `content`, `finish_reason` and `model` so a branch can be
seeded in the shapes the mock model cannot produce — a persisted summary, an
error part, an artifact.
2026-09-11 10:41:50 -04:00
Danny Avila
442d477acf
🛎️ fix: Preflight MCP Readiness for Scheduled Chats (#15782)
* fix: Validate Scheduled MCP Readiness 🕰️

* fix: Keep Schedule Permission Store Failures Retryable

* perf: Parallelize Scheduled MCP Preflight

* fix: Preserve Scheduled MCP Invariants

* fix: Close scheduled MCP recovery gaps

* fix: harden scheduled MCP recovery

* fix: bound scheduled MCP validation

* fix: harden scheduled MCP admission bounds

* fix: align scheduled MCP graph admission

* fix: bound scheduled MCP admission

* fix: align scheduled MCP preflight with runtime

* fix: persist scheduled MCP failure outcomes

* fix: match scheduled MCP runtime semantics

* fix: parallelize scheduled MCP admissions

* fix: mirror scheduled subagent traversal

* fix: enforce scheduled subagent config limits

* fix: bound scheduled MCP initialization

* fix: mirror lazy subagent metadata budgets

* fix: complete scheduled MCP recovery

* fix: attribute missing MCP tools

* fix: harden scheduled MCP admission

* fix: preserve scheduled admission invariants

* fix: retain inaccessible MCP requirements

* fix: make MCP admission recovery durable
2026-09-09 22:18:45 -04:00
James Todaro
3cab71c48a
🧷 ci: Await durable finalization in conversation-management mock e2e (#15791)
- send each turn through sendMessageAndWaitForCompletion so the composer is unlocked before the next Enter
- give the three tests explicit timeouts, matching the chat.spec.ts budgets from #14740
2026-09-09 14:50:57 -04:00
Danny Avila
fed09dacb6
📎 test: Verify Stateful Sandbox Upload Continuity (#14363)
Covers the one leg the credential-free mock suite cannot fake: a file
attached through the UI's Code Environment target must land in the live
Code API, get delivered into the sandbox, and stay readable across turns.

- fake-model: E2E_EXEC_UPLOADED:/E2E_EXEC_PERSIST: markers emit real
  bash_tool calls through the production tool pipeline (the sandbox
  surface stateful agents register; execute_code stays host-wired and
  never appears in the tool registry), plus an env-gated dump of each
  run's advertised tools for future spec authoring
- spec: attach uploads a CSV to the Code API, turn 1 reads it back from
  /mnt/data and drops a proof file no upload contained, turn 2 (sent
  without an attachment) reads both — only possible when the run reuses
  the same stateful runtime session
- e2e config: agents capabilities gain stateful_code_sessions, and the
  mock profile pins CHECK_BALANCE=false so a developer's local .env can
  never fail every send with zero-balance users
- skips unless LIBRECHAT_CODE_BASEURL is provided (kept out of CI)
2026-09-09 00:35:28 -04:00
Danny Avila
ec15075dc8
🚚 feat: Route Attachments and Provision Tools Lazily (#15763) 2026-09-08 23:28:52 -04:00
Danny Avila
6f05678bfc
🧐 feat: Restore Interactive Tool Approval Review (#15717)
* 🧐 feat: Review Pending Tool Actions in the Composer (#15714)

* feat: add interactive approval review to the composer

* fix: Harden interactive approval boundaries

* fix: Bound every approval display label

* test: exercise composer approval review in BYOM acceptance

* fix: reveal all directional approval controls

* fix: canonicalize code approval targets across replicas

* style: sort resumable approval test imports

* test: Exercise Coexisting Approval Surfaces

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

This reverts commit 5f79ded9553405b697e837e1976a70accbfc3fc3.

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

This reverts commit 52c7d9c7453da0168338bcf79494927f561a92a0.

* chore: bump agents sdk to v3.8.2
2026-09-07 22:02:56 -04:00
Danny Avila
b5c5624f13
🕹 fix: Keep Composer Focus Off Clicked Controls So Menus Can Close (#15669)
Some checks are pending
Docker Dev Images Build / publish (push) Waiting to run
Sync Helm Chart Tags / Ignore non-main push (push) Waiting to run
Sync Helm Chart Tags / Sync chart tags (push) Waiting to run
* fix: dismiss menus when composer focus changes

* 🎯 fix: Keep Composer Focus Off Clicked Controls So Menus Can Close

Ariakit records document.activeElement at open time as a menu's disclosure.
The composer surface focused the textarea on every bubbled click, including
the click that opened the Tools or attach menu, so the textarea became the
disclosure and the menu ignored every later textarea interaction. The Tools
menu went from modal to non-modal in #14979 (v0.8.8-rc2), which removed the
backdrop that had been closing it anyway.

Hoists the interactive-target selector, adds label to it, documents the
mechanism at the guard, and gives the composer surface a stable test id so
the empty-space focus test no longer depends on a utility class. Adds a test
that opens a menu and proves a textarea click closes it.

Closes #15624

* 🎯 fix: Restore Textarea Focus After Send, Steer and Stop Controls

The interactive-target guard also skipped the bubbled click that used to
return focus to the textarea after a mouse click on send. The send button
is then disabled or swapped for the stop control, leaving focus on body.
Route that refocus through a shared helper called from the form submit,
the during-run consume callbacks, and the stop button, keeping the
touchscreen exception. Adds a test that a mouse click on send leaves the
textarea focused; it fails without the submit refocus.

* 🎯 refactor: Exempt Only Focus-Owning Targets From the Composer Refocus

The blanket 'button' exemption inverted the surface's long-standing
behavior for every control, so each control that relied on the bubbled
refocus (send, stop, steer, badge toggles) became its own regression.
State the rule the other way round: the surface refocuses the textarea
after any click except on a target that owns focus itself (links, form
fields, labels) or opens or belongs to a popup (aria-haspopup disclosures
and menu/listbox/dialog content, which React bubbles through portals).
Matches that contain the surface itself are ignored so a host dialog can
never disable the refocus. Drops the explicit refocus calls, which plain
buttons no longer need.

* 🎯 fix: Restore Textarea Focus From Popup Actions That Consume the Composer

The during-run alternate actions live in an Ariakit hovercard, which is
portaled dialog content and therefore exempt from the surface's bubbled
refocus. Choosing Steer or Queue there consumed the text and unmounted
both the button and the hovercard, leaving focus on body. Actions that
consume the composer from inside a popup now restore focus themselves
through a shared consume callback. Adds a ChatForm test that opens the
real hovercard with screen-coordinate mouse travel, chooses Queue, and
asserts the textarea is focused; it fails without the refocus.

* 🧪 test: Expect Escape to Return Focus to the Quote Pill

The quotes e2e asserted that Escape on the selections popover focused
the textarea. That held only through the bug this branch fixes: Enter on
the pill fired a click that bubbled to the composer surface, the textarea
took focus mid-open and was recorded as the popover's disclosure, and
Ariakit then 'restored' focus to it on hide. With the surface no longer
stealing focus from a popup disclosure, the pill is the disclosure and
Escape returns focus to it, as PendingQuoteChips documents. The guard
against focus landing on body is unchanged.

* 🎯 fix: Restore Focus When Removing a Quote From the Selections Popup

The remove buttons in the selections popup are popup content, so the
surface no longer refocuses the textarea for them, and the clicked
button unmounts with its row. Removing the second-to-last quote also
unmounts the popup and its pill, so Ariakit has nothing to restore focus
to and it fell to body. The chip now restores focus itself: to the
textarea when the popup collapses, otherwise to the popup so keyboard
users stay inside it. Adds tests for both, plus one proving the primary
during-run submit still refocuses through the surface (the hovercard
anchor carries no popup attributes, so it bubbles like any button).

* ♿ fix: Keep Quote Removal Focus Guarded and on a Visible Control

Route the chip's collapse refocus through the composer's guarded helper
so a tap on a touchscreen does not raise the keyboard, and after removing
one of several quotes focus the remove button now at the same row (or
the last one) once React has re-rendered the list, instead of the
outline-less popup container. Tests pin both; each fails without its fix.

* test: make quote popup focus checks deterministic

---------

Co-authored-by: Jackson Riding <99007683+jacksonriding@users.noreply.github.com>
2026-09-06 17:31:16 -04:00
Danny Avila
deb3dad265
🫳 fix: Let the Composer Column Shrink Below a Queued Row's Text (#15665)
A queued follow-up or failed steer row longer than the composer widened
the whole composer column to the text's own length instead of truncating:
the row's controls left the viewport, the composer ran under the side
panel, and the chat pane grew a horizontal scrollbar.

The row's text is `nowrap` with `min-w-0 flex-1 truncate`, but nothing
caps its width, so its min-content width propagates up through the chips
column and the composer surface to the form's `flex-1` child. That child
is a flex item with `min-width: auto`, so its automatic minimum becomes
the text's width and the form cannot shrink it. The quote and skill chips
beside it never trigger this only because each carries a fixed `max-w-`.

`min-w-0` on that column wrapper lets it shrink to the form again;
everything below it is already `w-full` or `overflow-hidden`, so the text
truncates where it was meant to. The queue e2e test now queues a paragraph
wider than the composer and asserts the row ends inside the form with its
remove button fully in the viewport; it fails on the previous build by
2119px and passes on this one.
2026-09-06 15:32:01 -04:00
Marco Beretta
c9d208ad3b
🧰 feat: Unify Tool Activity, Reasoning, Search, and Agent Workflows (#14546)
* feat: Group Reasoning with Tool Calls and Polish Activity UI

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

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

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

* fix(client): handle singular grouped tool labels

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* feat(client): richer web search source list

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* style(client): align tool call import order

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

* test: stabilize full test suite

* test(e2e): align assertions with action groups

* fix: preserve tool run and answer state

* fix: sync subagent and answer handoffs

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

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

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

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

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

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

* Fix ask answer handoff and OAuth warnings

* fix(client): address Codex review findings

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* fix: address remaining Codex findings after dev rebase

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

* Resolve follow-up review findings

* Scope grouped background verdicts by execution step

* Fix canonical artifact ownership and frontend review regressions

* Fix terminal answer handoff and encoded edit previews

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

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

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

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

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

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

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

Two things a fold could swallow.

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

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

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

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

The stash carries its conversation now, and recovery keys on that, so a
revisit is a hand-back like any other exit. Only the exit this hook
armed knows what the composer held when the resume started; on a revisit
an empty composer is the only target that cannot overwrite something
newer, and either way the entry is dropped.
2026-09-06 14:56:50 -04:00
Danny Avila
a5932cb039
🎖️ perf: Promote Flat Thread Rendering to Default (#15660)
* 🧵 feat(client): Make the Flat Thread Renderer the Default

The flat message-thread renderer becomes the default; the recursive
MultiMessage path stays reachable with VITE_FLAT_THREAD=false at build
time or LC_FLAT_THREAD=false in localStorage as an escape hatch.

* 🧪 test(e2e): Differential Check of the Two Thread Renderers

Builds one conversation through the real pipeline with the content shapes
the seeded benchmarks never produce (a regenerated branch, reasoning,
markdown with a table and code, a provider attachment) and one with
detached subagent activity, then renders each with the flat list and the
recursive tree in turn. Both must produce the same transcript, sibling
counters, attachments and activity groups, before and after cycling a
branch. Also adds a benchmark config that runs the tree lane against the
built client for production-minified numbers.
2026-09-06 18:31:08 +00:00
Marco Beretta
971e076015
🎛 refactor: Replace Agent Skills Toggles With a Three-Way Mode Control (#15520)
* refactor: replace agent skills toggles with a three-way mode control

The Skills section in the agent builder exposed one dependent choice as two
peer switches. "Use all skills" only meant anything while "Enable skills" was
on, and turning it on hid the skill list, so the user could not see what "all"
covered. Two Add affordances competed for the same action and both labels
leaned on a tooltip to explain themselves.

Replace both switches with a single segmented control over the SkillsScope
enum that already existed. Off, All, and Selected now write skills_enabled and
skills_scope outright, so the mode is the only source of truth for catalog
exposure and the allowlist survives a round trip through All.

Extract the section into SkillsSection. That drops the badgeText, showAdd,
showBody, and children props SelectedSection only carried to bend the tools
layout into a skills layout, and it retires skillsSelectionTransition, which
inferred the capability flags from the allowlist length and flipped skills off
whenever the last skill was removed.

All mode reports how many skills the deployment exposes and expands a
read-only list, so the catalog is never hidden. Selected mode keeps one Add
affordance: the dashed card while nothing is chosen, a header button once rows
exist.

Legacy agents keep loading through resolveAgentSkillsScope. The one ambiguous
persisted shape, skills_enabled with no explicit scope, is normalized on load
without dirtying the form so the next save records the mode explicitly.

Also give the shared Radio the roving tabindex and arrow key handling a
radiogroup owes its users; every segment was previously its own tab stop with
no way to change the selection from the keyboard.

* chore: add temporary PR comparison screenshots

* chore: drop temporary PR comparison screenshots

* fix: address PR review bot findings on the skills mode control

Codex (P1):
- Compare the resolved mode, not the raw persisted scope, before treating a
  segment click as a no-op. An agent left with `skills_enabled: false` and a
  retained `skills_scope` renders as Off, so matching on the raw field
  swallowed the click that re-enables it while the shared Radio moved its own
  selection, leaving the form clean and the disabled state persisted.
- Exempt explicit scopes from the legacy allowlist normalization in
  AgentSelect. Off deliberately keeps the allowlist so returning to Selected
  restores it, and flipping `skills_enabled` there persisted skills-enabled on
  an agent shown as Off, which skillDeps reads as permission to inject the
  skill-authoring tools.

Codex (P2):
- Report a failed catalog request instead of rendering it as an empty catalog.
  All mode showed "0 skills available" over an empty list when /api/skills
  failed; it now renders the picker's alert with a retry.
- Stop paging the whole catalog before the list is opened. Merely viewing an
  All-scoped agent walked every cursor at 100 records a page and retained each
  summary. Pagination now waits for the expansion, and the header reports the
  loaded count as a floor while more pages remain.
- Honor an explicit `skills_scope` in both skill cleanup paths. Deleting the
  last allowlisted skill, or pruning a dangling id on save, forced
  `skills_enabled` to false without consulting the scope, so an All-scoped
  agent that had once picked a single skill was silently switched off. The
  fail-closed inference now applies only to legacy agents that persist no
  scope at all.

Copilot:
- Skip the onChange when Home or End lands on the already-checked segment.
  Focus still follows the key; only a selection that does not move stops
  firing a form write.

* fix: address second round of PR review bot findings

Codex (P1):
- Normalize authoring left on under a resolved Off. An agent carrying
  `skills_enabled: false` with `skill_authoring_enabled: true` renders as Off,
  yet skillDeps enables the skill-authoring tools for either flag, so it ran
  with skills the section reported as disabled. Clicking the already-selected
  Off segment is a no-op, so nothing ever cleared it. The section now clears
  the flag on load without dirtying the form, matching what selecting Off
  already writes.

Codex (P2):
- Apply the scope-aware pruning in createAgent and revertAgentVersion too, not
  only updateAgent. Restoring an All-scoped version whose skills have since
  been deleted silently came back as Off, and createAgent had the same
  unconditional branch for ids that go stale before the write lands.
- Collapse the duplicate first-page skills request. ToolsSection listed skills
  through useListSkillsQuery while the section and the picker used
  useSkillsInfiniteQuery, so the same endpoint was fetched under two React
  Query keys and could not be deduplicated. All three consumers now share the
  infinite query, which leaves one cache entry instead of two.

Also sorts the imports the repo's checker flagged in SkillsSection,
ToolsSection and the section's spec.

* fix: clear the skills master flag under a resolved Off

`skills_enabled: true` with `skills_scope: none` is a shape the API accepts,
and the resolver reports it as Off. `skillDeps` reads the master flag on its
own as permission to expose the skill-authoring tools, so the agent ran with a
capability the section said was disabled, and because clicking the
already-selected Off segment is a no-op there was no way to clear it without
cycling through another mode.

The normalization that already cleared `skill_authoring_enabled` now clears
both flags whenever the resolved mode is Off, still without dirtying the form.
Neither write fires while a catalog mode is active.

* fix: disable skills for an explicit none scope in allowlist cleanup

The scope-aware fail-closed rule exempted every explicit scope, which spared
one shape it should not have: `skills_enabled: true` with `skills_scope: none`.
The API accepts that combination, the builder renders it as Off, and skillDeps
reads the master flag on its own as permission to expose the skill-authoring
tools. Cleanup runs server side without the builder mounted, so the frontend
normalization cannot repair it.

Only `all` and `selected` opt out now, since each already defines what an
empty allowlist means. The three self-heal paths in agent.ts share a
`requiresSkillsDisable` predicate, and the Mongo filter in skill.ts uses
`$nin: [all, selected]`, which still matches an absent field for legacy
agents.

* test: align the skills e2e spec with the explicit-mode contract

Three assertions still encoded the removed toggle behavior:

- The remove button is labelled `Remove {name}` in the new section, not
  `Remove from agent`, so both removal steps waited 180s for a button that no
  longer exists. That was the timeout, not a failed expectation.
- Emptying the allowlist no longer infers Off. The save writes `skills: []`
  and leaves the mode at Selected, which resolves to no skills at runtime, so
  the spec now asserts `skills_enabled: true` with `skills_scope: 'selected'`
  and keeps the existing proof that the picker and the run expose nothing.
- All leaves `skills` untouched, so a fresh agent serializes no allowlist at
  all rather than an empty one: `composeAgentUpdatePayload` always carries the
  four skill fields and `JSON.stringify` drops the undefined ones. Create and
  Off now assert `skills_scope` instead of an empty array.

Adds `skills_scope` to the spec's payload and detail types.

* fix: address third round of PR review bot findings

All three are P2 accuracy and cost issues in All mode:

- Count only the skills the runtime would inject. The list endpoint returns
  every skill the user can VIEW, while catalog resolution filters each through
  `resolveSkillActive`, so a shared skill left inactive was counted and listed
  as available even though the agent never receives it. The section now shares
  the `isActive` predicate the chat-side picker already filters on, so the
  count cannot promise more than the runtime delivers.
- Report loading instead of an empty catalog. With a cold query `data` is
  undefined and the count derived to "0 skills available", presenting an empty
  deployment while it was merely loading.
- Skip the allowlist lookups outside Selected. `useResolvedSkills` issues one
  `getSkill` per allowlisted id missing from the first catalog page, and since
  All now retains previous picks, merely viewing such an agent could fire
  hundreds of requests for rows that mode never renders. The fallback is gated
  on Selected, where the rows exist.

* fix: gate the All catalog on resolved skill states

`useSkillActiveState` substitutes an empty override map while its own request
is in flight and after it fails, so `isActive` reports every skill active in
both states. The section consumed the predicate but discarded the status, so a
deliberately deactivated owned or deployment skill was counted and listed as
available: briefly during load, and permanently after an error.

The count now waits for both requests, and a failure in either renders the
alert instead of a count the runtime would not honor. Retry refetches both,
which needed the hook to expose its `refetch`.

* fix: resolve the config behind defaultActiveOnShare before filtering

`useSkillActiveState` reads `defaultActiveOnShare` from the interface config
and falls back to `false` while that request is pending or after it fails, so
a deployment configured with `true` had its shared skills filtered out of the
All count until the config landed, and permanently on error. The section only
gated on the skills and skill-states queries.

Both dependencies feed `isActive`, so the hook now reports them as one
signal: `isLoading` and `isError` cover the override map and the config
alike, and `refetch` retries both. A consumer gating on the pair can no
longer miss a dependency, which is how the previous gap arose. The section is
the only consumer of those flags.

Also composes the retry from the shared `Button` (`outline`, `sm`), matching
the picker's own retry instead of a feature-local recipe.

* fix: report what the All catalog loaded, not a lower bound

`hasNextPage` tracks raw pagination while the rows are filtered to the
runtime-active skills, so the two disagree: 30 active skills followed only by
deactivated ones made the header read "30+ skills available" when 30 was the
true total, and it stayed wrong until the user expanded the list and finished
paging.

While pages remain the header now describes what has been loaded rather than
claiming a floor on what is available, so it cannot overstate the catalog. The
exact "N skills available" phrasing still lands once the catalog is complete.
`com_ui_skills_available_count_more` is replaced by singular and plural loaded
keys.
2026-09-06 03:32:56 +02:00
Danny Avila
3d085b227d
🛰️ feat: Show BYOM Worker Readiness (#15618)
* feat: Show BYOM worker readiness

* test: Exercise approved BYOM commands end to end

* test: Wait for BYOM worker readiness
2026-09-04 19:02:35 -04:00