From c9d208ad3bb68127daccecd9076b5b156c0110df Mon Sep 17 00:00:00 2001 From: Marco Beretta <81851188+berry-13@users.noreply.github.com> Date: Sun, 6 Sep 2026 20:56:50 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=A7=B0=20feat:=20Unify=20Tool=20Activity,?= =?UTF-8?q?=20Reasoning,=20Search,=20and=20Agent=20Workflows=20(#14546)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 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. --- .github/workflows/codegraph-select.yml | 2 +- .../agents/__tests__/callbacks.spec.js | 68 +++ .../agents/__tests__/openai.spec.js | 3 + .../agents/__tests__/responses.unit.spec.js | 3 + api/server/controllers/agents/callbacks.js | 53 +- api/server/controllers/agents/openai.js | 5 +- api/server/controllers/agents/responses.js | 7 +- .../routes/agents/__tests__/responses.spec.js | 20 +- api/server/services/Tools/search.js | 6 + api/server/services/Tools/search.spec.js | 33 ++ client/src/components/Chat/ChatView.tsx | 103 ++-- .../Chat/Input/AskUserQuestionPopover.tsx | 143 +++--- .../Messages/Content/ActivityPhaseGroup.tsx | 11 +- .../Chat/Messages/Content/AgentHandoff.tsx | 216 ++++++-- .../Chat/Messages/Content/ApprovalContext.tsx | 47 +- .../Chat/Messages/Content/AskUserQuestion.tsx | 193 ++++--- .../Messages/Content/AskUserQuestions.tsx | 18 +- .../Chat/Messages/Content/CodeAnalyze.tsx | 2 +- .../Chat/Messages/Content/ContentParts.tsx | 21 +- .../Chat/Messages/Content/MemoryArtifacts.tsx | 190 +++---- .../Chat/Messages/Content/MemoryInfo.tsx | 54 +- .../components/Chat/Messages/Content/Part.tsx | 18 + .../Chat/Messages/Content/Parts/BashCall.tsx | 34 +- .../Content/Parts/CodeWindowHeader.tsx | 22 +- .../Chat/Messages/Content/Parts/DiffView.tsx | 217 ++++++++ .../Messages/Content/Parts/ExecuteCode.tsx | 8 +- .../Content/Parts/FileAuthoringCall.tsx | 149 +++--- .../Messages/Content/Parts/MemoryCall.tsx | 154 ++++++ .../Content/Parts/PendingSkillCall.tsx | 2 +- .../Messages/Content/Parts/ReadFileCall.tsx | 13 +- .../Chat/Messages/Content/Parts/Reasoning.tsx | 281 +++++++++- .../Chat/Messages/Content/Parts/SkillCall.tsx | 15 +- .../Messages/Content/Parts/SubagentCall.tsx | 2 +- .../Chat/Messages/Content/Parts/Summary.tsx | 197 +++---- .../Chat/Messages/Content/Parts/Thinking.tsx | 181 +++---- .../Content/Parts/__tests__/DiffView.test.ts | 105 ++++ .../Parts/__tests__/ExecuteCode.test.tsx | 1 - .../__tests__/FileAuthoringCall.test.tsx | 93 +++- .../Parts/__tests__/MemoryCall.test.tsx | 202 ++++++++ .../Parts/__tests__/PtcToolTrace.test.tsx | 8 +- .../Parts/__tests__/Reasoning.spec.tsx | 57 --- .../Parts/__tests__/ReasoningCompact.test.tsx | 102 ++++ .../Parts/__tests__/SubagentCall.test.tsx | 45 +- .../Content/Parts/__tests__/Summary.test.tsx | 50 ++ .../Chat/Messages/Content/Parts/index.ts | 3 +- .../Chat/Messages/Content/ProgressText.tsx | 14 +- .../Chat/Messages/Content/RetrievalCall.tsx | 28 +- .../Chat/Messages/Content/ToolCall.tsx | 51 +- .../Chat/Messages/Content/ToolCallGroup.tsx | 406 ++++++++++++--- .../Content/ToolOutput/OutputRenderer.tsx | 52 +- .../Messages/Content/ToolOutput/ToolIcon.tsx | 6 + .../__tests__/OutputRenderer.test.tsx | 24 + .../Chat/Messages/Content/WebSearch.tsx | 222 ++++++-- .../__tests__/ActivityPhaseGroup.test.tsx | 38 +- .../Content/__tests__/AgentHandoff.test.tsx | 117 ++++- .../__tests__/ApprovalContext.test.tsx | 10 +- .../__tests__/AskUserQuestion.test.tsx | 64 ++- .../AskUserQuestionCollapse.test.tsx | 31 +- .../ContentParts.integration.test.tsx | 138 ++++- .../Content/__tests__/ContentParts.test.tsx | 1 + .../__tests__/MemoryArtifacts.test.tsx | 52 +- .../Content/__tests__/MemoryInfo.test.tsx | 34 +- .../Content/__tests__/ProgressText.test.tsx | 34 +- .../Content/__tests__/RetrievalCall.test.tsx | 46 ++ .../Content/__tests__/ToolCall.test.tsx | 55 ++ .../Content/__tests__/ToolCallGroup.test.tsx | 481 +++++++++++++++++- .../Content/__tests__/WebSearch.test.tsx | 195 ++++++- .../components/Chat/Messages/Content/auth.tsx | 22 + .../Chat/Messages/Content/disclosure.ts | 3 + .../Chat/Messages/Content/verticals.tsx | 259 ++++++++++ .../components/Chat/Messages/MessageNav.tsx | 2 +- .../components/Chat/Messages/MessageParts.tsx | 4 + .../Chat/Subagents/SubagentActivity.tsx | 4 + .../Chat/Subagents/SubagentConversation.tsx | 4 + client/src/components/Chat/ask/options.tsx | 80 +++ client/src/components/Chat/ask/state.tsx | 50 ++ .../src/components/Messages/Content/Error.tsx | 49 ++ .../Messages/Content/__tests__/Error.spec.tsx | 65 ++- .../src/components/Messages/ContentRender.tsx | 4 + .../__tests__/UploadSkillDialog.spec.tsx | 32 +- .../mobile/__tests__/BottomBar.spec.tsx | 15 +- .../src/hooks/Input/useAskAnswerMode.spec.ts | 421 ++++++++++++--- client/src/hooks/Input/useAskAnswerMode.ts | 362 +++++++++---- .../__tests__/useAttachmentHandler.spec.tsx | 75 ++- .../SSE/__tests__/useStepHandler.spec.ts | 14 +- client/src/hooks/SSE/useAttachmentHandler.ts | 37 ++ client/src/hooks/SSE/useStepHandler.ts | 73 +-- .../src/hooks/useKeyboardShortcuts.spec.tsx | 5 +- client/src/locales/en/translation.json | 48 +- client/src/style.css | 14 + .../utils/__tests__/groupToolCalls.test.ts | 127 ++++- client/src/utils/__tests__/toolLabels.test.ts | 4 + client/src/utils/groupToolCalls.ts | 73 ++- client/src/utils/index.ts | 1 + client/src/utils/morph.ts | 21 + client/src/utils/toolLabels.ts | 6 + e2e/specs/mock/activity-labels.spec.ts | 12 +- e2e/specs/mock/agent-handoffs.spec.ts | 11 +- e2e/specs/mock/tool-approvals.spec.ts | 5 +- .../__tests__/run-summarization.test.ts | 29 ++ packages/api/src/agents/handlers.spec.ts | 28 +- packages/api/src/agents/handlers.ts | 36 +- packages/api/src/agents/run.ts | 28 +- .../src/components/DisclosureChevron.tsx | 29 ++ packages/client/src/components/index.ts | 1 + packages/client/src/theme/registry.spec.ts | 46 ++ packages/client/src/theme/registry.ts | 15 + .../client/src/theme/semanticTokens.spec.ts | 1 + packages/client/src/theme/themes/dark.ts | 1 + packages/client/src/theme/themes/default.ts | 1 + .../src/theme/themes/highContrast.spec.ts | 18 +- .../client/src/theme/themes/highContrast.ts | 2 + packages/client/src/theme/types/index.ts | 3 + .../client/src/theme/utils/applyTheme.spec.ts | 10 +- packages/data-provider/src/config.ts | 8 + .../data-provider/src/types/assistants.ts | 4 + 116 files changed, 6037 insertions(+), 1381 deletions(-) create mode 100644 client/src/components/Chat/Messages/Content/Parts/DiffView.tsx create mode 100644 client/src/components/Chat/Messages/Content/Parts/MemoryCall.tsx create mode 100644 client/src/components/Chat/Messages/Content/Parts/__tests__/DiffView.test.ts create mode 100644 client/src/components/Chat/Messages/Content/Parts/__tests__/MemoryCall.test.tsx delete mode 100644 client/src/components/Chat/Messages/Content/Parts/__tests__/Reasoning.spec.tsx create mode 100644 client/src/components/Chat/Messages/Content/Parts/__tests__/ReasoningCompact.test.tsx create mode 100644 client/src/components/Chat/Messages/Content/Parts/__tests__/Summary.test.tsx create mode 100644 client/src/components/Chat/Messages/Content/ToolOutput/__tests__/OutputRenderer.test.tsx create mode 100644 client/src/components/Chat/Messages/Content/auth.tsx create mode 100644 client/src/components/Chat/Messages/Content/disclosure.ts create mode 100644 client/src/components/Chat/Messages/Content/verticals.tsx create mode 100644 client/src/components/Chat/ask/options.tsx create mode 100644 client/src/components/Chat/ask/state.tsx create mode 100644 client/src/utils/morph.ts create mode 100644 packages/client/src/components/DisclosureChevron.tsx diff --git a/.github/workflows/codegraph-select.yml b/.github/workflows/codegraph-select.yml index e74a86e270..d76d673a8a 100644 --- a/.github/workflows/codegraph-select.yml +++ b/.github/workflows/codegraph-select.yml @@ -59,7 +59,7 @@ jobs: RESP=$(curl -sS --fail-with-body -m 45 -H "Authorization: Bearer $TOKEN" \ -H 'content-type: application/json' --data-binary @body.json "$URL/v1/select"); RC=$? if [ "$RC" -ne 0 ] || [ -z "$RESP" ] || ! echo "$RESP" | jq -e .selected >/dev/null 2>&1; then - note "_codegraph unavailable (curl exit $RC: ${RESP:0:120}); skipped — full CI runs as always_" + note "_codegraph unavailable (curl exit $RC: ${RESP:0:120}); skipped, full CI runs as always_" exit 0 fi diff --git a/api/server/controllers/agents/__tests__/callbacks.spec.js b/api/server/controllers/agents/__tests__/callbacks.spec.js index 34bab04619..1d76042381 100644 --- a/api/server/controllers/agents/__tests__/callbacks.spec.js +++ b/api/server/controllers/agents/__tests__/callbacks.spec.js @@ -8,6 +8,7 @@ jest.mock('nanoid', () => ({ jest.mock('@librechat/api', () => ({ sendEvent: jest.fn(), writeAttachmentEvent: jest.fn(), + createOwnedToolEndHandler: jest.fn((callback) => ({ handle: callback })), GenerationJobManager: { emitChunk: jest.fn(), }, @@ -468,6 +469,73 @@ describe('createToolEndCallback', () => { artifactPromises = []; }); + it('preserves separate owners for final search artifacts with repeated tool-call IDs', async () => { + const toolEndCallback = createToolEndCallback({ req, res, artifactPromises }); + for (const agentId of ['agent-a', 'agent-b']) { + await toolEndCallback( + { + output: { + tool_call_id: 'call_0', + artifact: { + [Tools.web_search]: { + turn: 0, + organic: [{ link: `https://example.com/${agentId}` }], + }, + }, + }, + }, + { run_id: 'run456', thread_id: 'thread789', agent_id: agentId }, + ); + } + const results = await Promise.all(artifactPromises); + expect( + results.map((attachment) => ({ + owner: attachment.agentId, + link: attachment[Tools.web_search].organic[0].link, + })), + ).toEqual([ + { owner: 'agent-a', link: 'https://example.com/agent-a' }, + { owner: 'agent-b', link: 'https://example.com/agent-b' }, + ]); + }); + + it.each(['createToolEndCallback', 'createResponsesToolEndCallback'])( + '%s preserves memory payloads and their execution owner', + async (factoryName) => { + const toolEndCallback = require('../callbacks')[factoryName]({ req, res, artifactPromises }); + await toolEndCallback( + { + output: { + tool_call_id: 'call_0', + artifact: { + [Tools.memory]: { + key: 'project', + type: 'update', + value: 'owned', + }, + }, + }, + }, + { + run_id: 'run456', + thread_id: 'thread789', + agent_id: 'outer-agent', + executingAgentId: 'agent-a', + stepId: 'step-memory-1', + }, + ); + + const [attachment] = await Promise.all(artifactPromises); + expect(attachment).toMatchObject({ + type: Tools.memory, + toolCallId: 'call_0', + agentId: 'agent-a', + stepId: 'step-memory-1', + [Tools.memory]: { key: 'project', type: 'update', value: 'owned' }, + }); + }, + ); + describe('ui_resources artifact handling', () => { it('should process ui_resources artifact and return attachment when headers not sent', async () => { const toolEndCallback = createToolEndCallback({ req, res, artifactPromises }); diff --git a/api/server/controllers/agents/__tests__/openai.spec.js b/api/server/controllers/agents/__tests__/openai.spec.js index 90fdabe516..8c8960b2d5 100644 --- a/api/server/controllers/agents/__tests__/openai.spec.js +++ b/api/server/controllers/agents/__tests__/openai.spec.js @@ -194,6 +194,9 @@ jest.mock('@librechat/api', () => ({ * export or the call throws before the assertions run. */ stripActivityLabelParts: jest.fn((payload) => payload), writeSSE: jest.fn(), + createOwnedToolEndHandler: jest.fn( + (...args) => new (require('@librechat/agents').ToolEndHandler)(...args), + ), createRun: jest.fn().mockResolvedValue({ processStream: mockProcessStream, }), diff --git a/api/server/controllers/agents/__tests__/responses.unit.spec.js b/api/server/controllers/agents/__tests__/responses.unit.spec.js index 584b4c8e56..5ea0d8628a 100644 --- a/api/server/controllers/agents/__tests__/responses.unit.spec.js +++ b/api/server/controllers/agents/__tests__/responses.unit.spec.js @@ -203,6 +203,9 @@ jest.mock('@librechat/api', () => ({ * before SDK formatting; the mock must expose it like any other used * export or the call throws before the assertions run. */ stripActivityLabelParts: jest.fn((payload) => payload), + createOwnedToolEndHandler: jest.fn( + (...args) => new (require('@librechat/agents').ToolEndHandler)(...args), + ), collectReachableAgents: (roots) => { const agents = []; const pending = [...roots]; diff --git a/api/server/controllers/agents/callbacks.js b/api/server/controllers/agents/callbacks.js index c97a196aad..89db7e4509 100644 --- a/api/server/controllers/agents/callbacks.js +++ b/api/server/controllers/agents/callbacks.js @@ -13,7 +13,6 @@ const { const { GraphEvents, GraphNodeKeys, - ToolEndHandler, createContentAggregator, summarizeEvent, } = require('@librechat/agents'); @@ -23,6 +22,7 @@ const { GenerationJobManager, writeAttachmentEvent, createToolExecuteHandler, + createOwnedToolEndHandler, createBackgroundCodeResultHandler: createCodeHarvestHandler, HOST_FILE_AUTHORING_ARTIFACT_KEY, isCodeSessionToolName, @@ -42,6 +42,15 @@ function isCodeArtifactToolOutput(output) { return isCodeSessionToolName(output.name) || isHostFileAuthoringArtifact(output.artifact); } +function getAttachmentOwnership(metadata) { + const agentId = metadata?.executingAgentId ?? metadata?.agentId ?? metadata?.agent_id; + const stepId = metadata?.stepId; + return { + ...(typeof agentId === 'string' && agentId.length > 0 ? { agentId } : {}), + ...(typeof stepId === 'string' && stepId.length > 0 ? { stepId } : {}), + }; +} + function addStatefulWorkspaceChange(attachment, artifact, executionProfile) { if (!attachment || executionProfile !== 'stateful' || !isHostFileAuthoringArtifact(artifact)) { return attachment; @@ -506,7 +515,7 @@ function getDefaultHandlers({ collectedThoughtSignatures, emitTokenUsage, ), - [GraphEvents.TOOL_END]: new ToolEndHandler(toolEndCallback, logger), + [GraphEvents.TOOL_END]: createOwnedToolEndHandler(toolEndCallback, logger), [GraphEvents.ON_RUN_STEP]: { /** * Handle ON_RUN_STEP event. @@ -785,6 +794,23 @@ function getDefaultHandlers({ handlers[GraphEvents.ON_SUMMARIZE_COMPLETE] = { handle: async (_event, data) => { aggregateContent({ event: GraphEvents.ON_SUMMARIZE_COMPLETE, data }); + /** + * Stamped onto the aggregated part for the same reason as + * `runStepStatus` above: an errored round keeps whatever deltas it + * already streamed, and the SDK's aggregator ignores a complete event + * that carries no `summary`, so nothing records the failure. Without + * this the flag exists only on the live client message and a reload + * re-renders the truncated text under "Conversation summarized". + * Resolved through `stepMap` only, so a missing step degrades to the + * old behavior rather than marking an unrelated part. + */ + if (data?.error && contentParts) { + const index = stepMap?.get(data?.id)?.index; + const part = typeof index === 'number' ? contentParts[index] : undefined; + if (part?.type === ContentTypes.SUMMARY) { + part.failed = true; + } + } await emitForJob({ event: GraphEvents.ON_SUMMARIZE_COMPLETE, data, @@ -987,6 +1013,7 @@ function createToolEndCallback({ req, res, artifactPromises, streamId = null, jo (async () => { const attachment = { type: Tools.web_search, + ...getAttachmentOwnership(metadata), messageId: metadata.run_id, toolCallId: output.tool_call_id, conversationId: metadata.thread_id, @@ -1009,6 +1036,7 @@ function createToolEndCallback({ req, res, artifactPromises, streamId = null, jo (async () => { const attachment = { type: Tools.memory, + ...getAttachmentOwnership(metadata), messageId: metadata.run_id, toolCallId: output.tool_call_id, conversationId: metadata.thread_id, @@ -1350,6 +1378,7 @@ function createResponsesToolEndCallback({ req, res, tracker, artifactPromises }) const attachment = { type: Tools.web_search, toolCallId: output.tool_call_id, + ...getAttachmentOwnership(metadata), [Tools.web_search]: { ...output.artifact[Tools.web_search] }, }; // For Responses API, always emit attachment during streaming @@ -1364,6 +1393,26 @@ function createResponsesToolEndCallback({ req, res, tracker, artifactPromises }) ); } + if (output.artifact[Tools.memory]) { + artifactPromises.push( + (async () => { + const attachment = { + type: Tools.memory, + toolCallId: output.tool_call_id, + ...getAttachmentOwnership(metadata), + [Tools.memory]: output.artifact[Tools.memory], + }; + if (res.headersSent && !res.writableEnded) { + writeResponsesAttachment(res, tracker, attachment, metadata); + } + return attachment; + })().catch((error) => { + logger.error('Error processing memory artifact content:', error); + return null; + }), + ); + } + if (output.artifact.content) { /** @type {FormattedContent[]} */ const content = output.artifact.content; diff --git a/api/server/controllers/agents/openai.js b/api/server/controllers/agents/openai.js index b57cce7493..de275905ad 100644 --- a/api/server/controllers/agents/openai.js +++ b/api/server/controllers/agents/openai.js @@ -1,6 +1,6 @@ const { nanoid } = require('nanoid'); const { logger } = require('@librechat/data-schemas'); -const { Callback, ToolEndHandler, formatAgentMessages } = require('@librechat/agents'); +const { Callback, formatAgentMessages } = require('@librechat/agents'); const { EModelEndpoint, ResourceType, @@ -56,6 +56,7 @@ const { getUserFacingProviderError, getRemoteAgentPermissions, createToolExecuteHandler, + createOwnedToolEndHandler, buildNonStreamingResponse, createOpenAIStreamTracker, resolveAgentScopedSkillIds, @@ -1001,7 +1002,7 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => { }, on_run_step_completed: createHandler(), // Use proper ToolEndHandler for processing artifacts (images, file citations, code output) - on_tool_end: new ToolEndHandler(toolEndCallback, logger), + on_tool_end: createOwnedToolEndHandler(toolEndCallback, logger), on_chain_stream: createHandler(), on_chain_end: createHandler(), on_agent_update: createHandler(), diff --git a/api/server/controllers/agents/responses.js b/api/server/controllers/agents/responses.js index 4903abf569..c3632f89c6 100644 --- a/api/server/controllers/agents/responses.js +++ b/api/server/controllers/agents/responses.js @@ -1,7 +1,7 @@ const { nanoid } = require('nanoid'); const { v4: uuidv4 } = require('uuid'); const { logger } = require('@librechat/data-schemas'); -const { Callback, ToolEndHandler, formatAgentMessages } = require('@librechat/agents'); +const { Callback, formatAgentMessages } = require('@librechat/agents'); const { EModelEndpoint, ResourceType, @@ -53,6 +53,7 @@ const { getSafeErrorMetadata, getUserFacingProviderError, createToolExecuteHandler, + createOwnedToolEndHandler, resolveRecursionLimit, getRemoteAgentPermissions, resolveAgentScopedSkillIds, @@ -1155,7 +1156,7 @@ const executeResponse = async (envelope, { req, res }) => { } }, }, - on_tool_end: new ToolEndHandler(toolEndCallback, logger), + on_tool_end: createOwnedToolEndHandler(toolEndCallback, logger), on_run_step_completed: { handle: () => {} }, on_chain_stream: { handle: () => {} }, on_chain_end: { handle: () => {} }, @@ -1368,7 +1369,7 @@ const executeResponse = async (envelope, { req, res }) => { } }, }, - on_tool_end: new ToolEndHandler(toolEndCallback, logger), + on_tool_end: createOwnedToolEndHandler(toolEndCallback, logger), on_run_step_completed: { handle: () => {} }, on_chain_stream: { handle: () => {} }, on_chain_end: { handle: () => {} }, diff --git a/api/server/routes/agents/__tests__/responses.spec.js b/api/server/routes/agents/__tests__/responses.spec.js index 4d83219b84..cddeaf95b7 100644 --- a/api/server/routes/agents/__tests__/responses.spec.js +++ b/api/server/routes/agents/__tests__/responses.spec.js @@ -4,6 +4,9 @@ * Tests the /v1/responses endpoint against the Open Responses specification * compliance tests. Uses real Anthropic API for LLM calls. * + * Run with: + * NODE_OPTIONS=--experimental-vm-modules RUN_RESPONSES_LIVE_TESTS=1 npx jest responses.spec --runInBand + * * @see https://openresponses.org/specification * @see https://github.com/openresponses/openresponses/blob/main/src/lib/compliance-tests.ts */ @@ -19,11 +22,10 @@ const originalEnv = { process.env.CREDS_KEY = '0123456789abcdef0123456789abcdef'; process.env.CREDS_IV = '0123456789abcdef'; -/** Skip tests if ANTHROPIC_API_KEY is not available */ -const SKIP_INTEGRATION_TESTS = !process.env.ANTHROPIC_API_KEY; -if (SKIP_INTEGRATION_TESTS) { - console.warn('ANTHROPIC_API_KEY not found - skipping integration tests'); -} +const shouldRunLive = + process.env.RUN_RESPONSES_LIVE_TESTS === '1' && + process.env.ANTHROPIC_API_KEY != null && + process.env.ANTHROPIC_API_KEY !== ''; jest.mock('meilisearch', () => ({ MeiliSearch: jest.fn().mockImplementation(() => ({ @@ -69,9 +71,13 @@ jest.mock('~/app/clients/tools', () => ({ jest.mock('~/config', () => ({ createMCPServersRegistry: jest.fn(), + getMCPServersRegistry: jest.fn().mockReturnValue({ + ensureConfigServers: jest.fn().mockResolvedValue({}), + }), createMCPManager: jest.fn().mockResolvedValue({ getAppToolFunctions: jest.fn().mockResolvedValue({}), }), + getMCPManager: jest.fn().mockReturnValue({}), })); const express = require('express'); @@ -369,9 +375,9 @@ async function createThinkingAgent(overrides = {}) { }); } -const describeWithApiKey = SKIP_INTEGRATION_TESTS ? describe.skip : describe; +const describeIfLive = shouldRunLive ? describe : describe.skip; -describeWithApiKey('Open Responses API Integration Tests', () => { +describeIfLive('Open Responses API Integration Tests', () => { // Increase timeout for real API calls jest.setTimeout(120000); diff --git a/api/server/services/Tools/search.js b/api/server/services/Tools/search.js index c6e031e9ee..e0ded1268b 100644 --- a/api/server/services/Tools/search.js +++ b/api/server/services/Tools/search.js @@ -34,6 +34,8 @@ function createOnSearchResults(res, streamId = null, jobCreatedAt) { sourceMap: new Map(), searchResultData: undefined, toolCallId: undefined, + agentId: undefined, + stepId: undefined, attachmentName: undefined, messageId: undefined, conversationId: undefined, @@ -83,6 +85,8 @@ function createOnSearchResults(res, streamId = null, jobCreatedAt) { } context.toolCallId = runnableConfig.toolCall.id; + context.agentId = runnableConfig.metadata.agent_id ?? runnableConfig.metadata.agentId; + context.stepId = runnableConfig.toolCall?.stepId; context.messageId = runnableConfig.metadata.run_id; context.conversationId = runnableConfig.metadata.thread_id; context.attachmentName = `${runnableConfig.toolCall.name}_${context.toolCallId}_${nanoid()}`; @@ -132,6 +136,8 @@ function buildAttachment(context) { return { messageId: context.messageId, toolCallId: context.toolCallId, + agentId: context.agentId, + stepId: context.stepId, conversationId: context.conversationId, name: context.attachmentName, type: Tools.web_search, diff --git a/api/server/services/Tools/search.spec.js b/api/server/services/Tools/search.spec.js index 8925d84062..adb864ab7b 100644 --- a/api/server/services/Tools/search.spec.js +++ b/api/server/services/Tools/search.spec.js @@ -28,6 +28,7 @@ describe('createOnSearchResults', () => { toolCall: { id: 'tool-call-1', name: 'web_search', + stepId: 'step-search-1', turn: 0, }, }; @@ -53,6 +54,7 @@ describe('createOnSearchResults', () => { data: expect.objectContaining({ messageId: 'response-1', toolCallId: 'tool-call-1', + stepId: 'step-search-1', conversationId: 'conversation-1', }), }, @@ -60,4 +62,35 @@ describe('createOnSearchResults', () => { ]); } }); + + it('keeps repeated search calls owned by their handoff agent through highlights', () => { + const snapshots = []; + const res = { + headersSent: true, + write: (event) => snapshots.push(JSON.parse(event.split('\ndata: ')[1])), + }; + for (const agentId of ['agent-a', 'agent-b']) { + const callbacks = createOnSearchResults(res); + callbacks.onSearchResults( + { + success: true, + data: { organic: [{ link: `https://example.com/${agentId}` }], topStories: [] }, + }, + { + metadata: { agent_id: agentId, run_id: 'response-1', thread_id: 'conversation-1' }, + toolCall: { id: 'call_0', name: 'web_search', turn: 0 }, + }, + ); + callbacks.onGetHighlights(`https://example.com/${agentId}`); + } + + expect(snapshots.map(({ agentId }) => agentId)).toEqual([ + 'agent-a', + 'agent-a', + 'agent-b', + 'agent-b', + ]); + expect(snapshots[1].web_search.organic[0].processed).toBe(true); + expect(snapshots[3].web_search.organic[0].processed).toBe(true); + }); }); diff --git a/client/src/components/Chat/ChatView.tsx b/client/src/components/Chat/ChatView.tsx index c0bceec1b8..7647e99bea 100644 --- a/client/src/components/Chat/ChatView.tsx +++ b/client/src/components/Chat/ChatView.tsx @@ -17,6 +17,7 @@ import { import { ChatContext, AddedChatContext, ChatFormProvider, useFileMapContext } from '~/Providers'; import ConversationStarters from './Input/ConversationStarters'; import { useGetMessagesByConvoId } from '~/data-provider'; +import { AskAnswerHostProvider } from './ask/state'; import MessagesView from './Messages/MessagesView'; import Presentation from './Presentation'; import ChatForm from './Input/ChatForm'; @@ -41,6 +42,7 @@ function ChatView({ index = 0, project }: { index?: number; project?: TChatProje const localize = useLocalize(); const rootSubmission = useRecoilValue(store.submissionByIndex(index)); const isSubmitting = useRecoilValue(store.isSubmittingFamily(index)); + const saveDrafts = useRecoilValue(store.saveDrafts); const centerFormOnLanding = useRecoilValue(store.centerFormOnLanding); const methods = useForm({ @@ -126,58 +128,65 @@ function ChatView({ index = 0, project }: { index?: number; project?: TChatProje const isSubagentThreadReadOnly = activeSubagentThread != null; return ( - - - - -
-

{pageHeading}

-
- <> -
- {content} + + + + + +
+

{pageHeading}

+
+ <>
- {isLandingPage && } - {isSubagentThreadReadOnly ? ( -
- {localize('com_ui_subagent_thread_read_only')} -
- ) : ( - - )} - {!isLandingPage &&
} + {content} + {/* Named + opaque so a view transition (the ask_user_question + popover ⇄ chat-card morph) paints the whole composer band + over the travelling card instead of letting it show + through below the composer. The background matches the + page, so normal rendering is unchanged. */} +
+ {isLandingPage && } + {isSubagentThreadReadOnly ? ( +
+ {localize('com_ui_subagent_thread_read_only')} +
+ ) : ( + + )} + {!isLandingPage &&
} +
-
- {isLandingPage &&
} - -
- - - - + {isLandingPage &&
} + +
+
+
+
+
+ ); } diff --git a/client/src/components/Chat/Input/AskUserQuestionPopover.tsx b/client/src/components/Chat/Input/AskUserQuestionPopover.tsx index 66c73e2654..1c967d48d0 100644 --- a/client/src/components/Chat/Input/AskUserQuestionPopover.tsx +++ b/client/src/components/Chat/Input/AskUserQuestionPopover.tsx @@ -1,12 +1,12 @@ import { memo, useEffect, useRef } from 'react'; import { useWatch } from 'react-hook-form'; -import { Button } from '@librechat/client'; -import { Check, ChevronDown, CornerDownLeft, TriangleAlert, X } from 'lucide-react'; +import { Button, TooltipAnchor } from '@librechat/client'; +import { ChevronDown, CornerDownLeft, TriangleAlert } from 'lucide-react'; import AskUserQuestions from '~/components/Chat/Messages/Content/AskUserQuestions'; import useAskAnswerMode from '~/hooks/Input/useAskAnswerMode'; +import AskOptions from '~/components/Chat/ask/options'; import { useChatFormContext } from '~/Providers'; import { useLocalize } from '~/hooks'; -import { cn } from '~/utils'; /** * Composer popover for a live `ask_user_question` pause. Single-select rows @@ -16,10 +16,10 @@ import { cn } from '~/utils'; * Submit confirms — * folding in any free-form text typed in the composer, exactly like Enter * would. The footer hint is a button that focuses the composer — the - * free-form answer box. Collapse (chevron) hides the popover but keeps - * answer mode live via the chat card; × dismisses it entirely. Pure - * rendering off {@link useAskAnswerMode}; disappears the moment an answer - * submits from any surface, and locks while one is in flight. + * free-form answer box. The chevron moves the question to the chat card and + * releases the composer (the card's chevron moves it back). Pure rendering + * off {@link useAskAnswerMode}; disappears the moment an answer submits from + * any surface, and locks while one is in flight. */ function AskUserQuestionPopoverContent({ conversationId, @@ -43,7 +43,7 @@ function AskUserQuestionPopoverContent({ function AskUserQuestionsPopoverPanel({ ask }: { ask: ReturnType }) { const localize = useLocalize(); - const { liveAsk, collapse, dismiss } = ask; + const { liveAsk, collapse } = ask; const questions = liveAsk?.questions; if (liveAsk == null || questions == null || questions.length === 0) { return null; @@ -59,24 +59,21 @@ function AskUserQuestionsPopoverPanel({ ask }: { ask: ReturnType -
- - -
+ +