mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-08-29 05:20:49 +00:00
🖥️ feat: Stream PTC Inner Tool Calls as a CLI-Style Trace (#15115)
* 🖥️ feat: Stream PTC Inner Tool Calls as a CLI-Style Trace Programmatic tool calling runs a whole program inside the sandbox, and the tool calls that program makes open no run step of their own. The card showed one running spinner for the entire execution, with no sign of what the code was doing. Emit a new `on_ptc_tool_call` step event for each inner invocation — once on dispatch, once on settle — and render them under the code as a terminal-style trace: status glyph, tool identity, argument preview, duration, with a failure message printed under the call that produced it. The seam is the tool map the sandbox bridge resolves inner calls against. `instrumentPtcToolMap` proxies `invoke` on each entry and leaves every other property (name, schema, mcp) passing straight through, so nothing about execution changes and emission failures can never fail a tool call. Client state is a per-tool-call Recoil atom keyed like the sandbox-starting and subagent atoms — live for the session, cleared on conversation switch so a finished program's trace stays readable. * 🩹 fix: Address Codex Review on the PTC Tool Trace Five findings, all confirmed against the source before fixing. Scope the trace atoms to a message occurrence. The hook already documents that providers repeat a tool_call_id across turns and even within one message, and `call_id` restarts at :0 for every outer call — so two programs sharing `call_0` merged into one card. Key by (response message id, tool call id) via `ptcTraceKey`, mirroring `subagentProgressKey`; the event's `runId` already carries the message id and the card reads its own from MessageContext. Prune unsettled rows on resume. Inner calls are not content parts, so the resume snapshot cannot rebuild them, and `trackReplayEvent` only persists OAuth events — a call that settled during a disconnect left a spinner that never resolved. Settled rows are real history and stay. Make the argument preview budget-aware. Iterate keys rather than entries so the budget check can actually skip work, and clip against a bounded window so a multi-megabyte value is never collapsed in full to build a 40-character preview. Catch the resumable emission promise. The synchronous try/catch around the emitter cannot observe a rejected `emitChunk`, so a failing transport raised an unhandled rejection per event instead of dropping telemetry. Announce completion to assistive technology. The check glyph is decorative and a fast call renders no duration, so a settled row previously announced no outcome; each row now carries an sr-only status and the visible cell that duplicated it is hidden. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MBRQUsPXSvDBnjrSDoXWHP * 🧹 fix: Repair CI Failures on the PTC Tool Trace Two failures on the previous head, both mine. `Tests: api (shard 2/3)` — 46 failures in `initialize.spec.js`, all `TypeError: createPtcProgressEmitter is not a function`. The suite mocks the callbacks module with an object literal, and wiring the new emitter into `initialize.js` without adding it there left the factory undefined at call time. Added it alongside `createAttachmentEmitter`, plus an assertion that it receives the same generation fence as every other resumable emitter — a stale epoch would leak one run's inner calls into the next. `Static checks` — import-order drift in `PtcToolTrace.tsx` and `handlers.ts`, repaired with `scripts/sort-imports.mts`. ESLint and Prettier both passed, so only the dedicated check caught it. `openai.js` and `responses.js` never take the emitter, so their specs were unaffected; verified the initialize mock now covers every name the module destructures. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MBRQUsPXSvDBnjrSDoXWHP * 🔐 fix: Address Second Codex Review on the PTC Tool Trace Three of five findings actioned; two answered on the thread. Respect tool-argument PII filtering (P1). Inner calls never reach `filteredToolArgumentsResult` — the sandbox bridge invokes them directly — so the trace was the one path putting their values on the wire in a deployment that had configured `filters.toolArguments.pii`. When any of the name / arguments / output fields are filtered, the emitter now omits both the argument preview and the failure message, which routinely quotes the argument that caused it. Name, status and duration still report. Drop the light/dark-specific background (P1). `dark:bg-transparent` stepped outside the semantic roles and would lose the intended separation under a custom theme. The pane now sets no background at all and inherits the card's surface, which resolves to the same color the override produced in both default themes and stays correct when a theme reassigns its roles. Bound the live trace (P2). A program looping over a large collection made every event copy an ever-growing array and rendered a row per call. The trace now keeps a rolling tail of 100 rows and counts what it evicted, surfaced as "+N earlier calls" so the cap is never silent. A settle whose row is gone — evicted, or pruned across a resume gap — no longer reappears out of order. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MBRQUsPXSvDBnjrSDoXWHP * ✅ test: Keep PTC Trace Tests Aligned With Caller-Capability Filtering Left out of the merge commit by a staging slip; without them `handlers.spec.ts` fails on the merged tree. `#15105` restricts the PTC tool map to tools whose `allowed_callers` admit code execution, so the existing trace test's registry entry — which declared none, defaulting to `direct` — was filtered out before the instrumentation could see it. Declare the fixture `code_execution`. Add a guard for the resolution itself: a `direct`-only tool must never appear in the instrumented map. Tracing wraps the eligible map, and this fails if a later change reorders that and lets the trace widen what the sandbox reaches. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MBRQUsPXSvDBnjrSDoXWHP * 🛡️ fix: Close Name Disclosure and Follow the PTC Trace Tail Two findings from the third Codex pass on `17a9ec9`. Redact filtered inner-tool names (P1). The previous gate suppressed argument and failure previews but the event still carried `name` verbatim, so a deployment whose `filters.toolArguments.pii.fields` includes `name` could see a blocked identifier disclosed through the trace — the one path inner calls take, since they never reach `filteredToolArgumentsResult`. Inner tool names are now inspected once per PTC call with the same `extractToolArgumentContent` + `inspectContent` pair the executor uses; any that trip the policy are left unwrapped, so they still execute and emit nothing. An un-inspectable name fails closed. Follow the trace tail (P2). The row list is a 200px scroller that never moved, so once a program exceeded the viewport the card sat on the oldest calls while live activity accumulated below the fold. Reuse `useFollowScroll` — the hook the code and command panes already use — which pins to the tail while calls are running and yields the moment the reader scrolls up. The host card threads its disclosure state so a collapsed pane is never scrolled invisibly. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MBRQUsPXSvDBnjrSDoXWHP * 📌 fix: Pin the PTC Trace Through Its Final Settle The fourth Codex pass on `4bf68e1`, one P2 finding. `useFollowScroll` returned early whenever `active` was false, so the one change it most needed to follow was the one it skipped. A failing inner call settles by appending its error line in the same commit that clears the last running row: the content grows and the stream ends together, and the pin that would have revealed that line never fired. On an expanded, bottom-pinned pane the failure — the row a reader most wants — stayed below the fold. The falling edge of `active` now pins too, but only when the content changed with it. Ending a stream on its own still leaves the pane where the reader left it, which is what the existing contract promises and what the sibling code and command panes rely on; a reader who has scrolled up is untouched either way. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MBRQUsPXSvDBnjrSDoXWHP * 🔌 fix: Keep PTC Calls That Outlive a Reconnect Fifth Codex pass on `085a83f`; one of its two findings. Pruning rows across a resume gap deleted every `running` row, but a stream gap is not proof the call ended. A call still executing across the reconnect settles normally on the restored live stream — and `applyPtcToolCall` drops a settle whose row is gone, by design, so an evicted row cannot reappear out of order. The call therefore vanished from the trace despite having run, which is worse than the spinner the pruning existed to prevent. Rows are now marked `interrupted` instead of removed. A call whose settle was genuinely lost in the gap reports that honestly rather than spinning forever, and one that survives the gap settles onto the row it opened, reporting its real outcome and duration. `interrupted` is a client-side conclusion, so it widens the row status locally and leaves the wire contract alone. Two cases added: the gap marks rather than drops, and a post-reconnect settle lands on its marked row; plus a render case for the new outcome. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MBRQUsPXSvDBnjrSDoXWHP --------- Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
parent
caa938fec6
commit
c2aa688d73
26 changed files with 1707 additions and 12 deletions
|
|
@ -14,6 +14,7 @@ import useFollowScroll from './useFollowScroll';
|
|||
import { ERROR_PATTERNS } from './ExecuteCode';
|
||||
import { AttachmentGroup } from './Attachment';
|
||||
import { useToolCallIntent } from './intent';
|
||||
import PtcToolTrace from './PtcToolTrace';
|
||||
import { useLocalize } from '~/hooks';
|
||||
import { cn } from '~/utils';
|
||||
|
||||
|
|
@ -176,6 +177,11 @@ export default function BashCall({
|
|||
</pre>
|
||||
</div>
|
||||
)}
|
||||
<PtcToolTrace
|
||||
toolCallId={toolCallId}
|
||||
expanded={showCode}
|
||||
className={cn(command && 'border-t border-border-light')}
|
||||
/>
|
||||
{hasOutput && backgroundHandle == null && (
|
||||
<div className={cn(command && 'border-t border-border-light')}>
|
||||
<pre
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import CodeWindowHeader from './CodeWindowHeader';
|
|||
import useFollowScroll from './useFollowScroll';
|
||||
import { AttachmentGroup } from './Attachment';
|
||||
import { useToolCallIntent } from './intent';
|
||||
import PtcToolTrace from './PtcToolTrace';
|
||||
import { useLocalize } from '~/hooks';
|
||||
import Stdout from './Stdout';
|
||||
import { cn } from '~/utils';
|
||||
|
|
@ -177,6 +178,11 @@ export default function ExecuteCode({
|
|||
<code className={`hljs language-${lang} !whitespace-pre`}>{highlighted}</code>
|
||||
</pre>
|
||||
)}
|
||||
<PtcToolTrace
|
||||
toolCallId={toolCallId}
|
||||
expanded={showCode}
|
||||
className={cn(code && 'border-t border-border-light')}
|
||||
/>
|
||||
{hasOutput && backgroundHandle == null && (
|
||||
<div
|
||||
className={cn(
|
||||
|
|
|
|||
|
|
@ -0,0 +1,170 @@
|
|||
import { useRecoilValue } from 'recoil';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { isReportableRunStepDuration } from 'librechat-data-provider';
|
||||
import type { TranslationKeys } from '~/hooks';
|
||||
import type { PtcTraceEntry } from '~/store';
|
||||
import { cn, parseToolName, getRunStepDurationLabels } from '~/utils';
|
||||
import { useMessageContext } from '~/Providers/MessageContext';
|
||||
import { ptcTraceByToolCallId, ptcTraceKey } from '~/store';
|
||||
import { useMCPServerNames } from '~/hooks/MCP';
|
||||
import useFollowScroll from './useFollowScroll';
|
||||
import { useLocalize } from '~/hooks';
|
||||
|
||||
/** Terminal-style status column: one glyph wide for every state, so the
|
||||
* tool names stay aligned as calls settle. */
|
||||
const STATUS_GLYPH: Record<PtcTraceEntry['status'], string> = {
|
||||
running: '›',
|
||||
success: '✓',
|
||||
error: '✗',
|
||||
interrupted: '?',
|
||||
};
|
||||
|
||||
/** Spoken equivalent of the glyph. The glyph itself is decorative, and a
|
||||
* fast call renders no duration, so without this a completed row would
|
||||
* announce no outcome at all. */
|
||||
const STATUS_LABEL_KEYS: Record<PtcTraceEntry['status'], TranslationKeys> = {
|
||||
running: 'com_ui_ptc_trace_running',
|
||||
success: 'com_ui_ptc_trace_done',
|
||||
error: 'com_ui_ptc_trace_failed',
|
||||
interrupted: 'com_ui_ptc_trace_interrupted',
|
||||
};
|
||||
|
||||
/**
|
||||
* One line of the trace. Reads as a shell transcript — status glyph, the tool
|
||||
* being called, its arguments, and how long it took — with the failure message
|
||||
* printed underneath the call that produced it, the way a CLI reports errors.
|
||||
*/
|
||||
function PtcTraceLine({ entry }: { entry: PtcTraceEntry }) {
|
||||
const localize = useLocalize();
|
||||
const { i18n } = useTranslation();
|
||||
const mcpServerNames = useMCPServerNames();
|
||||
const parsed = parseToolName(entry.name, mcpServerNames);
|
||||
const running = entry.status === 'running';
|
||||
const failed = entry.status === 'error';
|
||||
const duration = isReportableRunStepDuration(entry.durationMs)
|
||||
? getRunStepDurationLabels(entry.durationMs as number, i18n.language)
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
<li className="leading-5">
|
||||
<div className="flex items-baseline gap-1.5 whitespace-nowrap">
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
'w-2 shrink-0 text-center',
|
||||
failed ? 'text-status-error' : 'text-text-tertiary',
|
||||
running && 'animate-pulse',
|
||||
)}
|
||||
>
|
||||
{STATUS_GLYPH[entry.status]}
|
||||
</span>
|
||||
<span className="sr-only">{localize(STATUS_LABEL_KEYS[entry.status])}</span>
|
||||
<span className="shrink-0 text-text-primary">
|
||||
{parsed.mcpServer && (
|
||||
<>
|
||||
<span className="text-text-secondary">{parsed.mcpServer}</span>
|
||||
<span className="text-text-tertiary">·</span>
|
||||
</>
|
||||
)}
|
||||
{parsed.friendlyKey ? localize(parsed.friendlyKey) : parsed.toolName}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 truncate text-text-tertiary">{entry.args ?? ''}</span>
|
||||
{duration ? (
|
||||
<>
|
||||
<span className="shrink-0 tabular-nums text-text-tertiary" aria-hidden="true">
|
||||
{localize(duration.key, duration.values)}
|
||||
</span>
|
||||
<span className="sr-only">
|
||||
{localize(duration.announcedKey, duration.announcedValues)}
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
/* The sr-only status above already speaks this cell's meaning. */
|
||||
<span className="shrink-0 text-text-tertiary" aria-hidden="true">
|
||||
{running ? localize('com_ui_ptc_trace_running') : ''}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{failed && (
|
||||
<div className="flex items-baseline gap-1.5">
|
||||
<span className="w-2 shrink-0" aria-hidden="true" />
|
||||
<span className="min-w-0 flex-1 truncate text-status-error">
|
||||
{entry.error ?? localize('com_ui_ptc_trace_failed')}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Live trace of the tool calls a programmatic tool-calling program makes from
|
||||
* inside the sandbox, rendered under the code that is making them. Those inner
|
||||
* calls open no run step and get no card of their own, so without this the
|
||||
* card shows one running spinner for the whole program.
|
||||
*
|
||||
* Renders nothing when the tool call made no inner calls, which is every
|
||||
* non-PTC code execution — callers don't need to know which kind they hold.
|
||||
*/
|
||||
export default function PtcToolTrace({
|
||||
toolCallId,
|
||||
expanded = false,
|
||||
className,
|
||||
}: {
|
||||
toolCallId?: string;
|
||||
/** The host card's disclosure state — a collapsed pane must not be scrolled
|
||||
* invisibly, or it opens at the tail instead of the first call. */
|
||||
expanded?: boolean;
|
||||
className?: string;
|
||||
}) {
|
||||
const localize = useLocalize();
|
||||
/** Scope to this card's own message: providers reuse `tool_call_id` across
|
||||
* turns, so the raw id alone would show a later program's calls here. */
|
||||
const { messageId } = useMessageContext();
|
||||
const trace = useRecoilValue(
|
||||
ptcTraceByToolCallId(toolCallId && messageId ? ptcTraceKey(messageId, toolCallId) : ''),
|
||||
);
|
||||
|
||||
/** One character per row, so the pin re-fires both when a call is appended
|
||||
* and when one settles — a settle can add an error line and change height. */
|
||||
const followKey = `${trace.dropped}:${trace.entries.map((entry) => entry.status[0]).join('')}`;
|
||||
const running = trace.entries.some((entry) => entry.status === 'running');
|
||||
const { ref: listRef, onScroll } = useFollowScroll<HTMLOListElement>(
|
||||
followKey,
|
||||
running,
|
||||
expanded,
|
||||
);
|
||||
|
||||
if (trace.entries.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** No background of its own: the pane inherits the card's surface in both
|
||||
* themes, which is what the sibling output pane resolves to anyway. A
|
||||
* `dark:` override here would step outside the semantic roles and lose the
|
||||
* intended separation under a custom theme. */
|
||||
return (
|
||||
<div className={cn('p-4 text-xs', className)}>
|
||||
<div className="mb-1.5 text-[10px] font-medium uppercase tracking-wide text-text-secondary">
|
||||
{localize('com_ui_ptc_trace_title')}
|
||||
</div>
|
||||
<ol
|
||||
ref={listRef}
|
||||
onScroll={onScroll}
|
||||
className="max-h-[200px] overflow-auto font-mono"
|
||||
aria-live="polite"
|
||||
>
|
||||
{/* The retained tail is a window, not the whole program — say so
|
||||
rather than let the reader assume these are all the calls. */}
|
||||
{trace.dropped > 0 && (
|
||||
<li className="leading-5 text-text-tertiary">
|
||||
{localize('com_ui_ptc_trace_earlier', { count: trace.dropped })}
|
||||
</li>
|
||||
)}
|
||||
{trace.entries.map((entry) => (
|
||||
<PtcTraceLine key={entry.callId} entry={entry} />
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,6 +1,9 @@
|
|||
import React from 'react';
|
||||
import { RecoilRoot } from 'recoil';
|
||||
import { render } from '@testing-library/react';
|
||||
import type { PtcTraceEntry } from '~/store/ptc';
|
||||
import { ptcTraceByToolCallId, ptcTraceKey } from '~/store/ptc';
|
||||
import { MessageContext } from '~/Providers/MessageContext';
|
||||
import ExecuteCode from '../ExecuteCode';
|
||||
import store from '~/store';
|
||||
|
||||
|
|
@ -55,9 +58,14 @@ jest.mock('../useLazyHighlight', () => {
|
|||
});
|
||||
|
||||
jest.mock('~/utils', () => ({
|
||||
...jest.requireActual<typeof import('~/utils/toolLabels')>('~/utils/toolLabels'),
|
||||
...jest.requireActual<typeof import('~/utils/runStepDuration')>('~/utils/runStepDuration'),
|
||||
cn: (...classes: Array<string | false | null | undefined>) => classes.filter(Boolean).join(' '),
|
||||
}));
|
||||
|
||||
jest.mock('react-i18next', () => ({ useTranslation: () => ({ i18n: { language: 'en' } }) }));
|
||||
jest.mock('~/hooks/MCP', () => ({ useMCPServerNames: () => [] }));
|
||||
|
||||
/**
|
||||
* jsdom has no layout, so the capped pane's scroll geometry is stubbed:
|
||||
* `clientHeight` is fixed, `scrollHeight` either reads from mutable state
|
||||
|
|
@ -134,3 +142,43 @@ describe('ExecuteCode streaming follow-scroll', () => {
|
|||
expect(state.writes).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ExecuteCode programmatic tool trace', () => {
|
||||
const TOOL_CALL_ID = 'call_ptc_1';
|
||||
const MESSAGE_ID = 'response-msg-1';
|
||||
|
||||
const renderWithTrace = (entries: PtcTraceEntry[]) =>
|
||||
render(
|
||||
<RecoilRoot
|
||||
initializeState={({ set }) => {
|
||||
set(store.autoExpandTools, true);
|
||||
set(ptcTraceByToolCallId(ptcTraceKey(MESSAGE_ID, TOOL_CALL_ID)), { entries, dropped: 0 });
|
||||
}}
|
||||
>
|
||||
<MessageContext.Provider value={{ messageId: MESSAGE_ID, isExpanded: true }}>
|
||||
<ExecuteCode
|
||||
initialProgress={0.5}
|
||||
isSubmitting={true}
|
||||
toolCallId={TOOL_CALL_ID}
|
||||
args={{ lang: 'py', code: 'print(1)' }}
|
||||
output=""
|
||||
/>
|
||||
</MessageContext.Provider>
|
||||
</RecoilRoot>,
|
||||
);
|
||||
|
||||
it('lists the inner tool calls the running program has made', () => {
|
||||
const { getByText } = renderWithTrace([
|
||||
{ callId: 'a', name: 'read_file', status: 'success', args: 'path=a.ts', durationMs: 1200 },
|
||||
]);
|
||||
|
||||
expect(getByText('read_file')).toBeInTheDocument();
|
||||
expect(getByText('path=a.ts')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('adds nothing to a plain code execution that made no inner calls', () => {
|
||||
const { queryByText } = renderWithTrace([]);
|
||||
|
||||
expect(queryByText('com_ui_ptc_trace_title')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -0,0 +1,140 @@
|
|||
import React from 'react';
|
||||
import { RecoilRoot, useSetRecoilState } from 'recoil';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import type { PtcTraceEntry } from '~/store/ptc';
|
||||
import { ptcTraceByToolCallId, ptcTraceKey } from '~/store/ptc';
|
||||
import { MessageContext } from '~/Providers/MessageContext';
|
||||
import PtcToolTrace from '../PtcToolTrace';
|
||||
|
||||
jest.mock('~/hooks', () => ({
|
||||
useLocalize:
|
||||
() =>
|
||||
(key: string, values?: Record<string, unknown>): string => {
|
||||
const translations: Record<string, string> = {
|
||||
com_ui_ptc_trace_title: 'Tool calls',
|
||||
com_ui_ptc_trace_running: 'running',
|
||||
com_ui_ptc_trace_failed: 'failed',
|
||||
com_ui_ptc_trace_done: 'done',
|
||||
com_ui_ptc_trace_interrupted: 'interrupted',
|
||||
com_ui_ptc_trace_earlier: `+${values?.count} earlier calls`,
|
||||
com_ui_tool_name_code: 'Code',
|
||||
};
|
||||
if (key === 'com_ui_duration_seconds') {
|
||||
return `${values?.[0]}s`;
|
||||
}
|
||||
return translations[key] ?? key;
|
||||
},
|
||||
}));
|
||||
|
||||
jest.mock('react-i18next', () => ({ useTranslation: () => ({ i18n: { language: 'en' } }) }));
|
||||
jest.mock('~/hooks/MCP', () => ({ useMCPServerNames: () => ['github'] }));
|
||||
jest.mock('~/utils', () => ({
|
||||
...jest.requireActual('~/utils/toolLabels'),
|
||||
...jest.requireActual('~/utils/runStepDuration'),
|
||||
cn: (...classes: unknown[]) => classes.filter(Boolean).join(' '),
|
||||
}));
|
||||
|
||||
const TOOL_CALL_ID = 'call_ptc_1';
|
||||
const MESSAGE_ID = 'response-msg-1';
|
||||
|
||||
function renderTrace(entries: PtcTraceEntry[], messageId = MESSAGE_ID, dropped = 0) {
|
||||
const Seed = () => {
|
||||
const set = useSetRecoilState(ptcTraceByToolCallId(ptcTraceKey(MESSAGE_ID, TOOL_CALL_ID)));
|
||||
React.useEffect(() => {
|
||||
if (entries.length > 0) {
|
||||
set({ entries, dropped });
|
||||
}
|
||||
}, [set]);
|
||||
return null;
|
||||
};
|
||||
|
||||
return render(
|
||||
<RecoilRoot>
|
||||
<Seed />
|
||||
<MessageContext.Provider value={{ messageId, isExpanded: false }}>
|
||||
<PtcToolTrace toolCallId={TOOL_CALL_ID} />
|
||||
</MessageContext.Provider>
|
||||
</RecoilRoot>,
|
||||
);
|
||||
}
|
||||
|
||||
describe('PtcToolTrace', () => {
|
||||
it('renders nothing when the call made no inner tool calls', () => {
|
||||
const { container } = renderTrace([]);
|
||||
expect(container).toBeEmptyDOMElement();
|
||||
});
|
||||
|
||||
it('lists each inner call with its arguments', () => {
|
||||
renderTrace([
|
||||
{ callId: 'a', name: 'read_file', status: 'success', args: 'path=a.ts', durationMs: 1200 },
|
||||
{ callId: 'b', name: 'write_file', status: 'running', args: 'path=b.ts' },
|
||||
]);
|
||||
|
||||
expect(screen.getByText('Tool calls')).toBeInTheDocument();
|
||||
expect(screen.getByText('read_file')).toBeInTheDocument();
|
||||
expect(screen.getByText('path=a.ts')).toBeInTheDocument();
|
||||
expect(screen.getByText('write_file')).toBeInTheDocument();
|
||||
/* Twice by design: the visible cell plus the screen-reader status. */
|
||||
expect(screen.getAllByText('running')).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('splits an MCP tool id into its server and tool name', () => {
|
||||
renderTrace([{ callId: 'a', name: 'search_code_mcp_github', status: 'running' }]);
|
||||
|
||||
expect(screen.getByText('github')).toBeInTheDocument();
|
||||
expect(screen.getByText('search_code')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows a settled duration', () => {
|
||||
renderTrace([{ callId: 'a', name: 'read_file', status: 'success', durationMs: 1200 }]);
|
||||
|
||||
expect(screen.getByText('1.2s')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('prints the failure message under the call that produced it', () => {
|
||||
renderTrace([
|
||||
{ callId: 'a', name: 'write_file', status: 'error', args: 'path=/etc/x', error: 'Denied' },
|
||||
]);
|
||||
|
||||
expect(screen.getByText('path=/etc/x')).toBeInTheDocument();
|
||||
expect(screen.getByText('Denied')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('falls back to a generic failure label when no message came through', () => {
|
||||
renderTrace([{ callId: 'a', name: 'write_file', status: 'error' }]);
|
||||
|
||||
expect(screen.getAllByText('failed').length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('speaks a completion status even when the call was too fast to time', () => {
|
||||
renderTrace([{ callId: 'a', name: 'read_file', status: 'success' }]);
|
||||
|
||||
expect(screen.getByText('done')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('speaks an interrupted outcome for a call a stream gap cut off', () => {
|
||||
renderTrace([{ callId: 'c1', name: 'write_file', status: 'interrupted' }]);
|
||||
expect(screen.getByText('interrupted')).toBeInTheDocument();
|
||||
/** Neither a failure nor still in flight: no error styling, no spinner. */
|
||||
expect(screen.queryByText('failed')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('running')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('says how many calls the cap dropped rather than truncating silently', () => {
|
||||
renderTrace([{ callId: 'a', name: 'read_file', status: 'success' }], MESSAGE_ID, 42);
|
||||
|
||||
expect(screen.getByText('+42 earlier calls')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows no truncation notice when nothing was dropped', () => {
|
||||
renderTrace([{ callId: 'a', name: 'read_file', status: 'success' }]);
|
||||
|
||||
expect(screen.queryByText(/earlier calls/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not show another message\u2019s trace in this card', () => {
|
||||
renderTrace([{ callId: 'a', name: 'read_file', status: 'success' }], 'a-different-message');
|
||||
|
||||
expect(screen.queryByText('read_file')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
|
@ -112,6 +112,34 @@ describe('useFollowScroll', () => {
|
|||
expect(state.writes).toEqual([900]);
|
||||
});
|
||||
|
||||
/** A failing PTC call settles by appending its error line in the same
|
||||
* commit that clears the last running row, so the growth and the end of
|
||||
* the stream arrive together. */
|
||||
it('pins one last time when the change that ends the stream also adds content', () => {
|
||||
const { rerender, state } = setup();
|
||||
state.scrollHeight = 1200;
|
||||
rerender(<Probe content="ab" active={false} expanded />);
|
||||
expect(state.writes).toEqual([1200]);
|
||||
});
|
||||
|
||||
it('does not pin the settling change for a reader who scrolled up', () => {
|
||||
const { rerender, pane, state } = setup();
|
||||
state.scrollTop = 100;
|
||||
fireEvent.scroll(pane);
|
||||
state.scrollHeight = 1200;
|
||||
rerender(<Probe content="ab" active={false} expanded />);
|
||||
expect(state.writes).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('pins only the settling change, not the ones after it', () => {
|
||||
const { rerender, state } = setup();
|
||||
rerender(<Probe content="ab" active={false} expanded />);
|
||||
expect(state.writes).toEqual([900]);
|
||||
state.scrollHeight = 1200;
|
||||
rerender(<Probe content="abc" active={false} expanded />);
|
||||
expect(state.writes).toEqual([900]);
|
||||
});
|
||||
|
||||
it('detaches when the user scrolls up beyond the follow threshold', () => {
|
||||
const { rerender, pane, state } = setup();
|
||||
state.scrollTop = 100;
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ export { default as SkillCall } from './SkillCall';
|
|||
export { default as ReadFileCall } from './ReadFileCall';
|
||||
export { default as FileAuthoringCall } from './FileAuthoringCall';
|
||||
export { default as BashCall } from './BashCall';
|
||||
export { default as PtcToolTrace } from './PtcToolTrace';
|
||||
export { default as SubagentCall } from './SubagentCall';
|
||||
export { default as SteerPart } from './SteerPart';
|
||||
export { default as AuthorHeader } from './AuthorHeader';
|
||||
|
|
|
|||
|
|
@ -32,8 +32,16 @@ const FOLLOW_THRESHOLD_PX = 40;
|
|||
* would open at the tail. Gated, it opens reading from the top, while an
|
||||
* expand mid-stream pins immediately. The pin's own scroll event measures
|
||||
* distance zero and keeps the attached state, so programmatic scrolls
|
||||
* need no special-casing. Finished panes (`active === false`) are never
|
||||
* scrolled.
|
||||
* need no special-casing.
|
||||
*
|
||||
* A finished pane (`active === false`) is never scrolled, with one
|
||||
* exception: the very change that ends the stream. That change often adds
|
||||
* content — a failing PTC call settles by appending its error line in the
|
||||
* same commit that clears the last running row — and gating on `active`
|
||||
* alone would drop exactly the pin that content needs, leaving the final
|
||||
* line below the fold. So the falling edge of `active` still pins, but
|
||||
* only when the content changed with it; ending the stream on its own
|
||||
* leaves the pane where the reader left it.
|
||||
*/
|
||||
export default function useFollowScroll<T extends HTMLElement>(
|
||||
content: string | readonly ReactNode[],
|
||||
|
|
@ -42,6 +50,8 @@ export default function useFollowScroll<T extends HTMLElement>(
|
|||
): { ref: RefObject<T>; onScroll: UIEventHandler<T> } {
|
||||
const ref = useRef<T>(null);
|
||||
const followRef = useRef(true);
|
||||
const wasActiveRef = useRef(active);
|
||||
const previousContentRef = useRef(content);
|
||||
|
||||
const onScroll = useCallback<UIEventHandler<T>>((event) => {
|
||||
const el = event.currentTarget;
|
||||
|
|
@ -49,7 +59,14 @@ export default function useFollowScroll<T extends HTMLElement>(
|
|||
}, []);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!active || !expanded || !followRef.current) {
|
||||
const settling = wasActiveRef.current && !Object.is(previousContentRef.current, content);
|
||||
previousContentRef.current = content;
|
||||
wasActiveRef.current = active;
|
||||
|
||||
if (!expanded || !followRef.current) {
|
||||
return;
|
||||
}
|
||||
if (!active && !settling) {
|
||||
return;
|
||||
}
|
||||
const el = ref.current;
|
||||
|
|
|
|||
|
|
@ -236,6 +236,7 @@ jest.mock('~/hooks/SSE/useEventHandlers', () => {
|
|||
contentHandler: jest.fn(),
|
||||
resetContentHandler: jest.fn(),
|
||||
syncStepMessage: jest.fn(),
|
||||
prunePtcTraces: jest.fn(),
|
||||
clearStepMaps: mockClearStepMaps,
|
||||
flushPendingDeltas: jest.fn(),
|
||||
messageHandler: jest.fn(),
|
||||
|
|
|
|||
|
|
@ -15,8 +15,11 @@ import type {
|
|||
TConversation,
|
||||
TMessage,
|
||||
SubagentUpdateEvent,
|
||||
PtcToolCallEvent,
|
||||
Agents,
|
||||
} from 'librechat-data-provider';
|
||||
import type { PtcTrace, PtcTraceEntry } from '~/store/ptc';
|
||||
import { ptcTraceByToolCallId, ptcTraceKey, PTC_TRACE_MAX_ENTRIES } from '~/store/ptc';
|
||||
import { subagentProgressByToolCallId, subagentProgressKey } from '~/store/subagents';
|
||||
import { resolveAskUserQuestionPart } from '~/utils/approval';
|
||||
import useStepHandler from '~/hooks/SSE/useStepHandler';
|
||||
|
|
@ -3913,4 +3916,315 @@ describe('useStepHandler', () => {
|
|||
expect(response?.content).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PTC inner tool-call trace', () => {
|
||||
const renderWithTraceReader = () => {
|
||||
const hookResult = renderHook(
|
||||
() => {
|
||||
const stepHandler = useStepHandler(createHookParams());
|
||||
const read = useRecoilCallback(
|
||||
({ snapshot }) =>
|
||||
(messageId: string, toolCallId: string): PtcTrace =>
|
||||
snapshot
|
||||
.getLoadable(ptcTraceByToolCallId(ptcTraceKey(messageId, toolCallId)))
|
||||
.valueOrThrow(),
|
||||
[],
|
||||
);
|
||||
return { ...stepHandler, read };
|
||||
},
|
||||
{ wrapper: RecoilRoot },
|
||||
);
|
||||
return {
|
||||
result: hookResult.result,
|
||||
getEntries: (toolCallId: string, messageId = 'response-msg-1'): PtcTraceEntry[] =>
|
||||
(
|
||||
hookResult.result.current as unknown as { read: (m: string, id: string) => PtcTrace }
|
||||
).read(messageId, toolCallId).entries,
|
||||
getTrace: (toolCallId: string, messageId = 'response-msg-1'): PtcTrace =>
|
||||
(
|
||||
hookResult.result.current as unknown as { read: (m: string, id: string) => PtcTrace }
|
||||
).read(messageId, toolCallId),
|
||||
};
|
||||
};
|
||||
|
||||
const ptcEvent = (overrides: Partial<PtcToolCallEvent>): PtcToolCallEvent => ({
|
||||
tool_call_id: 'call_ptc',
|
||||
call_id: 'call_ptc:0',
|
||||
name: 'read_file',
|
||||
status: 'running',
|
||||
runId: 'response-msg-1',
|
||||
...overrides,
|
||||
});
|
||||
|
||||
it('appends a row for each inner call the program starts', () => {
|
||||
const { result, getEntries } = renderWithTraceReader();
|
||||
const submission = createSubmission();
|
||||
|
||||
act(() => {
|
||||
result.current.stepHandler(
|
||||
{
|
||||
event: StepEvents.ON_PTC_TOOL_CALL,
|
||||
data: ptcEvent({ call_id: 'call_ptc:0', args: 'path=a.ts' }),
|
||||
},
|
||||
submission,
|
||||
);
|
||||
result.current.stepHandler(
|
||||
{
|
||||
event: StepEvents.ON_PTC_TOOL_CALL,
|
||||
data: ptcEvent({ call_id: 'call_ptc:1', name: 'write_file', args: 'path=b.ts' }),
|
||||
},
|
||||
submission,
|
||||
);
|
||||
});
|
||||
|
||||
expect(getEntries('call_ptc')).toEqual([
|
||||
{ callId: 'call_ptc:0', name: 'read_file', status: 'running', args: 'path=a.ts' },
|
||||
{ callId: 'call_ptc:1', name: 'write_file', status: 'running', args: 'path=b.ts' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('settles a row in place instead of appending a duplicate', () => {
|
||||
const { result, getEntries } = renderWithTraceReader();
|
||||
const submission = createSubmission();
|
||||
|
||||
act(() => {
|
||||
result.current.stepHandler(
|
||||
{ event: StepEvents.ON_PTC_TOOL_CALL, data: ptcEvent({ args: 'path=a.ts' }) },
|
||||
submission,
|
||||
);
|
||||
result.current.stepHandler(
|
||||
{
|
||||
event: StepEvents.ON_PTC_TOOL_CALL,
|
||||
data: ptcEvent({ status: 'success', durationMs: 1200 }),
|
||||
},
|
||||
submission,
|
||||
);
|
||||
});
|
||||
|
||||
expect(getEntries('call_ptc')).toEqual([
|
||||
{
|
||||
callId: 'call_ptc:0',
|
||||
name: 'read_file',
|
||||
status: 'success',
|
||||
args: 'path=a.ts',
|
||||
durationMs: 1200,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('keeps each PTC call trace under its own tool call id', () => {
|
||||
const { result, getEntries } = renderWithTraceReader();
|
||||
const submission = createSubmission();
|
||||
|
||||
act(() => {
|
||||
result.current.stepHandler(
|
||||
{ event: StepEvents.ON_PTC_TOOL_CALL, data: ptcEvent({}) },
|
||||
submission,
|
||||
);
|
||||
result.current.stepHandler(
|
||||
{
|
||||
event: StepEvents.ON_PTC_TOOL_CALL,
|
||||
data: ptcEvent({ tool_call_id: 'call_other', call_id: 'call_other:0' }),
|
||||
},
|
||||
submission,
|
||||
);
|
||||
});
|
||||
|
||||
expect(getEntries('call_ptc')).toHaveLength(1);
|
||||
expect(getEntries('call_other')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('drops an envelope with no call identity rather than seeding a blank row', () => {
|
||||
const { result, getEntries } = renderWithTraceReader();
|
||||
const submission = createSubmission();
|
||||
|
||||
act(() => {
|
||||
result.current.stepHandler(
|
||||
{ event: StepEvents.ON_PTC_TOOL_CALL, data: ptcEvent({ call_id: '' }) },
|
||||
submission,
|
||||
);
|
||||
});
|
||||
|
||||
expect(getEntries('call_ptc')).toEqual([]);
|
||||
});
|
||||
|
||||
it('keeps a reused tool_call_id isolated across parent messages', () => {
|
||||
const { result, getEntries } = renderWithTraceReader();
|
||||
const submission = createSubmission();
|
||||
|
||||
act(() => {
|
||||
result.current.stepHandler(
|
||||
{ event: StepEvents.ON_PTC_TOOL_CALL, data: ptcEvent({ name: 'read_file' }) },
|
||||
submission,
|
||||
);
|
||||
result.current.stepHandler(
|
||||
{
|
||||
event: StepEvents.ON_PTC_TOOL_CALL,
|
||||
data: ptcEvent({ name: 'write_file', runId: 'response-msg-2' }),
|
||||
},
|
||||
submission,
|
||||
);
|
||||
});
|
||||
|
||||
expect(getEntries('call_ptc').map((e) => e.name)).toEqual(['read_file']);
|
||||
expect(getEntries('call_ptc', 'response-msg-2').map((e) => e.name)).toEqual(['write_file']);
|
||||
});
|
||||
|
||||
it('drops an envelope that cannot be scoped to a parent message', () => {
|
||||
const { result, getEntries } = renderWithTraceReader();
|
||||
const submission = createSubmission();
|
||||
|
||||
act(() => {
|
||||
result.current.stepHandler(
|
||||
{ event: StepEvents.ON_PTC_TOOL_CALL, data: ptcEvent({ runId: undefined }) },
|
||||
submission,
|
||||
);
|
||||
});
|
||||
|
||||
expect(getEntries('call_ptc')).toEqual([]);
|
||||
});
|
||||
|
||||
it('marks rows still running across a resume gap and keeps settled ones', () => {
|
||||
const { result, getEntries } = renderWithTraceReader();
|
||||
const submission = createSubmission();
|
||||
|
||||
act(() => {
|
||||
/** Real order: each row opens as `running` before it settles. */
|
||||
result.current.stepHandler(
|
||||
{ event: StepEvents.ON_PTC_TOOL_CALL, data: ptcEvent({ call_id: 'call_ptc:0' }) },
|
||||
submission,
|
||||
);
|
||||
result.current.stepHandler(
|
||||
{
|
||||
event: StepEvents.ON_PTC_TOOL_CALL,
|
||||
data: ptcEvent({ call_id: 'call_ptc:0', status: 'success', durationMs: 900 }),
|
||||
},
|
||||
submission,
|
||||
);
|
||||
result.current.stepHandler(
|
||||
{
|
||||
event: StepEvents.ON_PTC_TOOL_CALL,
|
||||
data: ptcEvent({ call_id: 'call_ptc:1', name: 'write_file' }),
|
||||
},
|
||||
submission,
|
||||
);
|
||||
});
|
||||
expect(getEntries('call_ptc')).toHaveLength(2);
|
||||
|
||||
act(() => {
|
||||
(result.current as unknown as { prunePtcTraces: () => void }).prunePtcTraces();
|
||||
});
|
||||
|
||||
expect(getEntries('call_ptc').map((e) => [e.callId, e.status])).toEqual([
|
||||
['call_ptc:0', 'success'],
|
||||
['call_ptc:1', 'interrupted'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('lets a call still running across the gap settle onto its marked row', () => {
|
||||
const { result, getEntries } = renderWithTraceReader();
|
||||
const submission = createSubmission();
|
||||
|
||||
act(() => {
|
||||
result.current.stepHandler(
|
||||
{
|
||||
event: StepEvents.ON_PTC_TOOL_CALL,
|
||||
data: ptcEvent({ call_id: 'call_ptc:0', name: 'write_file' }),
|
||||
},
|
||||
submission,
|
||||
);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
(result.current as unknown as { prunePtcTraces: () => void }).prunePtcTraces();
|
||||
});
|
||||
expect(getEntries('call_ptc').map((e) => e.status)).toEqual(['interrupted']);
|
||||
|
||||
/** The call outlived the disconnect, so its terminal event arrives on
|
||||
* the restored live stream and must land on the row it opened. */
|
||||
act(() => {
|
||||
result.current.stepHandler(
|
||||
{
|
||||
event: StepEvents.ON_PTC_TOOL_CALL,
|
||||
data: ptcEvent({
|
||||
call_id: 'call_ptc:0',
|
||||
name: 'write_file',
|
||||
status: 'success',
|
||||
durationMs: 1400,
|
||||
}),
|
||||
},
|
||||
submission,
|
||||
);
|
||||
});
|
||||
|
||||
expect(getEntries('call_ptc')).toEqual([
|
||||
expect.objectContaining({ callId: 'call_ptc:0', status: 'success', durationMs: 1400 }),
|
||||
]);
|
||||
});
|
||||
|
||||
it('caps the retained rows and reports how many it dropped', () => {
|
||||
const { result, getTrace } = renderWithTraceReader();
|
||||
const submission = createSubmission();
|
||||
const total = PTC_TRACE_MAX_ENTRIES + 25;
|
||||
|
||||
act(() => {
|
||||
for (let i = 0; i < total; i++) {
|
||||
result.current.stepHandler(
|
||||
{ event: StepEvents.ON_PTC_TOOL_CALL, data: ptcEvent({ call_id: `call_ptc:${i}` }) },
|
||||
submission,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const trace = getTrace('call_ptc');
|
||||
expect(trace.entries).toHaveLength(PTC_TRACE_MAX_ENTRIES);
|
||||
expect(trace.dropped).toBe(25);
|
||||
/** The tail is retained, so the newest call is still visible. */
|
||||
expect(trace.entries.at(-1)?.callId).toBe(`call_ptc:${total - 1}`);
|
||||
});
|
||||
|
||||
it('ignores a settle whose row the cap already evicted', () => {
|
||||
const { result, getTrace } = renderWithTraceReader();
|
||||
const submission = createSubmission();
|
||||
|
||||
act(() => {
|
||||
for (let i = 0; i < PTC_TRACE_MAX_ENTRIES + 5; i++) {
|
||||
result.current.stepHandler(
|
||||
{ event: StepEvents.ON_PTC_TOOL_CALL, data: ptcEvent({ call_id: `call_ptc:${i}` }) },
|
||||
submission,
|
||||
);
|
||||
}
|
||||
result.current.stepHandler(
|
||||
{
|
||||
event: StepEvents.ON_PTC_TOOL_CALL,
|
||||
data: ptcEvent({ call_id: 'call_ptc:0', status: 'success', durationMs: 10 }),
|
||||
},
|
||||
submission,
|
||||
);
|
||||
});
|
||||
|
||||
const trace = getTrace('call_ptc');
|
||||
expect(trace.entries).toHaveLength(PTC_TRACE_MAX_ENTRIES);
|
||||
expect(trace.entries.some((e) => e.callId === 'call_ptc:0')).toBe(false);
|
||||
});
|
||||
|
||||
it('releases the trace atoms on reset', () => {
|
||||
const { result, getEntries } = renderWithTraceReader();
|
||||
const submission = createSubmission();
|
||||
|
||||
act(() => {
|
||||
result.current.stepHandler(
|
||||
{ event: StepEvents.ON_PTC_TOOL_CALL, data: ptcEvent({}) },
|
||||
submission,
|
||||
);
|
||||
});
|
||||
expect(getEntries('call_ptc')).toHaveLength(1);
|
||||
|
||||
act(() => {
|
||||
(result.current as unknown as { resetPtcAtoms: () => void }).resetPtcAtoms();
|
||||
});
|
||||
|
||||
expect(getEntries('call_ptc')).toEqual([]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -375,6 +375,8 @@ export default function useEventHandlers({
|
|||
stepHandler,
|
||||
clearStepMaps,
|
||||
resetSubagentAtoms,
|
||||
resetPtcAtoms,
|
||||
prunePtcTraces,
|
||||
syncStepMessage,
|
||||
cancelPendingDeltaFlush,
|
||||
flushPendingDeltas,
|
||||
|
|
@ -420,8 +422,12 @@ export default function useEventHandlers({
|
|||
shouldResetSubagentAtomsOnConversationChange(previous, paramId, preserveNewConversationId)
|
||||
) {
|
||||
resetSubagentAtoms();
|
||||
/** PTC traces are live-only for the same reason and share the boundary:
|
||||
* keep them through a run so a finished program stays auditable, drop
|
||||
* them when the conversation changes. */
|
||||
resetPtcAtoms();
|
||||
}
|
||||
}, [paramId, resetSubagentAtoms]);
|
||||
}, [paramId, resetSubagentAtoms, resetPtcAtoms]);
|
||||
|
||||
/** Final cleanup on component unmount. `useStepHandler` keeps the
|
||||
* set of known atom keys in a ref; when the hook unmounts (user
|
||||
|
|
@ -432,8 +438,9 @@ export default function useEventHandlers({
|
|||
useEffect(
|
||||
() => () => {
|
||||
resetSubagentAtoms();
|
||||
resetPtcAtoms();
|
||||
},
|
||||
[resetSubagentAtoms],
|
||||
[resetSubagentAtoms, resetPtcAtoms],
|
||||
);
|
||||
|
||||
const messageHandler = useCallback(
|
||||
|
|
@ -1205,6 +1212,7 @@ export default function useEventHandlers({
|
|||
createdHandler,
|
||||
titleHandler,
|
||||
syncStepMessage,
|
||||
prunePtcTraces,
|
||||
cancelPendingDeltaFlush,
|
||||
flushPendingDeltas,
|
||||
attachmentHandler,
|
||||
|
|
|
|||
|
|
@ -1137,6 +1137,7 @@ export default function useResumableSSE(
|
|||
createdHandler,
|
||||
titleHandler,
|
||||
syncStepMessage,
|
||||
prunePtcTraces,
|
||||
attachmentHandler,
|
||||
resetContentHandler,
|
||||
flushPendingDeltas,
|
||||
|
|
@ -2126,6 +2127,14 @@ export default function useResumableSSE(
|
|||
titleHandler(data.resumeState.titleEvent);
|
||||
}
|
||||
|
||||
/** PTC inner calls are not content parts, so the resume snapshot
|
||||
* can't rebuild them and a settling event lost in this gap is
|
||||
* never replayed. Mark rows still `running` as interrupted rather
|
||||
* than leave a spinner that never resolves — and rather than drop
|
||||
* them, since a call still executing across the reconnect settles
|
||||
* normally on the restored stream and updates its row in place. */
|
||||
prunePtcTraces();
|
||||
|
||||
if (data.resumeState?.replayEvents?.length > 0) {
|
||||
logger.log(
|
||||
'ResumableSSE',
|
||||
|
|
@ -3474,6 +3483,7 @@ export default function useResumableSSE(
|
|||
contentHandler,
|
||||
resetContentHandler,
|
||||
syncStepMessage,
|
||||
prunePtcTraces,
|
||||
clearStepMaps,
|
||||
messageHandler,
|
||||
errorHandler,
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ import type {
|
|||
TMessageContentParts,
|
||||
SubagentUpdateEvent,
|
||||
SandboxStartingEvent,
|
||||
PtcToolCallEvent,
|
||||
} from 'librechat-data-provider';
|
||||
import type { SetterOrUpdater } from 'recoil';
|
||||
import type { AnnounceOptions } from '~/common';
|
||||
|
|
@ -29,9 +30,12 @@ import {
|
|||
registerSubagentProgressKey,
|
||||
subagentParentStreamOpenByToolCallId,
|
||||
subagentProgressByToolCallId,
|
||||
subagentProgressKey,
|
||||
takeRegisteredSubagentProgressKeys,
|
||||
sandboxStartingByToolCallId,
|
||||
ptcTraceByToolCallId,
|
||||
PTC_TRACE_MAX_ENTRIES,
|
||||
subagentProgressKey,
|
||||
ptcTraceKey,
|
||||
} from '~/store';
|
||||
import { isAskUserQuestionPart, isAnsweredAskUserQuestionPart } from '~/utils/approval';
|
||||
import { MESSAGE_UPDATE_INTERVAL } from '~/common';
|
||||
|
|
@ -63,7 +67,8 @@ type TStepEvent =
|
|||
| { event: StepEvents.ON_SUMMARIZE_DELTA; data: Agents.SummarizeDeltaEvent }
|
||||
| { event: StepEvents.ON_SUMMARIZE_COMPLETE; data: Agents.SummarizeCompleteEvent }
|
||||
| { event: StepEvents.ON_SUBAGENT_UPDATE; data: SubagentUpdateEvent }
|
||||
| { event: StepEvents.ON_SANDBOX_STARTING; data: SandboxStartingEvent };
|
||||
| { event: StepEvents.ON_SANDBOX_STARTING; data: SandboxStartingEvent }
|
||||
| { event: StepEvents.ON_PTC_TOOL_CALL; data: PtcToolCallEvent };
|
||||
|
||||
type MessageDeltaUpdate = {
|
||||
type: ContentTypes.TEXT;
|
||||
|
|
@ -346,6 +351,108 @@ export default function useStepHandler({
|
|||
[],
|
||||
);
|
||||
|
||||
/** PTC tool call ids with a live trace, so the atoms can be released. */
|
||||
const knownPtcAtomKeys = useRef(new Set<string>());
|
||||
|
||||
/**
|
||||
* Folds one `on_ptc_tool_call` envelope into its program's trace: the
|
||||
* `running` event appends a row, the settling event updates that row in
|
||||
* place by `call_id`. Order follows the sandbox's dispatch order, which is
|
||||
* what the code reads like — a round trip can settle out of order.
|
||||
*/
|
||||
const applyPtcToolCall = useRecoilCallback(
|
||||
({ set }) =>
|
||||
(event: PtcToolCallEvent, parentMessageId: string): void => {
|
||||
const { tool_call_id: toolCallId, call_id: callId, name, status } = event;
|
||||
/** No parent message means no occurrence to scope this to; a raw
|
||||
* `tool_call_id` would leak the rows into whichever card reused it. */
|
||||
if (!toolCallId || !callId || !parentMessageId) {
|
||||
return;
|
||||
}
|
||||
const atomKey = ptcTraceKey(parentMessageId, toolCallId);
|
||||
knownPtcAtomKeys.current.add(atomKey);
|
||||
set(ptcTraceByToolCallId(atomKey), (previous) => {
|
||||
const index = previous.entries.findIndex((entry) => entry.callId === callId);
|
||||
const entry = {
|
||||
callId,
|
||||
name,
|
||||
status,
|
||||
...(event.args ? { args: event.args } : {}),
|
||||
...(event.error ? { error: event.error } : {}),
|
||||
...(event.durationMs != null ? { durationMs: event.durationMs } : {}),
|
||||
};
|
||||
|
||||
if (index !== -1) {
|
||||
const next = [...previous.entries];
|
||||
next[index] = { ...previous.entries[index], ...entry };
|
||||
return { entries: next, dropped: previous.dropped };
|
||||
}
|
||||
|
||||
/** A settle whose row is gone — evicted by the cap, or pruned across
|
||||
* a resume gap — must not reappear at the tail out of order. */
|
||||
if (status !== 'running') {
|
||||
return previous;
|
||||
}
|
||||
|
||||
const appended = [...previous.entries, entry];
|
||||
const overflow = appended.length - PTC_TRACE_MAX_ENTRIES;
|
||||
if (overflow <= 0) {
|
||||
return { entries: appended, dropped: previous.dropped };
|
||||
}
|
||||
return {
|
||||
entries: appended.slice(overflow),
|
||||
dropped: previous.dropped + overflow,
|
||||
};
|
||||
});
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const resetPtcAtoms = useRecoilCallback(
|
||||
({ reset }) =>
|
||||
(): void => {
|
||||
for (const atomKey of knownPtcAtomKeys.current) {
|
||||
reset(ptcTraceByToolCallId(atomKey));
|
||||
}
|
||||
knownPtcAtomKeys.current.clear();
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
/**
|
||||
* Settles rows still marked `running` after a stream gap as `interrupted`.
|
||||
* Inner calls carry no durable state — they are not content parts, so the
|
||||
* resume snapshot cannot rebuild them and a settling event lost in the gap
|
||||
* is never replayed — which means such a row would otherwise spin forever.
|
||||
*
|
||||
* Marked, not removed: a call can also still be executing across the
|
||||
* reconnect, and its settling event then arrives normally on the restored
|
||||
* live stream. That event updates this row in place, so the call reports its
|
||||
* real outcome. Deleting the row would strand it — a settle whose row is
|
||||
* gone is dropped rather than re-appended out of order — and the call would
|
||||
* vanish from the trace despite having run. Settled rows are untouched.
|
||||
*/
|
||||
const prunePtcTraces = useRecoilCallback(
|
||||
({ set }) =>
|
||||
(): void => {
|
||||
for (const atomKey of knownPtcAtomKeys.current) {
|
||||
set(ptcTraceByToolCallId(atomKey), (previous) =>
|
||||
previous.entries.some((entry) => entry.status === 'running')
|
||||
? {
|
||||
...previous,
|
||||
entries: previous.entries.map((entry) =>
|
||||
entry.status === 'running'
|
||||
? { ...entry, status: 'interrupted' as const }
|
||||
: entry,
|
||||
),
|
||||
}
|
||||
: previous,
|
||||
);
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
/**
|
||||
* Calculate content index for a run step.
|
||||
*
|
||||
|
|
@ -1258,6 +1365,14 @@ export default function useStepHandler({
|
|||
);
|
||||
} else if (stepEvent.event === StepEvents.ON_SANDBOX_STARTING) {
|
||||
setSandboxStarting(stepEvent.data.tool_call_id);
|
||||
} else if (stepEvent.event === StepEvents.ON_PTC_TOOL_CALL) {
|
||||
/** `runId` is the response message id (the run configurable's
|
||||
* `run_id`), the same correlation the subagent path uses. */
|
||||
let responseMessageId = stepEvent.data.runId ?? '';
|
||||
if (responseMessageId === Constants.USE_PRELIM_RESPONSE_MESSAGE_ID) {
|
||||
responseMessageId = submission?.initialResponse?.messageId ?? '';
|
||||
}
|
||||
applyPtcToolCall(stepEvent.data, responseMessageId);
|
||||
} else if (stepEvent.event === StepEvents.ON_SUBAGENT_UPDATE) {
|
||||
let responseMessageId = stepEvent.data.runId;
|
||||
if (responseMessageId === Constants.USE_PRELIM_RESPONSE_MESSAGE_ID) {
|
||||
|
|
@ -1369,6 +1484,7 @@ export default function useStepHandler({
|
|||
applySubagentUpdate,
|
||||
setSandboxStarting,
|
||||
clearSandboxStarting,
|
||||
applyPtcToolCall,
|
||||
onSkillAuthoringComplete,
|
||||
],
|
||||
);
|
||||
|
|
@ -1459,6 +1575,8 @@ export default function useStepHandler({
|
|||
stepHandler,
|
||||
clearStepMaps,
|
||||
resetSubagentAtoms,
|
||||
resetPtcAtoms,
|
||||
prunePtcTraces,
|
||||
syncStepMessage,
|
||||
cancelPendingDeltaFlush,
|
||||
flushPendingDeltas,
|
||||
|
|
|
|||
|
|
@ -1742,6 +1742,12 @@
|
|||
"com_ui_provider": "Provider",
|
||||
"com_ui_provider_api_keys_description": "Manage API keys for endpoints configured to use a user-provided key.",
|
||||
"com_ui_provider_api_keys_not_set": "No key set",
|
||||
"com_ui_ptc_trace_done": "done",
|
||||
"com_ui_ptc_trace_earlier": "+{{count}} earlier calls",
|
||||
"com_ui_ptc_trace_failed": "failed",
|
||||
"com_ui_ptc_trace_interrupted": "interrupted",
|
||||
"com_ui_ptc_trace_running": "running",
|
||||
"com_ui_ptc_trace_title": "Tool calls",
|
||||
"com_ui_quality": "Quality",
|
||||
"com_ui_question_failed": "Question wasn't shown",
|
||||
"com_ui_question_failed_description": "The agent couldn't show this question and may retry automatically.",
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ export * from './mcp';
|
|||
export * from './favorites';
|
||||
export * from './subagents';
|
||||
export * from './sandbox';
|
||||
export * from './ptc';
|
||||
export * from './usage';
|
||||
export * from './steer';
|
||||
|
||||
|
|
|
|||
64
client/src/store/ptc.ts
Normal file
64
client/src/store/ptc.ts
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
import { atomFamily } from 'recoil';
|
||||
import type { PtcToolCallStatus } from 'librechat-data-provider';
|
||||
|
||||
/**
|
||||
* A row's outcome. Widens the wire status with `interrupted`, which the
|
||||
* backend never sends: it is what the client concludes locally about a call
|
||||
* that was still running when a stream gap swallowed its settling event.
|
||||
*/
|
||||
export type PtcTraceStatus = PtcToolCallStatus | 'interrupted';
|
||||
|
||||
/** One tool call a programmatic (PTC) program made from inside the sandbox. */
|
||||
export interface PtcTraceEntry {
|
||||
/** Stable id from the backend; the settle event updates this row in place. */
|
||||
callId: string;
|
||||
/** Inner tool id, e.g. `search_code_mcp_github`. */
|
||||
name: string;
|
||||
status: PtcTraceStatus;
|
||||
/** `key=value` preview of the call's input. */
|
||||
args?: string;
|
||||
/** Truncated failure message on a failed call. */
|
||||
error?: string;
|
||||
durationMs?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stable identity for one PTC invocation in its parent message. Providers
|
||||
* reuse `tool_call_id` across turns and agents, so the raw id is not
|
||||
* sufficient identity for live progress — the same rule `subagentProgressKey`
|
||||
* exists for. Without the message scope, a later program's rows would land in
|
||||
* an earlier card that happened to share `call_0`.
|
||||
*/
|
||||
export const ptcTraceKey = (parentMessageId: string, toolCallId: string) =>
|
||||
`${parentMessageId}\u0000${toolCallId}`;
|
||||
|
||||
/**
|
||||
* Rolling cap on retained rows. A program looping over a large collection can
|
||||
* make thousands of inner calls; without a bound, every event would copy an
|
||||
* ever-growing array and the card would render a row per call.
|
||||
*/
|
||||
export const PTC_TRACE_MAX_ENTRIES = 100;
|
||||
|
||||
/** One PTC program's trace: the retained tail plus what the cap discarded. */
|
||||
export interface PtcTrace {
|
||||
entries: PtcTraceEntry[];
|
||||
/** Rows evicted by {@link PTC_TRACE_MAX_ENTRIES}, so the cap is never silent. */
|
||||
dropped: number;
|
||||
}
|
||||
|
||||
/** Shared empty value — one reference, so untouched atoms compare equal. */
|
||||
export const EMPTY_PTC_TRACE: PtcTrace = { entries: [], dropped: 0 };
|
||||
|
||||
/**
|
||||
* Live trace of the inner tool calls made by one PTC run step, in the order
|
||||
* the sandbox started them (`on_ptc_tool_call` SSE events). Keyed by
|
||||
* {@link ptcTraceKey} — one concrete invocation in one message.
|
||||
*
|
||||
* Session-scoped like the subagent ticker: inner calls open no run step, so
|
||||
* nothing persists them on the message. Cleared on conversation switch rather
|
||||
* than at run boundaries, so a finished program's trace stays readable.
|
||||
*/
|
||||
export const ptcTraceByToolCallId = atomFamily<PtcTrace, string>({
|
||||
key: 'ptcTraceByToolCallId',
|
||||
default: EMPTY_PTC_TRACE,
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue