mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-23 16:34:27 +00:00
🪟 feat: Show a Running Subagent's Current Row on Its Card (#18279)
Some checks are pending
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Backend Unit Tests / backend (push) Blocked by required conditions
Channel Gateway / gateway (push) Waiting to run
Codegraph E2E Vote Gate / Gate (push) Waiting to run
Codegraph E2E Votes / vote (shard 1/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 10/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 2/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 3/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 4/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 5/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 6/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 7/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 8/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 9/10) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Client build recovery regression (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/chat (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
Frontend Unit Tests / frontend (push) Blocked by required conditions
Sync Locize Translations & Create Translation PR / Sync Translation Keys with Locize (push) Waiting to run
Sync Locize Translations & Create Translation PR / Create Translation PR on Version Published (push) Blocked by required conditions
Playwright E2E Tests / Codegraph select (push) Waiting to run
Playwright E2E Tests / Shard timings (push) Waiting to run
Playwright E2E Tests / e2e () (push) Blocked by required conditions
Playwright E2E Tests / MCP list_changed (replica count 1) (push) Blocked by required conditions
Playwright E2E Tests / MCP list_changed (replica count 2) (push) Blocked by required conditions
Playwright E2E Tests / MCP Apps (browser and server) (push) Waiting to run
Playwright E2E Tests / e2e (push) Blocked by required conditions
Playwright Shard Timings / Record shard timings (push) Waiting to run
Repository Safety / Confine repository symlinks (push) Waiting to run
Some checks are pending
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Backend Unit Tests / backend (push) Blocked by required conditions
Channel Gateway / gateway (push) Waiting to run
Codegraph E2E Vote Gate / Gate (push) Waiting to run
Codegraph E2E Votes / vote (shard 1/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 10/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 2/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 3/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 4/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 5/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 6/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 7/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 8/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 9/10) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Client build recovery regression (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/chat (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
Frontend Unit Tests / frontend (push) Blocked by required conditions
Sync Locize Translations & Create Translation PR / Sync Translation Keys with Locize (push) Waiting to run
Sync Locize Translations & Create Translation PR / Create Translation PR on Version Published (push) Blocked by required conditions
Playwright E2E Tests / Codegraph select (push) Waiting to run
Playwright E2E Tests / Shard timings (push) Waiting to run
Playwright E2E Tests / e2e () (push) Blocked by required conditions
Playwright E2E Tests / MCP list_changed (replica count 1) (push) Blocked by required conditions
Playwright E2E Tests / MCP list_changed (replica count 2) (push) Blocked by required conditions
Playwright E2E Tests / MCP Apps (browser and server) (push) Waiting to run
Playwright E2E Tests / e2e (push) Blocked by required conditions
Playwright Shard Timings / Record shard timings (push) Waiting to run
Repository Safety / Confine repository symlinks (push) Waiting to run
* 🪟 feat: Show a Running Subagent's Current Row on Its Card * 🪟 fix: Draw the Card's Row Live and Skip Label Reservations That Draw Nothing * 🪟 fix: Show a Card's Row Only While Its Thread Is Followed, and Throttle a Detached Row Too * 🪟 chore: Sort the Card Spec's Imports * 🪟 fix: Draw the Card's Row as a Picture That Registers, Claims and Reveals Nothing * 🪟 test: Give the Artifact Preview Test the Props Its Type Requires * 🪟 refactor: Keep the Shared Follower Registry in Provider-Scoped Jotai Atoms * 👀 fix: Look Again for a Run the Caller Knows Of Before Taking It to Have No Stream
This commit is contained in:
parent
0e626948c4
commit
b2244f7b53
16 changed files with 1282 additions and 363 deletions
|
|
@ -3,6 +3,7 @@ import throttle from 'lodash/throttle';
|
|||
import { visit } from 'unist-util-visit';
|
||||
import { useSetRecoilState } from 'recoil';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import { useIsPartsPreview } from '@librechat/chat/react';
|
||||
import type { Pluggable } from 'unified';
|
||||
import type { Artifact } from '~/common';
|
||||
import { useMessageContext, useArtifactContext } from '~/Providers';
|
||||
|
|
@ -48,6 +49,8 @@ export function Artifact({
|
|||
node: unknown;
|
||||
}) {
|
||||
const location = useLocation();
|
||||
/** A picture of a row drawn elsewhere: the row itself registers the artifact. */
|
||||
const isPreview = useIsPartsPreview();
|
||||
const { messageId } = useMessageContext();
|
||||
const { getNextIndex, resetCounter } = useArtifactContext();
|
||||
const artifactIndex = useRef(getNextIndex(false)).current;
|
||||
|
|
@ -89,7 +92,7 @@ export function Artifact({
|
|||
lastUpdateTime: now,
|
||||
};
|
||||
|
||||
if (!isArtifactRoute(location.pathname)) {
|
||||
if (isPreview || !isArtifactRoute(location.pathname)) {
|
||||
return setArtifact(currentArtifact);
|
||||
}
|
||||
|
||||
|
|
@ -118,6 +121,7 @@ export function Artifact({
|
|||
messageId,
|
||||
artifactIndex,
|
||||
location.pathname,
|
||||
isPreview,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,76 @@
|
|||
import React from 'react';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { RecoilRoot, useRecoilValue } from 'recoil';
|
||||
import { act, render } from '@testing-library/react';
|
||||
import { PartsPreviewContext } from '@librechat/chat/react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { MessageContext, ArtifactProvider } from '~/Providers';
|
||||
import { artifactsState } from '~/store/artifacts';
|
||||
import { Artifact } from '../Artifact';
|
||||
|
||||
jest.mock('../ArtifactButton', () => ({
|
||||
__esModule: true,
|
||||
default: () => null,
|
||||
}));
|
||||
|
||||
let registered: Record<string, unknown> | null | undefined;
|
||||
|
||||
function Registry(): null {
|
||||
registered = useRecoilValue(artifactsState) as Record<string, unknown> | null;
|
||||
return null;
|
||||
}
|
||||
|
||||
const message = {
|
||||
messageId: 'message-1',
|
||||
conversationId: 'conversation-1',
|
||||
partIndex: 0,
|
||||
isExpanded: false,
|
||||
isSubmitting: false,
|
||||
isLatestMessage: false,
|
||||
} as unknown as React.ContextType<typeof MessageContext>;
|
||||
|
||||
const page = (ui: ReactNode) => (
|
||||
<RecoilRoot>
|
||||
<MemoryRouter initialEntries={['/c/conversation-1']}>
|
||||
<MessageContext.Provider value={message}>
|
||||
<ArtifactProvider>
|
||||
<Registry />
|
||||
{ui}
|
||||
</ArtifactProvider>
|
||||
</MessageContext.Provider>
|
||||
</MemoryRouter>
|
||||
</RecoilRoot>
|
||||
);
|
||||
|
||||
const artifact = (
|
||||
<Artifact id="" lastUpdateTime={0} identifier="chart" title="Chart" type="text/html" node={null}>
|
||||
{'<p>hello</p>'}
|
||||
</Artifact>
|
||||
);
|
||||
|
||||
const settle = () =>
|
||||
act(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 80));
|
||||
});
|
||||
|
||||
describe('Artifact registration', () => {
|
||||
beforeEach(() => {
|
||||
registered = undefined;
|
||||
});
|
||||
|
||||
it('registers an artifact a message row draws', async () => {
|
||||
render(page(artifact));
|
||||
await settle();
|
||||
|
||||
expect(Object.keys(registered ?? {})).toEqual(['chart_text/html_chart_message-1']);
|
||||
});
|
||||
|
||||
it('registers nothing for a picture of a row drawn elsewhere', async () => {
|
||||
render(
|
||||
page(<PartsPreviewContext.Provider value={true}>{artifact}</PartsPreviewContext.Provider>),
|
||||
);
|
||||
await settle();
|
||||
|
||||
expect(Object.keys(registered ?? {})).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
|
@ -9,7 +9,6 @@ import { useMessageContext } from '~/Providers/MessageContext';
|
|||
import { useShareContext } from '~/Providers/ShareContext';
|
||||
import MessageIcon from '~/components/Share/MessageIcon';
|
||||
import { MCPAppViews } from '~/components/MCPUIResource';
|
||||
import { useMCPServerNames } from '~/hooks/MCP';
|
||||
import { useLocalize } from '~/hooks';
|
||||
|
||||
const agentMessage = { endpoint: EModelEndpoint.agents, isCreatedByUser: false } as TMessage;
|
||||
|
|
@ -28,7 +27,6 @@ export default function SubagentCall(props: SubagentCallProps) {
|
|||
const message = useMessageContext();
|
||||
const share = useShareContext();
|
||||
const agentsMap = useAgentsMapContext();
|
||||
const mcpServerNames = useMCPServerNames();
|
||||
const translate = useLocalize();
|
||||
const localize = useCallback<SubagentCallContext['localize']>(
|
||||
(key, values) => translate(key as TranslationKeys, values),
|
||||
|
|
@ -40,7 +38,6 @@ export default function SubagentCall(props: SubagentCallProps) {
|
|||
{...share}
|
||||
message={message}
|
||||
agentsMap={agentsMap}
|
||||
mcpServerNames={mcpServerNames}
|
||||
localize={localize}
|
||||
renderAgentIcon={renderAgentIcon}
|
||||
renderAttachments={renderAttachments}
|
||||
|
|
|
|||
|
|
@ -3500,11 +3500,6 @@
|
|||
"com_ui_subagent_trigger_truncated": "Trigger summary shortened for display.",
|
||||
"com_ui_subagent_turn": "Turn",
|
||||
"com_ui_subagent_running": "Running agent",
|
||||
"com_ui_subagent_ticker_error": "Error",
|
||||
"com_ui_subagent_ticker_reasoning": "Reasoning",
|
||||
"com_ui_subagent_ticker_tool_done": "done",
|
||||
"com_ui_subagent_ticker_using": "Using",
|
||||
"com_ui_subagent_ticker_writing": "Writing",
|
||||
"com_ui_subagent_waiting": "Working…",
|
||||
"com_ui_submit": "Submit",
|
||||
"com_ui_submit_decisions": "Submit {{0}} decisions",
|
||||
|
|
|
|||
|
|
@ -164,16 +164,29 @@ test.describe('detached subagent activity', () => {
|
|||
await expect(cards).toHaveCount(2, { timeout: 30_000 });
|
||||
await expect(cards.first()).toHaveAttribute('data-subagent-thread', /.+/);
|
||||
const firstThreadId = (await cards.first().getAttribute('data-subagent-thread')) ?? '';
|
||||
const threadReadPromise = page.waitForResponse((candidate) => {
|
||||
const read = THREAD_MESSAGES_PATH.exec(new URL(candidate.url()).pathname);
|
||||
return read != null && decodeURIComponent(read[1]) === firstThreadId;
|
||||
});
|
||||
const attachesOf = (threadId: string) =>
|
||||
streamAttaches.filter((attached) => attached === threadId).length;
|
||||
|
||||
/** With no panel open, each running child's card shows the row its thread is on: the
|
||||
* thread's own content, drawn by the thread's renderer, one row at a time. The page
|
||||
* follows each child once for that. */
|
||||
const rows = page.locator('[data-subagent-preview]');
|
||||
await expect(rows).toHaveCount(2, { timeout: 30_000 });
|
||||
await expect(rows.first()).toContainText(/child-1-phase-\d+/);
|
||||
await expect(rows.nth(1)).toContainText(/child-2-phase-\d+/);
|
||||
await expect(cards.first()).toContainText('Running');
|
||||
await expect.poll(() => messageReads).toContain(firstThreadId);
|
||||
/** A collapsed group shows no cards and follows nothing, so the count so far depends on
|
||||
* how long the group stood open before the parent's turn ended. What is fixed is that the
|
||||
* child is being followed now, and that opening it adds no stream of its own. */
|
||||
const followedByCard = attachesOf(firstThreadId);
|
||||
expect(followedByCard).toBeGreaterThanOrEqual(1);
|
||||
await cards.first().click();
|
||||
|
||||
/** The child's thread opens as a conversation: its messages, read through the parent, and
|
||||
* its own generation stream while it runs. The bounded activity feed is not read at all. */
|
||||
* the generation stream the card was already reading. The bounded activity feed is not
|
||||
* read at all. */
|
||||
const panel = childActivityPanel(page);
|
||||
expect((await threadReadPromise).ok()).toBeTruthy();
|
||||
await expect(panel).toBeVisible();
|
||||
await expect(panel).toContainText('child-1-phase-10');
|
||||
await expect(panel.getByText('Running', { exact: true })).toHaveCount(0);
|
||||
|
|
@ -182,12 +195,13 @@ test.describe('detached subagent activity', () => {
|
|||
timeout: 30_000,
|
||||
});
|
||||
await expect(panel.getByText('Completed', { exact: true })).toHaveCount(0);
|
||||
const attachesOf = (threadId: string) =>
|
||||
streamAttaches.filter((attached) => attached === threadId).length;
|
||||
/** At most one attachment, and none added once the run is over: a finished child is read
|
||||
* from its stored messages, and a running one is followed by a single stream. */
|
||||
/** One attachment for the card and the panel together, and none added once the run is
|
||||
* over: a finished child is read from its stored messages. Its card drops its row. */
|
||||
const attaches = attachesOf(firstThreadId);
|
||||
expect(attaches).toBeLessThanOrEqual(1);
|
||||
expect(attaches).toBe(followedByCard);
|
||||
await expect(
|
||||
cards.first().locator('xpath=..').locator('[data-subagent-preview]'),
|
||||
).toHaveCount(0);
|
||||
await page.waitForTimeout(ACTIVITY_RECONNECT_GUARD_MS);
|
||||
expect(attachesOf(firstThreadId)).toBe(attaches);
|
||||
expect(messageReads).toContain(firstThreadId);
|
||||
|
|
@ -228,9 +242,12 @@ test.describe('detached subagent activity', () => {
|
|||
});
|
||||
});
|
||||
|
||||
/** A subagent card's row is a picture of the child's thread, not part of this one: its folds
|
||||
* take no pointer and are not this history's to expand. */
|
||||
const NOT_A_PREVIEW = ':not([data-subagent-preview] *)';
|
||||
const HISTORY_FOLDS =
|
||||
'[data-fold-root] > div > button[aria-expanded="false"]:visible, ' +
|
||||
'[data-testid="activity-phase-card"] > div > div > button[aria-expanded="false"]:visible';
|
||||
`[data-fold-root] > div > button[aria-expanded="false"]${NOT_A_PREVIEW}:visible, ` +
|
||||
`[data-testid="activity-phase-card"] > div > div > button[aria-expanded="false"]${NOT_A_PREVIEW}:visible`;
|
||||
|
||||
/** How long a click waits for a fold that was counted a moment ago. */
|
||||
const FOLD_CLICK_TIMEOUT_MS = 1_000;
|
||||
|
|
|
|||
|
|
@ -3,30 +3,37 @@ import { useSetAtom } from 'jotai';
|
|||
import { Button, cn } from '@librechat/client';
|
||||
import { ChevronRight, Users } from 'lucide-react';
|
||||
import { ContentTypes } from 'librechat-data-provider';
|
||||
import type { PartMetadata, TAttachment, TMessageContentParts } from 'librechat-data-provider';
|
||||
import type {
|
||||
TMessage,
|
||||
PartMetadata,
|
||||
TAttachment,
|
||||
TMessageContentParts,
|
||||
} from 'librechat-data-provider';
|
||||
import type { Dispatch, ReactNode, SetStateAction } from 'react';
|
||||
import type { Agent } from 'librechat-data-provider';
|
||||
import type { ReactNode } from 'react';
|
||||
import type { MessagePartMessage, MessagePartsHost, ToolCallChrome } from '../../react/host';
|
||||
import type { SubagentContentPreview } from '../../react/subagents/state';
|
||||
import type { SubagentTickerLine } from '../../core/subagents/content';
|
||||
import {
|
||||
activeSubagentPanel,
|
||||
subagentProgressKey,
|
||||
useSubagentProgress,
|
||||
} from '../../react/subagents/state';
|
||||
import { isLiveSubagentStatus, subagentStatusLabelKey } from '../../react/subagents/status';
|
||||
import { MessagePartsHostProvider, useMessagePartsHost } from '../../react/host';
|
||||
import { isSelfSpawn as isSelfSpawnType } from '../../react/subagents/author';
|
||||
import { parseSubagentBackgroundHandle } from '../../core/parts/handle';
|
||||
import { lastVisibleContentIdx } from '../../core/parts/activityLabels';
|
||||
import { resolveSubagentAgentId } from '../../react/subagents/identity';
|
||||
import { subagentStatusLabelKey } from '../../react/subagents/status';
|
||||
import { tailOverflowDirection } from '../../core/subagents/content';
|
||||
import { useOpenSubagentPanel } from '../../react/subagents/surface';
|
||||
import { useParentSubagents } from '../../react/subagents/parents';
|
||||
import { useThreadInterest } from '../../react/subagents/follows';
|
||||
import { getSubagentPrompt } from '../../react/subagents/prompt';
|
||||
import { PartsPreviewContext } from '../../react/parts/preview';
|
||||
import { FailedRevealContext, useFailedReveal } from './reveal';
|
||||
import { useToolCallIntent } from '../../react/parts/intent';
|
||||
import { parseToolName } from '../../core/parts/toolLabels';
|
||||
import { useBranchTailSelect } from '../../react/latest';
|
||||
import { useToolPreparation } from './preparation';
|
||||
import { isError } from '../../core/parts/output';
|
||||
import { useFailedReveal } from './reveal';
|
||||
import { FOLD_GLYPH_CLASS } from './rows';
|
||||
|
||||
export interface SubagentCallProps {
|
||||
|
|
@ -55,10 +62,7 @@ export interface SubagentCallProps {
|
|||
}
|
||||
|
||||
/** App subscriptions arrive as values; render callbacks contain no card behavior. */
|
||||
export type SubagentCallContext = Pick<
|
||||
ToolCallChrome,
|
||||
'localize' | 'mcpServerNames' | 'renderAttachments'
|
||||
> &
|
||||
export type SubagentCallContext = Pick<ToolCallChrome, 'localize' | 'renderAttachments'> &
|
||||
Pick<MessagePartsHost, 'renderAgentIcon'> & {
|
||||
message: Pick<MessagePartMessage, 'messageId' | 'conversationId' | 'partIndex'>;
|
||||
isSharedConvo?: boolean;
|
||||
|
|
@ -66,7 +70,6 @@ export type SubagentCallContext = Pick<
|
|||
agentsMap?: Record<string, Agent | undefined>;
|
||||
};
|
||||
|
||||
const TICKER_MAX_LINES = 3;
|
||||
/** Trailing-edge refresh window for the live preview once the ticker has
|
||||
* enough text to fill the row. Keeps long streaming lines from repainting
|
||||
* every token while still letting the collapsed subagent UI feel responsive. */
|
||||
|
|
@ -76,7 +79,7 @@ export const SUBAGENT_TICKER_THROTTLE_MS = 400;
|
|||
* streams the rest of the sentence. The pass-through lets early
|
||||
* tokens appear right away, and throttling only kicks in once the
|
||||
* preview is long enough to "fill the container". */
|
||||
const TICKER_PASSTHROUGH_CHARS = 120;
|
||||
const PREVIEW_PASSTHROUGH_CHARS = 120;
|
||||
|
||||
/**
|
||||
* Trailing-edge throttle for the ticker. Forwards `value` at most once per
|
||||
|
|
@ -188,7 +191,6 @@ export default function SubagentCall({
|
|||
isSharedConvo,
|
||||
shareId,
|
||||
localize,
|
||||
mcpServerNames,
|
||||
agentsMap,
|
||||
renderAgentIcon,
|
||||
renderAttachments,
|
||||
|
|
@ -211,7 +213,13 @@ export default function SubagentCall({
|
|||
subagentType,
|
||||
progress?.subagentKind ?? subagentIdentity?.subagentKind,
|
||||
);
|
||||
const subagentAgentId = resolveSubagentAgentId(progress, subagentIdentity);
|
||||
/** A detached child's identity as the parent's index reports it, once the parent's own stream
|
||||
* that named it is gone. */
|
||||
const { byThreadId } = useParentSubagents();
|
||||
const indexedChild =
|
||||
backgroundHandle == null ? undefined : byThreadId.get(backgroundHandle.subagent_thread_id);
|
||||
const subagentAgentId =
|
||||
resolveSubagentAgentId(progress, subagentIdentity) ?? indexedChild?.agentId;
|
||||
const subagentAgent = subagentAgentId ? agentsMap?.[subagentAgentId] : undefined;
|
||||
/**
|
||||
* Tri-state status resolution, aligned with `ToolCall.tsx`:
|
||||
|
|
@ -250,33 +258,15 @@ export default function SubagentCall({
|
|||
const running = !finished && !cancelled;
|
||||
const detachedStatusUnknown = backgroundHandle != null && progress == null && !isSubmitting;
|
||||
|
||||
/** Last `TICKER_MAX_LINES` lines from the atom's incrementally-built
|
||||
* ticker state, so history isn't lost to any event trimming. */
|
||||
const tickerLines = useMemo<SubagentTickerLine[]>(() => {
|
||||
const lines = progress?.tickerState?.lines ?? [];
|
||||
return lines.slice(-TICKER_MAX_LINES);
|
||||
}, [progress?.tickerState?.lines]);
|
||||
/** The child's newest part: the row it is on right now. */
|
||||
const tailPart = useMemo(() => {
|
||||
const parts = (progress?.contentParts ?? []) as TMessageContentParts[];
|
||||
const index = lastVisibleContentIdx(parts);
|
||||
return index < 0 ? undefined : { part: parts[index], index };
|
||||
}, [progress?.contentParts]);
|
||||
|
||||
/** Only throttle once the running buffer is wide enough to "fill the
|
||||
* container". Pre-threshold updates pass through so the user sees
|
||||
* early tokens immediately, not a static "Reasoning: I" while more
|
||||
* text piles up behind the throttle. */
|
||||
const shouldThrottleTicker = useMemo(() => {
|
||||
if (!running) return false;
|
||||
const liveBody = tickerLines.reduce((max, line) => {
|
||||
if (line.kind === 'writing' || line.kind === 'reasoning') {
|
||||
return Math.max(max, line.body.length);
|
||||
}
|
||||
return max;
|
||||
}, 0);
|
||||
return liveBody >= TICKER_PASSTHROUGH_CHARS;
|
||||
}, [running, tickerLines]);
|
||||
|
||||
const displayedTickerLines = useTickerThrottle(
|
||||
tickerLines,
|
||||
SUBAGENT_TICKER_THROTTLE_MS,
|
||||
shouldThrottleTicker,
|
||||
);
|
||||
const preview = useThrottledRow(tailPart, running);
|
||||
const showPreview = running && preview != null;
|
||||
|
||||
const prompt = getSubagentPrompt(args);
|
||||
|
||||
|
|
@ -419,100 +409,107 @@ export default function SubagentCall({
|
|||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
variant="activity-card"
|
||||
data-running={running && !detachedStatusUnknown}
|
||||
onClick={openDetails}
|
||||
disabled={!canOpenDetails}
|
||||
data-subagent-thread={
|
||||
canOpenDurablePanel ? backgroundHandle?.subagent_thread_id : undefined
|
||||
}
|
||||
data-subagent-tool-call={toolCallId}
|
||||
data-subagent-parent-message={parentMessageId}
|
||||
data-subagent-part-index={partIndex}
|
||||
className={cn('my-2', canOpenDetails && 'group')}
|
||||
aria-label={detachedStatusUnknown ? undefined : cardLabel}
|
||||
>
|
||||
<div className="text-text-primary flex w-full min-w-0 items-center gap-2 text-sm font-medium">
|
||||
<div
|
||||
className={cn(
|
||||
FOLD_GLYPH_CLASS,
|
||||
'flex h-5 w-5 shrink-0 items-center justify-center overflow-hidden rounded-full',
|
||||
running &&
|
||||
!subagentAgent &&
|
||||
'text-text-primary animate-pulse motion-reduce:animate-none',
|
||||
)}
|
||||
aria-hidden="true"
|
||||
>
|
||||
{subagentAgent ? renderAgentIcon(subagentAgent) : <Users size={14} />}
|
||||
</div>
|
||||
{subagentNameLabel ? (
|
||||
<>
|
||||
<span
|
||||
className="max-w-[50%] min-w-0 shrink truncate font-semibold"
|
||||
title={subagentNameLabel}
|
||||
>
|
||||
{subagentNameLabel}
|
||||
</span>
|
||||
<span
|
||||
className="text-text-secondary min-w-0 flex-1 truncate font-normal"
|
||||
title={detachedStatusUnknown ? undefined : headerText}
|
||||
>
|
||||
{detachedStatusUnknown && backgroundHandle != null ? (
|
||||
<DetachedTaskStatus
|
||||
threadId={backgroundHandle.subagent_thread_id}
|
||||
taskId={backgroundHandle.background_task_id}
|
||||
fallback={headerText}
|
||||
localize={localize}
|
||||
/>
|
||||
) : (
|
||||
headerText
|
||||
)}
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span
|
||||
className="min-w-0 truncate"
|
||||
title={detachedStatusUnknown ? undefined : headerText}
|
||||
>
|
||||
{detachedStatusUnknown && backgroundHandle != null ? (
|
||||
<DetachedTaskStatus
|
||||
threadId={backgroundHandle.subagent_thread_id}
|
||||
taskId={backgroundHandle.background_task_id}
|
||||
fallback={headerText}
|
||||
localize={localize}
|
||||
/>
|
||||
) : (
|
||||
headerText
|
||||
)}
|
||||
</span>
|
||||
<span className="flex-1" />
|
||||
</>
|
||||
)}
|
||||
{canOpenDetails && (
|
||||
<ChevronRight
|
||||
size={14}
|
||||
className="text-text-secondary shrink-0 transition group-hover:translate-x-0.5 rtl:-scale-x-100 rtl:group-hover:-translate-x-0.5"
|
||||
<div className={cn('relative my-2', PREVIEW_ROOM)}>
|
||||
<Button
|
||||
variant="activity-card"
|
||||
data-running={running && !detachedStatusUnknown}
|
||||
onClick={openDetails}
|
||||
disabled={!canOpenDetails}
|
||||
data-subagent-thread={
|
||||
canOpenDurablePanel ? backgroundHandle?.subagent_thread_id : undefined
|
||||
}
|
||||
data-subagent-tool-call={toolCallId}
|
||||
data-subagent-parent-message={parentMessageId}
|
||||
data-subagent-part-index={partIndex}
|
||||
className={cn(canOpenDetails && 'group')}
|
||||
aria-label={detachedStatusUnknown ? undefined : cardLabel}
|
||||
>
|
||||
<div className="text-text-primary flex w-full min-w-0 items-center gap-2 text-sm font-medium">
|
||||
<div
|
||||
className={cn(
|
||||
FOLD_GLYPH_CLASS,
|
||||
'flex h-5 w-5 shrink-0 items-center justify-center overflow-hidden rounded-full',
|
||||
running &&
|
||||
!subagentAgent &&
|
||||
'text-text-primary animate-pulse motion-reduce:animate-none',
|
||||
)}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
>
|
||||
{subagentAgent ? renderAgentIcon(subagentAgent) : <Users size={14} />}
|
||||
</div>
|
||||
{subagentNameLabel ? (
|
||||
<>
|
||||
<span
|
||||
className="max-w-[50%] min-w-0 shrink truncate font-semibold"
|
||||
title={subagentNameLabel}
|
||||
>
|
||||
{subagentNameLabel}
|
||||
</span>
|
||||
<span
|
||||
className="text-text-secondary min-w-0 flex-1 truncate font-normal"
|
||||
title={detachedStatusUnknown ? undefined : headerText}
|
||||
>
|
||||
{detachedStatusUnknown && backgroundHandle != null ? (
|
||||
<DetachedTaskStatus
|
||||
threadId={backgroundHandle.subagent_thread_id}
|
||||
taskId={backgroundHandle.background_task_id}
|
||||
fallback={headerText}
|
||||
localize={localize}
|
||||
/>
|
||||
) : (
|
||||
headerText
|
||||
)}
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span
|
||||
className="min-w-0 truncate"
|
||||
title={detachedStatusUnknown ? undefined : headerText}
|
||||
>
|
||||
{detachedStatusUnknown && backgroundHandle != null ? (
|
||||
<DetachedTaskStatus
|
||||
threadId={backgroundHandle.subagent_thread_id}
|
||||
taskId={backgroundHandle.background_task_id}
|
||||
fallback={headerText}
|
||||
localize={localize}
|
||||
/>
|
||||
) : (
|
||||
headerText
|
||||
)}
|
||||
</span>
|
||||
<span className="flex-1" />
|
||||
</>
|
||||
)}
|
||||
{canOpenDetails && (
|
||||
<ChevronRight
|
||||
size={14}
|
||||
className="text-text-secondary shrink-0 transition group-hover:translate-x-0.5 rtl:-scale-x-100 rtl:group-hover:-translate-x-0.5"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<ul className="text-text-secondary w-full space-y-0.5 ps-5 font-mono text-xs">
|
||||
{displayedTickerLines.length === 0 && running ? (
|
||||
<li className="truncate opacity-70">{localize('com_ui_subagent_waiting')}</li>
|
||||
{!showPreview && running ? (
|
||||
<div className="text-text-secondary w-full truncate text-sm opacity-70">
|
||||
{localize('com_ui_subagent_waiting')}
|
||||
</div>
|
||||
) : null}
|
||||
{displayedTickerLines.map((line, i) => (
|
||||
<TickerLineView
|
||||
key={`${i}-${tickerLineKey(line)}`}
|
||||
line={line}
|
||||
localize={localize}
|
||||
mcpServerNames={mcpServerNames}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
</Button>
|
||||
</Button>
|
||||
{showPreview ? (
|
||||
<SubagentPreview
|
||||
key={preview.index}
|
||||
part={preview.part}
|
||||
messageId={`${parentMessageId}:${toolCallId}:${partIndex}:preview`}
|
||||
/>
|
||||
) : null}
|
||||
{!showPreview && canOpenDurablePanel && backgroundHandle != null ? (
|
||||
<DetachedPreview
|
||||
threadId={backgroundHandle.subagent_thread_id}
|
||||
taskId={backgroundHandle.background_task_id}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{!hideAttachments && attachments != null && attachments.length > 0
|
||||
? renderAttachments(attachments)
|
||||
|
|
@ -538,14 +535,93 @@ function DetachedTaskStatus({
|
|||
taskId: string;
|
||||
fallback: string;
|
||||
}): ReactNode {
|
||||
const { byThreadId } = useParentSubagents();
|
||||
const child = byThreadId.get(threadId);
|
||||
const status =
|
||||
child?.tasks.find((task) => task.taskId === taskId)?.status ??
|
||||
(child?.latestTaskId === taskId ? child.status : undefined);
|
||||
const status = useDetachedStatus(threadId, taskId);
|
||||
return <>{status == null ? fallback : localize(subagentStatusLabelKey(status))}</>;
|
||||
}
|
||||
|
||||
/** A detached task's status in the parent's subagent index, when the index has one. */
|
||||
function useDetachedStatus(threadId: string, taskId: string) {
|
||||
const { byThreadId, discover } = useParentSubagents();
|
||||
const child = byThreadId.get(threadId);
|
||||
/** A child dispatched after the index was last read is not in it; the index is told. */
|
||||
useEffect(() => {
|
||||
if (child == null) {
|
||||
discover(threadId);
|
||||
}
|
||||
}, [child, discover, threadId]);
|
||||
return (
|
||||
child?.tasks.find((task) => task.taskId === taskId)?.status ??
|
||||
(child?.latestTaskId === taskId ? child.status : undefined)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a reply's newest row is: its last part that draws something. A batch of tool calls ends
|
||||
* with an empty label reservation, which draws nothing until its label arrives.
|
||||
*/
|
||||
const pickTailIndex = (tail: TMessage | null): number | null => {
|
||||
if (tail == null || tail.isCreatedByUser) return null;
|
||||
const index = lastVisibleContentIdx(tail.content);
|
||||
return index < 0 ? null : index;
|
||||
};
|
||||
|
||||
const pickTailPart = (tail: TMessage | null): TMessageContentParts | null => {
|
||||
const index = pickTailIndex(tail);
|
||||
return index == null ? null : (tail?.content?.[index] ?? null);
|
||||
};
|
||||
|
||||
/**
|
||||
* A detached child's row, read from its thread's messages wherever something is following that
|
||||
* thread. Its own leaf, so a streamed token re-renders this row alone and never the card.
|
||||
*/
|
||||
function DetachedPreview({ threadId, taskId }: { threadId: string; taskId: string }): ReactNode {
|
||||
const status = useDetachedStatus(threadId, taskId);
|
||||
const live = status != null && isLiveSubagentStatus(status);
|
||||
/**
|
||||
* A running child is followed for its row; the page follows it once, with or without a panel.
|
||||
* Its messages outlive the following: a child the page has no room to preview keeps what was
|
||||
* last read for it, which is not what it is doing now, so its row is shown only while it is
|
||||
* being followed.
|
||||
*/
|
||||
const followed = useThreadInterest(threadId, { live: true, enabled: live, passive: true });
|
||||
const part = useBranchTailSelect(threadId, threadId, pickTailPart);
|
||||
const index = useBranchTailSelect(threadId, threadId, pickTailIndex);
|
||||
const row = useMemo(
|
||||
() => (part == null || index == null ? undefined : { part, index }),
|
||||
[part, index],
|
||||
);
|
||||
const shown = useThrottledRow(row, live && followed);
|
||||
if (shown == null || !live || !followed) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<SubagentPreview
|
||||
key={shown.index}
|
||||
part={shown.part}
|
||||
messageId={`${threadId}:${taskId}:preview`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
type PreviewRow = { part: TMessageContentParts; index: number };
|
||||
|
||||
/**
|
||||
* A child's row at the pace the card redraws it. Short text passes straight through, so the
|
||||
* first tokens appear at once; once the live text is long enough to fill the row it refreshes on
|
||||
* the throttle, wherever the row comes from, instead of on every token.
|
||||
*/
|
||||
function useThrottledRow(row: PreviewRow | undefined, running: boolean): PreviewRow | undefined {
|
||||
const throttled = useMemo(() => {
|
||||
if (!running || row == null) return false;
|
||||
const { part } = row;
|
||||
let text: unknown = '';
|
||||
if (part.type === ContentTypes.TEXT) text = part.text;
|
||||
else if (part.type === ContentTypes.THINK) text = part.think;
|
||||
return typeof text === 'string' && text.length >= PREVIEW_PASSTHROUGH_CHARS;
|
||||
}, [running, row]);
|
||||
return useTickerThrottle(row, SUBAGENT_TICKER_THROTTLE_MS, throttled);
|
||||
}
|
||||
|
||||
function extractSubagentType(args: SubagentCallProps['args']): string {
|
||||
if (typeof args === 'string') {
|
||||
try {
|
||||
|
|
@ -559,148 +635,77 @@ function extractSubagentType(args: SubagentCallProps['args']): string {
|
|||
return a?.subagent_type ?? 'agent';
|
||||
}
|
||||
|
||||
/** Stable key for a ticker line. Helps React reuse the DOM node across
|
||||
* in-place updates to the same live `writing` / `reasoning` line, and
|
||||
* gives tool-call lines a stable identity by tool name. */
|
||||
function tickerLineKey(line: SubagentTickerLine): string {
|
||||
switch (line.kind) {
|
||||
case 'writing':
|
||||
case 'reasoning':
|
||||
return line.kind;
|
||||
case 'using_tool':
|
||||
return `using:${line.toolNames.join(',')}`;
|
||||
case 'tool_complete':
|
||||
return `done:${line.toolName}`;
|
||||
case 'error':
|
||||
return `error:${line.message ?? ''}`;
|
||||
}
|
||||
}
|
||||
|
||||
/** Inline code-style tool-name badge. Matches the monospace styling of
|
||||
* the ticker itself but with a subtle background so the tool identifier
|
||||
* reads as a "code" token rather than plain prose. */
|
||||
function ToolNameBadge({ name }: { name: string }): ReactNode {
|
||||
return (
|
||||
<code className="bg-surface-tertiary text-text-primary shrink-0 rounded px-1">{name}</code>
|
||||
);
|
||||
}
|
||||
|
||||
/** Render a single tool id as a compact JSX fragment: MCP tools split
|
||||
* into `<server> · <code>toolName</code>`, native tools resolve their
|
||||
* friendly name via `FRIENDLY_NAME_KEYS`, unknown ids fall back to a
|
||||
* bare code badge of the raw name. */
|
||||
function ToolIdentifier({
|
||||
rawName,
|
||||
localize,
|
||||
mcpServerNames,
|
||||
}: {
|
||||
rawName: string;
|
||||
localize: (key: string) => string;
|
||||
mcpServerNames?: readonly string[];
|
||||
}): ReactNode {
|
||||
const parsed = parseToolName(rawName, mcpServerNames);
|
||||
if (parsed.mcpServer) {
|
||||
return (
|
||||
<span className="inline-flex min-w-0 shrink items-baseline gap-1">
|
||||
<span className="truncate">{parsed.mcpServer}</span>
|
||||
<span className="text-text-tertiary shrink-0">{'\u00b7'}</span>
|
||||
<ToolNameBadge name={parsed.toolName} />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (parsed.friendlyKey) {
|
||||
return <span className="truncate">{localize(parsed.friendlyKey)}</span>;
|
||||
}
|
||||
return <ToolNameBadge name={parsed.toolName} />;
|
||||
}
|
||||
const PREVIEW_ROW_HEIGHT = 'h-8';
|
||||
/** No request to reveal a failure reaches a picture, and it claims no focus. */
|
||||
const NO_REVEAL = { tick: 0, claimFocus: null };
|
||||
/** A tool artifact is always some other row's: a picture never draws it and never takes it. */
|
||||
const PICTURE_CLAIM: [string | null, Dispatch<SetStateAction<string | null>>] = [
|
||||
'subagent-preview',
|
||||
() => undefined,
|
||||
];
|
||||
const useNoClaim = (): [string | null, Dispatch<SetStateAction<string | null>>] => PICTURE_CLAIM;
|
||||
/**
|
||||
* The line above the row dissolves at the top edge instead of being cut through. A mask stencil,
|
||||
* not paint: only its alpha is read, so it is not a theme color.
|
||||
*/
|
||||
const PREVIEW_FADE =
|
||||
'[mask-image:linear-gradient(to_bottom,transparent,rgb(var(--black)/1)_0.625rem)]';
|
||||
/** Room under the header for the row, kept by the card only while a row is drawn over it. */
|
||||
const PREVIEW_ROOM = '[&:has([data-subagent-preview])>button]:pb-11';
|
||||
/** `inert` as an attribute: React 18's types do not know it. */
|
||||
const INERT: Record<string, string> = { inert: '' };
|
||||
|
||||
/**
|
||||
* Renderer for one ticker line. Writing is the default visible activity, so
|
||||
* it renders without a redundant prefix. Reasoning retains its semantic label.
|
||||
* Streaming bodies run the outer box opposite to the text direction so the
|
||||
* oldest characters clip and the newest stay visible; `text-end` of that box is
|
||||
* the text's own start, so a line that fits stays where it reads from. The text
|
||||
* sits in an isolated `dir="auto"` span so its punctuation is never reordered.
|
||||
*
|
||||
* Tool lines (`using_tool`, `tool_complete`) go through `ToolIdentifier`
|
||||
* so MCP-hosted tools render as `<server> · <tool>` badges and native
|
||||
* tools use their friendly names, matching the delimiter-aware
|
||||
* rendering the main tool UI already uses.
|
||||
* The row the child is on right now, drawn by the renderer the thread itself uses and shown one
|
||||
* row at a time: the same tool row, reasoning row or text a reader sees after opening the child,
|
||||
* held to the card's last line. It is a picture of that row, not a control: it sits over the
|
||||
* card instead of inside its button, takes no pointer or focus, and is hidden from assistive
|
||||
* technology, which reads the card's label.
|
||||
*/
|
||||
function TailText({ text }: { text: string }): ReactNode {
|
||||
function SubagentPreview({
|
||||
part,
|
||||
messageId,
|
||||
}: {
|
||||
part: TMessageContentParts;
|
||||
messageId: string;
|
||||
}): ReactNode {
|
||||
const host = useMessagePartsHost();
|
||||
const content = useMemo(() => [part], [part]);
|
||||
const pictureHost = useMemo(() => ({ ...host, useToolArtifactClaim: useNoClaim }), [host]);
|
||||
return (
|
||||
<span
|
||||
dir={tailOverflowDirection(text)}
|
||||
className="min-w-0 flex-1 overflow-hidden text-end text-ellipsis whitespace-nowrap"
|
||||
<div
|
||||
{...INERT}
|
||||
aria-hidden="true"
|
||||
data-subagent-preview
|
||||
className={cn(
|
||||
'pointer-events-none absolute inset-x-[calc(0.75rem+1px)] bottom-[calc(0.5rem+1px)] overflow-hidden',
|
||||
PREVIEW_ROW_HEIGHT,
|
||||
PREVIEW_FADE,
|
||||
)}
|
||||
>
|
||||
<bdi dir="auto" className="[unicode-bidi:isolate]">
|
||||
{text}
|
||||
</bdi>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function TickerLineView({
|
||||
line,
|
||||
localize,
|
||||
mcpServerNames,
|
||||
}: { line: SubagentTickerLine } & Pick<
|
||||
SubagentCallContext,
|
||||
'localize' | 'mcpServerNames'
|
||||
>): ReactNode {
|
||||
if (line.kind === 'writing') {
|
||||
return (
|
||||
<li className="text-text-primary flex w-full items-baseline overflow-hidden">
|
||||
<TailText text={line.body} />
|
||||
</li>
|
||||
);
|
||||
}
|
||||
if (line.kind === 'reasoning') {
|
||||
return (
|
||||
<li className="text-text-primary flex w-full items-baseline gap-1 overflow-hidden">
|
||||
<span className="shrink-0">{`${localize('com_ui_subagent_ticker_reasoning')}:`}</span>
|
||||
<TailText text={line.body} />
|
||||
</li>
|
||||
);
|
||||
}
|
||||
if (line.kind === 'using_tool') {
|
||||
const prefix = localize('com_ui_subagent_ticker_using');
|
||||
return (
|
||||
<li className="flex w-full items-baseline gap-1 overflow-hidden whitespace-nowrap">
|
||||
<span className="shrink-0">{prefix}</span>
|
||||
<span className="flex min-w-0 flex-1 items-baseline gap-1 overflow-hidden">
|
||||
{line.toolNames.map((name, i) => (
|
||||
<span key={`${i}-${name}`} className="flex min-w-0 items-baseline gap-1">
|
||||
{i > 0 && <span className="text-text-tertiary shrink-0">{','}</span>}
|
||||
<ToolIdentifier rawName={name} localize={localize} mcpServerNames={mcpServerNames} />
|
||||
</span>
|
||||
))}
|
||||
{line.argsSnippet && (
|
||||
<span className="text-text-tertiary min-w-0 truncate">{`(${line.argsSnippet})`}</span>
|
||||
)}
|
||||
</span>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
if (line.kind === 'tool_complete') {
|
||||
return (
|
||||
<li className="flex w-full items-baseline gap-1 overflow-hidden whitespace-nowrap">
|
||||
<ToolIdentifier
|
||||
rawName={line.toolName}
|
||||
localize={localize}
|
||||
mcpServerNames={mcpServerNames}
|
||||
/>
|
||||
<span className="text-text-tertiary shrink-0">{'\u2192'}</span>
|
||||
<TailText text={line.outputSnippet ?? localize('com_ui_subagent_ticker_tool_done')} />
|
||||
</li>
|
||||
);
|
||||
}
|
||||
/* error */
|
||||
const errorPrefix = localize('com_ui_subagent_ticker_error');
|
||||
return (
|
||||
<li className="text-text-warning flex w-full items-baseline gap-1 overflow-hidden">
|
||||
<span className="shrink-0">{`${errorPrefix}:`}</span>
|
||||
<span className="min-w-0 flex-1 truncate">{line.message ?? ''}</span>
|
||||
</li>
|
||||
{/* Held to its last line: what the child wrote most recently is the part in view. */}
|
||||
<div className="absolute inset-x-0 bottom-0">
|
||||
{/* A picture of the child's row and nothing more: the row itself registers what it
|
||||
holds with the app, owns its artifacts and answers a request to reveal a failure. */}
|
||||
<PartsPreviewContext.Provider value={true}>
|
||||
<FailedRevealContext.Provider value={NO_REVEAL}>
|
||||
<MessagePartsHostProvider host={pictureHost}>
|
||||
{host.renderContentParts({
|
||||
content,
|
||||
messageId,
|
||||
conversationId: null,
|
||||
isCreatedByUser: false,
|
||||
showThinking: false,
|
||||
isSubmitting: true,
|
||||
isLast: true,
|
||||
/** The row is live: a renderer told otherwise draws a tool still running as
|
||||
* stopped. */
|
||||
isLatestMessage: true,
|
||||
})}
|
||||
</MessagePartsHostProvider>
|
||||
</FailedRevealContext.Provider>
|
||||
</PartsPreviewContext.Provider>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -36,7 +36,6 @@ function SubagentCall(props: SubagentCallProps) {
|
|||
isSharedConvo
|
||||
shareId="share-1"
|
||||
localize={localize}
|
||||
mcpServerNames={[]}
|
||||
renderAgentIcon={() => null}
|
||||
renderAttachments={() => null}
|
||||
/>
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
/**
|
||||
* @jest-environment jsdom
|
||||
*/
|
||||
import React, { useState } from 'react';
|
||||
import React, { useState, useEffect, useContext } from 'react';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { Provider as JotaiProvider, createStore, useAtomValue, useStore } from 'jotai';
|
||||
import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
|
||||
|
|
@ -34,19 +34,20 @@ import {
|
|||
subagentProgressByToolCallId,
|
||||
subagentProgressKey,
|
||||
} from '../../../react/subagents/state';
|
||||
import { MAX_PREVIEWED_THREADS, useThreadInterest } from '../../../react/subagents/follows';
|
||||
import { MessagePartsHostProvider, useMessagePartsHost } from '../../../react/host';
|
||||
import PackageSubagentCall, { SUBAGENT_TICKER_THROTTLE_MS } from '../SubagentCall';
|
||||
import { ParentSubagentsProvider } from '../../../react/subagents/parents';
|
||||
import { createSubagentsHost } from '../../../__fixtures__/subagentsHost';
|
||||
import { createMessagePartsHost } from '../../../__fixtures__/partsHost';
|
||||
import { ChatSurfaceProvider } from '../../../react/subagents/provider';
|
||||
import { SubagentsHostProvider } from '../../../react/subagents/host';
|
||||
import { useIsPartsPreview } from '../../../react/parts/preview';
|
||||
import { StreamHostProvider } from '../../../react/stream/host';
|
||||
import { MessagePartsHostProvider } from '../../../react/host';
|
||||
import { FailedRevealContext } from '../reveal';
|
||||
import { FOLD_GLYPH_SELECTOR } from '../rows';
|
||||
import { litFoldPath } from '../rail';
|
||||
|
||||
const mockMCPServerNames: string[] = [];
|
||||
let mockIndexedChildren = new Map<string, ParentSubagentSummary>();
|
||||
|
||||
type CardMessage = {
|
||||
|
|
@ -96,7 +97,6 @@ function SubagentCall(props: SubagentCallProps) {
|
|||
message={currentMessage}
|
||||
agentsMap={agents}
|
||||
localize={localize}
|
||||
mcpServerNames={mockMCPServerNames}
|
||||
renderAgentIcon={(agent) =>
|
||||
agent?.avatar?.filepath != null ? (
|
||||
<img alt={agent.name ?? ''} src={agent.avatar.filepath} />
|
||||
|
|
@ -111,10 +111,71 @@ function SubagentCall(props: SubagentCallProps) {
|
|||
/>
|
||||
);
|
||||
}
|
||||
const partsHost = createMessagePartsHost();
|
||||
/** A part as one line, so a spec reads which row the thread's renderer was handed. */
|
||||
const partLine = (part: object | undefined): string => {
|
||||
const {
|
||||
text,
|
||||
think,
|
||||
tool_call: toolCall,
|
||||
} = (part ?? {}) as {
|
||||
text?: string;
|
||||
think?: string;
|
||||
tool_call?: { name?: string };
|
||||
};
|
||||
return toolCall?.name ?? text ?? think ?? '';
|
||||
};
|
||||
/** What a row is told when it is drawn, read the way the app's parts read it. */
|
||||
function ThreadRow({ line, live }: { line: string; live: boolean }): ReactNode {
|
||||
const [claim, setClaim] = useMessagePartsHost().useToolArtifactClaim('artifact-1');
|
||||
const reveal = useContext(FailedRevealContext);
|
||||
useEffect(() => {
|
||||
setClaim('thread-row');
|
||||
}, [setClaim]);
|
||||
return (
|
||||
<div
|
||||
data-testid="thread-row"
|
||||
data-live={String(live)}
|
||||
data-preview={String(useIsPartsPreview())}
|
||||
data-claim={String(claim)}
|
||||
data-reveal={String(reveal.tick)}
|
||||
>
|
||||
{line}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
let claimedArtifact: string | null = null;
|
||||
const partsHost = createMessagePartsHost({
|
||||
/** One claim for the page, as the app keeps one per artifact. */
|
||||
useToolArtifactClaim: () => [
|
||||
claimedArtifact,
|
||||
(next) => {
|
||||
claimedArtifact = typeof next === 'function' ? next(claimedArtifact) : next;
|
||||
},
|
||||
],
|
||||
renderContentParts: ({ content, isSubmitting, isLatestMessage }) => (
|
||||
<ThreadRow
|
||||
line={content.map(partLine).join('|')}
|
||||
live={isSubmitting && isLatestMessage === true}
|
||||
/>
|
||||
),
|
||||
});
|
||||
|
||||
const mockUseThreadChat = jest.fn();
|
||||
const mockRefetchIndex = jest.fn(async () => ({ data: undefined }));
|
||||
let seedQueries: ((client: QueryClient) => void) | undefined;
|
||||
/** Other readers on the page, mounted ahead of the card under the same providers. */
|
||||
let neighbours: ReactNode;
|
||||
|
||||
/** Another running child's card, as far as the page's followers are concerned. */
|
||||
function OtherPreview({ threadId }: { threadId: string }): null {
|
||||
useThreadInterest(threadId, { live: true, enabled: true, passive: true });
|
||||
return null;
|
||||
}
|
||||
|
||||
const subagentsHost = createSubagentsHost({
|
||||
useAgentsMap: () => agents,
|
||||
useThreadChat: (...args) => mockUseThreadChat(...args),
|
||||
});
|
||||
|
||||
const streamHost = {
|
||||
|
|
@ -125,7 +186,7 @@ const streamHost = {
|
|||
childrenTruncated: false,
|
||||
},
|
||||
isError: false,
|
||||
refetch: async () => ({ data: undefined }),
|
||||
refetch: mockRefetchIndex,
|
||||
}),
|
||||
} as unknown as StreamHost;
|
||||
|
||||
|
|
@ -158,9 +219,11 @@ function Providers({
|
|||
seed?.(created);
|
||||
return created;
|
||||
});
|
||||
const [queryClient] = useState(
|
||||
() => new QueryClient({ defaultOptions: { queries: { retry: false } } }),
|
||||
);
|
||||
const [queryClient] = useState(() => {
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
seedQueries?.(client);
|
||||
return client;
|
||||
});
|
||||
const card = (
|
||||
<FailedRevealContext.Provider value={{ tick, claimFocus: () => true }}>
|
||||
<MessagePartsHostProvider host={partsHost}>{children}</MessagePartsHostProvider>
|
||||
|
|
@ -169,17 +232,19 @@ function Providers({
|
|||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<StreamHostProvider host={streamHost}>
|
||||
<ParentSubagentsProvider conversationId="parent-conversation" enabled>
|
||||
<JotaiProvider store={store}>
|
||||
<SubagentsHostProvider host={subagentsHost}>
|
||||
{/* The page's followers read the subagents host, so it sits above the index provider. */}
|
||||
<SubagentsHostProvider host={subagentsHost}>
|
||||
<ParentSubagentsProvider conversationId="parent-conversation" enabled>
|
||||
<JotaiProvider store={store}>
|
||||
{neighbours}
|
||||
{withSurface ? (
|
||||
<ChatSurfaceProvider value={surface}>{card}</ChatSurfaceProvider>
|
||||
) : (
|
||||
card
|
||||
)}
|
||||
</SubagentsHostProvider>
|
||||
</JotaiProvider>
|
||||
</ParentSubagentsProvider>
|
||||
</JotaiProvider>
|
||||
</ParentSubagentsProvider>
|
||||
</SubagentsHostProvider>
|
||||
</StreamHostProvider>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
|
|
@ -187,9 +252,13 @@ function Providers({
|
|||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
mockMCPServerNames.length = 0;
|
||||
mockIndexedChildren = new Map();
|
||||
currentMessage = defaultMessage;
|
||||
seedQueries = undefined;
|
||||
neighbours = undefined;
|
||||
claimedArtifact = null;
|
||||
mockUseThreadChat.mockReset();
|
||||
mockRefetchIndex.mockClear();
|
||||
});
|
||||
|
||||
function foldEvents(events: SubagentUpdateEvent[]): {
|
||||
|
|
@ -477,7 +546,7 @@ describe('SubagentCall', () => {
|
|||
expect(rendered.getSelection()).toBeNull();
|
||||
});
|
||||
|
||||
it('keeps the compact semantic ticker while selecting the shared panel', async () => {
|
||||
it('shows the row the child is on, drawn by the thread renderer, over the card and not in its button', () => {
|
||||
const progress = progressFromEvents({
|
||||
subagentRunId: 'child-run',
|
||||
subagentType: 'self',
|
||||
|
|
@ -499,10 +568,24 @@ describe('SubagentCall', () => {
|
|||
progress,
|
||||
});
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Using')).toBeInTheDocument());
|
||||
expect(screen.getByText('Working…')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Writing')).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Running agent' }));
|
||||
/** One row: the newest part, not the ones before it. */
|
||||
const row = screen.getByTestId('thread-row');
|
||||
expect(row).toHaveTextContent('calculator');
|
||||
expect(row).not.toHaveTextContent('Working…');
|
||||
/** Drawn as a live row, or a tool still running would read as one that was stopped. */
|
||||
expect(row).toHaveAttribute('data-live', 'true');
|
||||
/** And as a picture of that row: it is told so, it takes no artifact from the row it
|
||||
* pictures, and a request to reveal a failure does not reach it. */
|
||||
expect(row).toHaveAttribute('data-preview', 'true');
|
||||
expect(claimedArtifact).toBeNull();
|
||||
rendered.reveal();
|
||||
expect(screen.getByTestId('thread-row')).toHaveAttribute('data-reveal', '0');
|
||||
const preview = row.closest('[data-subagent-preview]');
|
||||
expect(preview).toHaveAttribute('aria-hidden', 'true');
|
||||
expect(preview).toHaveAttribute('inert');
|
||||
const card = screen.getByRole('button', { name: 'Running agent' });
|
||||
expect(card.contains(row)).toBe(false);
|
||||
fireEvent.click(card);
|
||||
|
||||
expect(rendered.getSelection()).toEqual(
|
||||
expect.objectContaining({
|
||||
|
|
@ -516,43 +599,28 @@ describe('SubagentCall', () => {
|
|||
expect(rendered.getSelection()?.durable).toBeUndefined();
|
||||
});
|
||||
|
||||
it('preserves a configured MCP server boundary in the live ticker', () => {
|
||||
mockMCPServerNames.push('Google_mcp_Workspace');
|
||||
renderWithState({
|
||||
toolCallId: 'call_mcp_ticker',
|
||||
it('says it is waiting until the child has a row, and shows none once it is done', () => {
|
||||
const rendered = renderWithState({
|
||||
toolCallId: 'call-waiting',
|
||||
initialProgress: 0.3,
|
||||
isSubmitting: true,
|
||||
progress: progressFromEvents({
|
||||
subagentRunId: 'run_a',
|
||||
subagentType: 'self',
|
||||
status: 'run_step',
|
||||
events: [
|
||||
{
|
||||
runId: 'p',
|
||||
subagentRunId: 'run_a',
|
||||
subagentType: 'self',
|
||||
phase: 'run_step',
|
||||
data: {
|
||||
stepDetails: {
|
||||
type: 'tool_calls',
|
||||
tool_calls: [
|
||||
{
|
||||
id: 'c1',
|
||||
name: 'search_documents_mcp_Google_mcp_Workspace',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
timestamp: '',
|
||||
} as SubagentUpdateEvent,
|
||||
],
|
||||
}),
|
||||
});
|
||||
expect(screen.getByText('Waiting for first update…')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('thread-row')).toBeNull();
|
||||
|
||||
expect(screen.getByText('Google_mcp_Workspace')).toBeInTheDocument();
|
||||
rendered.setProgress(
|
||||
progressFromEvents({
|
||||
subagentRunId: 'child-run',
|
||||
subagentType: 'self',
|
||||
status: 'stop',
|
||||
events: [event('message_delta', { delta: { content: [{ type: 'text', text: 'Done' }] } })],
|
||||
}),
|
||||
);
|
||||
expect(screen.queryByText('Waiting for first update…')).toBeNull();
|
||||
expect(screen.queryByTestId('thread-row')).toBeNull();
|
||||
});
|
||||
|
||||
it('refreshes a long ticker preview only after the throttle window', () => {
|
||||
it('refreshes a long live row only after the throttle window', () => {
|
||||
jest.useFakeTimers();
|
||||
const progressFor = (text: string) =>
|
||||
progressFromEvents({
|
||||
|
|
@ -569,11 +637,158 @@ describe('SubagentCall', () => {
|
|||
isSubmitting: true,
|
||||
progress: progressFor(first),
|
||||
});
|
||||
const card = within(screen.getByRole('button', { name: 'Running agent' }));
|
||||
rendered.setProgress(progressFor(second));
|
||||
expect(card.getByText(first)).toBeInTheDocument();
|
||||
expect(screen.getByTestId('thread-row')).toHaveTextContent(first);
|
||||
act(() => jest.advanceTimersByTime(SUBAGENT_TICKER_THROTTLE_MS));
|
||||
expect(card.getByText(second)).toBeInTheDocument();
|
||||
expect(screen.getByTestId('thread-row')).toHaveTextContent(second);
|
||||
});
|
||||
|
||||
describe('a detached child', () => {
|
||||
const detachedOutput = JSON.stringify({
|
||||
background_task_id: 'task-1',
|
||||
subagent_thread_id: 'child-thread-1',
|
||||
tool: 'subagent',
|
||||
subagent_type: 'agent_reviewer',
|
||||
status: 'running',
|
||||
message: 'Started subagent background task. Poll with background_task_id task-1.',
|
||||
});
|
||||
const indexed = (status: ParentSubagentSummary['status']) =>
|
||||
new Map([
|
||||
[
|
||||
'child-thread-1',
|
||||
{
|
||||
threadId: 'child-thread-1',
|
||||
status,
|
||||
latestTaskId: 'task-1',
|
||||
agentId: 'agent_reviewer',
|
||||
tasks: [{ taskId: 'task-1', status }],
|
||||
} as ParentSubagentSummary,
|
||||
],
|
||||
]);
|
||||
const threadMessages = [
|
||||
{ messageId: 'task-1:user', isCreatedByUser: true, text: 'Review it' },
|
||||
{
|
||||
messageId: 'task-1:assistant',
|
||||
parentMessageId: 'task-1:user',
|
||||
isCreatedByUser: false,
|
||||
text: '',
|
||||
content: [
|
||||
{ type: 'text', text: 'Reading the diff' },
|
||||
{ type: 'tool_call', tool_call: { id: 'c1', name: 'read_file', args: '{}' } },
|
||||
],
|
||||
},
|
||||
];
|
||||
const mountDetached = () =>
|
||||
renderWithState({
|
||||
toolCallId: 'detached-live',
|
||||
initialProgress: 1,
|
||||
output: detachedOutput,
|
||||
toolArgs: { subagent_type: 'agent_reviewer', run_in_background: true },
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
mockUseThreadChat.mockReturnValue({ messages: [], isLoading: true });
|
||||
seedQueries = (client) => client.setQueryData(['messages', 'child-thread-1'], threadMessages);
|
||||
});
|
||||
|
||||
it('is followed while it runs, once, and shows the row its thread is on', () => {
|
||||
mockIndexedChildren = indexed('running');
|
||||
mountDetached();
|
||||
|
||||
expect(mockUseThreadChat).toHaveBeenCalledWith('parent-conversation', 'child-thread-1', {
|
||||
live: true,
|
||||
enabled: true,
|
||||
});
|
||||
expect(screen.getByTestId('thread-row')).toHaveTextContent('read_file');
|
||||
/** Named by the index, which is all that names a child once the parent's stream is gone. */
|
||||
expect(
|
||||
screen.getByRole('button', {
|
||||
name: 'Code Reviewer com_ui_subagent_thread_status_running',
|
||||
}),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('keeps the last row that draws something when an empty label reservation follows it', () => {
|
||||
mockIndexedChildren = indexed('running');
|
||||
seedQueries = (client) =>
|
||||
client.setQueryData(
|
||||
['messages', 'child-thread-1'],
|
||||
[
|
||||
threadMessages[0],
|
||||
{
|
||||
...threadMessages[1],
|
||||
content: [
|
||||
...(threadMessages[1].content ?? []),
|
||||
{ type: 'activity_label', activity_label: '' },
|
||||
],
|
||||
},
|
||||
],
|
||||
);
|
||||
mountDetached();
|
||||
|
||||
expect(screen.getByTestId('thread-row')).toHaveTextContent('read_file');
|
||||
});
|
||||
|
||||
it('shows no row for a child the page has no room to follow, whatever was last read for it', () => {
|
||||
mockIndexedChildren = indexed('running');
|
||||
neighbours = Array.from({ length: MAX_PREVIEWED_THREADS }, (_, n) => (
|
||||
<OtherPreview key={n} threadId={`other-thread-${n}`} />
|
||||
));
|
||||
mountDetached();
|
||||
|
||||
/** Its messages are in the cache, but nothing is reading its stream, so they are stale. */
|
||||
expect(mockUseThreadChat).not.toHaveBeenCalledWith(
|
||||
'parent-conversation',
|
||||
'child-thread-1',
|
||||
expect.anything(),
|
||||
);
|
||||
expect(screen.queryByTestId('thread-row')).toBeNull();
|
||||
});
|
||||
|
||||
it('refreshes a long live row on the throttle, as a foreground child does', async () => {
|
||||
jest.useFakeTimers();
|
||||
mockIndexedChildren = indexed('running');
|
||||
const first = 'First live preview '.repeat(8).trim();
|
||||
const second = 'Second live preview '.repeat(8).trim();
|
||||
const withText = (text: string) => [
|
||||
threadMessages[0],
|
||||
{ ...threadMessages[1], content: [{ type: 'text', text }] },
|
||||
];
|
||||
let cache: QueryClient | undefined;
|
||||
seedQueries = (client) => {
|
||||
cache = client;
|
||||
client.setQueryData(['messages', 'child-thread-1'], withText(first));
|
||||
};
|
||||
mountDetached();
|
||||
expect(screen.getByTestId('thread-row')).toHaveTextContent(first);
|
||||
|
||||
/** The cache tells its readers on a timer; a moment later the newer text has reached the
|
||||
* card and is being held back. */
|
||||
await act(async () => {
|
||||
cache?.setQueryData(['messages', 'child-thread-1'], withText(second));
|
||||
await jest.advanceTimersByTimeAsync(1);
|
||||
});
|
||||
expect(screen.getByTestId('thread-row')).toHaveTextContent(first);
|
||||
await act(async () => {
|
||||
await jest.advanceTimersByTimeAsync(SUBAGENT_TICKER_THROTTLE_MS);
|
||||
});
|
||||
expect(screen.getByTestId('thread-row')).toHaveTextContent(second);
|
||||
});
|
||||
|
||||
it('is not followed and shows no row once it has finished', () => {
|
||||
mockIndexedChildren = indexed('completed');
|
||||
mountDetached();
|
||||
|
||||
expect(mockUseThreadChat).not.toHaveBeenCalled();
|
||||
expect(screen.queryByTestId('thread-row')).toBeNull();
|
||||
});
|
||||
|
||||
it('asks the index to look again for a child it does not list, once', async () => {
|
||||
mountDetached();
|
||||
|
||||
await waitFor(() => expect(mockRefetchIndex).toHaveBeenCalledTimes(1));
|
||||
expect(mockUseThreadChat).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it('opens a foreground legacy invocation in the shared panel with persisted activity', () => {
|
||||
|
|
|
|||
|
|
@ -53,6 +53,7 @@ import {
|
|||
useSubagentPanelState,
|
||||
useSubagentPanelActions,
|
||||
} from '../../react/subagents/surface';
|
||||
import { useFollowedThread, useThreadFollows } from '../../react/subagents/follows';
|
||||
import { SubagentActivity, SubagentActivityScrollSurface } from './transcript';
|
||||
import { eventSubagentSelection } from '../../react/subagents/eventSelection';
|
||||
import { isMacPlatform, resolveComposerKeyDown } from '../../core/shortcuts';
|
||||
|
|
@ -317,10 +318,18 @@ export default function SubagentThreadPanel({
|
|||
selection.event == null &&
|
||||
threadId !== '';
|
||||
const followLive = followable && taskView?.status === 'running';
|
||||
const followed = host.useThreadChat?.(selection.parentConversationId, threadId, {
|
||||
/** One follower per thread on the page: where the page shares them, the card previewing this
|
||||
* child and this panel read the same stream; elsewhere the panel follows the thread itself. */
|
||||
const sharedFollows = useThreadFollows();
|
||||
const ownFollowed = host.useThreadChat?.(selection.parentConversationId, threadId, {
|
||||
live: followLive,
|
||||
enabled: followable,
|
||||
enabled: followable && sharedFollows == null,
|
||||
});
|
||||
const sharedFollowed = useFollowedThread(threadId, {
|
||||
live: followLive,
|
||||
enabled: followable && sharedFollows != null,
|
||||
});
|
||||
const followed = sharedFollows == null ? ownFollowed : sharedFollowed;
|
||||
/** Rows that are not being streamed into: the stored ones, as first read or as read again at
|
||||
* a run's end. */
|
||||
const followedSettled = followed != null && !followed.isLoading && !followed.isFollowing;
|
||||
|
|
|
|||
|
|
@ -213,6 +213,7 @@ export {
|
|||
useOptionalMessagesOperations,
|
||||
useOptionalMessagesConversation,
|
||||
} from './react/messages/view';
|
||||
export { PartsPreviewContext, useIsPartsPreview } from './react/parts/preview';
|
||||
export type {
|
||||
MessagesEditing,
|
||||
MessagesOperations,
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ import type { ReactNode } from 'react';
|
|||
import type { ChatStream, ChatTransport, ChatStreamStatus } from '../../core';
|
||||
import type { FollowChatOptions } from '../follow';
|
||||
import { MAX_RETRIES, getReconnectDelay } from '../../core';
|
||||
import { useFollowChat } from '../follow';
|
||||
import { ABSENT_RETRIES, useFollowChat } from '../follow';
|
||||
|
||||
type TestStream = ChatStream & { push(event: ChatEvent): void; closed: boolean };
|
||||
|
||||
|
|
@ -263,7 +263,7 @@ describe('useFollowChat', () => {
|
|||
expect(result.current.isUnattached).toBe(false);
|
||||
});
|
||||
|
||||
it('says a run the caller knows of has no stream only once an attachment found none', async () => {
|
||||
it('says a run the caller knows of has no stream only after looking for it again', async () => {
|
||||
const { transport } = createTransport(idle);
|
||||
let release: (messages: TMessage[]) => void = () => undefined;
|
||||
const loadMessages = jest.fn(
|
||||
|
|
@ -277,10 +277,47 @@ describe('useFollowChat', () => {
|
|||
expect(result.current.isUnattached).toBe(false);
|
||||
|
||||
loadMessages.mockResolvedValue([brief]);
|
||||
await act(async () => release([brief]));
|
||||
jest.useFakeTimers();
|
||||
try {
|
||||
await act(async () => {
|
||||
release([brief]);
|
||||
await jest.advanceTimersByTimeAsync(getReconnectDelay(1));
|
||||
});
|
||||
/** Not found once is not yet nothing to attach to. */
|
||||
expect(result.current.isUnattached).toBe(false);
|
||||
await act(async () => {
|
||||
await jest.advanceTimersByTimeAsync(60_000);
|
||||
});
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
}
|
||||
await waitFor(() => expect(result.current.isUnattached).toBe(true));
|
||||
expect(result.current.isFollowing).toBe(false);
|
||||
expect(transport.reconnectToStream).toHaveBeenCalledTimes(1);
|
||||
expect(transport.reconnectToStream).toHaveBeenCalledTimes(1 + ABSENT_RETRIES);
|
||||
});
|
||||
|
||||
it('follows a run whose stream opens a moment after the caller learns of it', async () => {
|
||||
const { transport, streams, setStatus } = createTransport(idle);
|
||||
const { result } = setup({ transport, live: true });
|
||||
await waitFor(() => expect(transport.reconnectToStream).toHaveBeenCalledTimes(1));
|
||||
expect(streams).toHaveLength(0);
|
||||
|
||||
/** The run was announced first; its generation opens now. */
|
||||
setStatus(running);
|
||||
jest.useFakeTimers();
|
||||
try {
|
||||
await act(async () => {
|
||||
await jest.advanceTimersByTimeAsync(getReconnectDelay(1));
|
||||
});
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
}
|
||||
await waitFor(() => expect(streams).toHaveLength(1));
|
||||
act(() => streams[0].push(snapshot('Late start')));
|
||||
await settle();
|
||||
|
||||
expect(textOf(result.current.messages)).toEqual(['Late start']);
|
||||
expect(result.current.isUnattached).toBe(false);
|
||||
});
|
||||
|
||||
it('says the stream is gone once a dropped one could not be attached again', async () => {
|
||||
|
|
|
|||
|
|
@ -106,6 +106,12 @@ type Load = { id: string; attempt: number; state: 'loading' | 'ready' | 'error'
|
|||
*/
|
||||
type Attachment = { finished?: ChatFinishResult; received: boolean };
|
||||
|
||||
/**
|
||||
* How many more times a run the caller knows of is looked for after it was not found. Short: a
|
||||
* caller with another way to show the run is waiting on the answer.
|
||||
*/
|
||||
export const ABSENT_RETRIES = 2;
|
||||
|
||||
const noMessages: TMessage[] = [];
|
||||
const unsubscribed = (): (() => void) => () => undefined;
|
||||
|
||||
|
|
@ -241,9 +247,19 @@ export function useFollowChat({
|
|||
/** Whether a generation was reached and not lost for good. */
|
||||
let reached = false;
|
||||
try {
|
||||
for (let failures = 0; !stale; ) {
|
||||
for (let failures = 0, absences = 0; !stale; ) {
|
||||
const { finished, received } = await follow();
|
||||
reached ||= received || finished != null;
|
||||
/**
|
||||
* The caller says a run is going and none was found. Its stream may not be open yet:
|
||||
* a run is announced as running before its generation is, so the attachment is tried
|
||||
* again shortly before it is taken to have nothing to attach to.
|
||||
*/
|
||||
if (!reached && host.current.live && absences < ABSENT_RETRIES) {
|
||||
absences += 1;
|
||||
await pause(getReconnectDelay(absences));
|
||||
continue;
|
||||
}
|
||||
if (finished?.isDisconnect !== true) {
|
||||
break;
|
||||
}
|
||||
|
|
|
|||
12
packages/chat/src/react/parts/preview.ts
Normal file
12
packages/chat/src/react/parts/preview.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
import { createContext, useContext } from 'react';
|
||||
import type { Context } from 'react';
|
||||
|
||||
/**
|
||||
* Whether the parts under this are a picture of a row drawn somewhere else, as a subagent card's
|
||||
* row is of its child's thread. A picture paints and nothing more: a part that would register
|
||||
* itself with the app, claim something only one mounted row may hold, or act on the reader's
|
||||
* behalf does none of that here, because the row it pictures already does.
|
||||
*/
|
||||
export const PartsPreviewContext: Context<boolean> = createContext<boolean>(false);
|
||||
|
||||
export const useIsPartsPreview = (): boolean => useContext(PartsPreviewContext);
|
||||
214
packages/chat/src/react/subagents/__tests__/follows.spec.tsx
Normal file
214
packages/chat/src/react/subagents/__tests__/follows.spec.tsx
Normal file
|
|
@ -0,0 +1,214 @@
|
|||
/**
|
||||
* @jest-environment jsdom
|
||||
*/
|
||||
import { useEffect } from 'react';
|
||||
import { act, render } from '@testing-library/react';
|
||||
import type { ReactElement } from 'react';
|
||||
import type { FollowedChat } from '../../follow';
|
||||
import {
|
||||
useFollowedThread,
|
||||
useThreadInterest,
|
||||
ThreadFollowsProvider,
|
||||
THREAD_LINGER_MS,
|
||||
MAX_PREVIEWED_THREADS,
|
||||
} from '../follows';
|
||||
import { createSubagentsHost } from '../../../__fixtures__/subagentsHost';
|
||||
import { SubagentsHostProvider } from '../host';
|
||||
|
||||
const followed = (overrides: Partial<FollowedChat> = {}): FollowedChat => ({
|
||||
chat: undefined,
|
||||
messages: [],
|
||||
status: 'ready',
|
||||
connection: 'idle',
|
||||
error: undefined,
|
||||
isLoading: false,
|
||||
isFollowing: false,
|
||||
isUnattached: false,
|
||||
isLoadError: false,
|
||||
retry: () => undefined,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
/** Each thread's follower as the host sees it: which are mounted, and how each was last asked. */
|
||||
let asked: Record<string, { live: boolean; enabled: boolean }>;
|
||||
let results: Record<string, FollowedChat>;
|
||||
let mounted: Set<string>;
|
||||
let unmounts: number;
|
||||
|
||||
const host = createSubagentsHost({
|
||||
useThreadChat: (_parent, threadId, options) => {
|
||||
asked[threadId] = options;
|
||||
useEffect(() => {
|
||||
mounted.add(threadId);
|
||||
return () => {
|
||||
mounted.delete(threadId);
|
||||
unmounts += 1;
|
||||
};
|
||||
}, [threadId]);
|
||||
return results[threadId] ?? followed({ isLoading: true });
|
||||
},
|
||||
});
|
||||
|
||||
const page = (ui: ReactElement) => (
|
||||
<SubagentsHostProvider host={host}>
|
||||
<ThreadFollowsProvider parentConversationId="parent">{ui}</ThreadFollowsProvider>
|
||||
</SubagentsHostProvider>
|
||||
);
|
||||
|
||||
function Reader({ threadId, live = false }: { threadId: string; live?: boolean }): null {
|
||||
seen[threadId] = useFollowedThread(threadId, { live, enabled: true });
|
||||
return null;
|
||||
}
|
||||
|
||||
function Preview({ threadId }: { threadId: string }): null {
|
||||
admitted[threadId] = useThreadInterest(threadId, { live: true, enabled: true, passive: true });
|
||||
return null;
|
||||
}
|
||||
|
||||
let admitted: Record<string, boolean>;
|
||||
|
||||
let seen: Record<string, FollowedChat | undefined>;
|
||||
|
||||
beforeEach(() => {
|
||||
asked = {};
|
||||
results = {};
|
||||
seen = {};
|
||||
mounted = new Set();
|
||||
unmounts = 0;
|
||||
admitted = {};
|
||||
jest.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
describe('ThreadFollowsProvider', () => {
|
||||
it('follows a thread once for every reader and lets it go when the last one leaves', () => {
|
||||
const view = render(
|
||||
page(
|
||||
<>
|
||||
<Reader threadId="thread-1" />
|
||||
<Preview threadId="thread-1" />
|
||||
</>,
|
||||
),
|
||||
);
|
||||
/** One follower, live for the page as soon as any reader knows a run is going. */
|
||||
expect([...mounted]).toEqual(['thread-1']);
|
||||
expect(asked['thread-1']).toEqual({ live: true, enabled: true });
|
||||
|
||||
view.rerender(page(<Reader threadId="thread-1" />));
|
||||
expect([...mounted]).toEqual(['thread-1']);
|
||||
expect(asked['thread-1']).toEqual({ live: false, enabled: true });
|
||||
|
||||
view.rerender(page(<></>));
|
||||
/** Kept for a moment, so a reader that is only being replaced finds it still open. */
|
||||
expect([...mounted]).toEqual(['thread-1']);
|
||||
act(() => jest.advanceTimersByTime(THREAD_LINGER_MS));
|
||||
expect([...mounted]).toEqual([]);
|
||||
});
|
||||
|
||||
it('keeps one follower through a reader being replaced', () => {
|
||||
const view = render(page(<Preview key="first" threadId="thread-1" />));
|
||||
view.rerender(page(<Preview key="second" threadId="thread-1" />));
|
||||
act(() => jest.advanceTimersByTime(THREAD_LINGER_MS * 2));
|
||||
expect([...mounted]).toEqual(['thread-1']);
|
||||
expect(unmounts).toBe(0);
|
||||
});
|
||||
|
||||
it('hands a reader an opening state until the follower reports, then what it reports', () => {
|
||||
results['thread-1'] = followed({ isLoading: true });
|
||||
const view = render(page(<Reader threadId="thread-1" />));
|
||||
expect(seen['thread-1']).toMatchObject({ isLoading: true, messages: [] });
|
||||
|
||||
const streaming = followed({ status: 'streaming', isFollowing: true });
|
||||
results['thread-1'] = streaming;
|
||||
act(() => view.rerender(page(<Reader threadId="thread-1" live />)));
|
||||
expect(seen['thread-1']).toBe(streaming);
|
||||
});
|
||||
|
||||
it('previews only as many threads as the page has room for, and always follows an opened one', () => {
|
||||
const previews = Array.from({ length: MAX_PREVIEWED_THREADS + 1 }, (_, n) => `preview-${n}`);
|
||||
const view = render(
|
||||
page(
|
||||
<>
|
||||
{previews.map((threadId) => (
|
||||
<Preview key={threadId} threadId={threadId} />
|
||||
))}
|
||||
<Reader threadId="opened" />
|
||||
</>,
|
||||
),
|
||||
);
|
||||
const overflow = previews[MAX_PREVIEWED_THREADS];
|
||||
expect([...mounted].sort()).toEqual(
|
||||
[...previews.slice(0, MAX_PREVIEWED_THREADS), 'opened'].sort(),
|
||||
);
|
||||
|
||||
/** Opening a preview that had no room follows it. */
|
||||
view.rerender(
|
||||
page(
|
||||
<>
|
||||
{previews.map((threadId) => (
|
||||
<Preview key={threadId} threadId={threadId} />
|
||||
))}
|
||||
<Reader threadId="opened" />
|
||||
<Reader threadId={overflow} />
|
||||
</>,
|
||||
),
|
||||
);
|
||||
expect(mounted.has(overflow)).toBe(true);
|
||||
expect(asked[overflow]).toEqual({ live: true, enabled: true });
|
||||
|
||||
/** A preview that ends gives its room to the next one waiting. */
|
||||
view.rerender(
|
||||
page(
|
||||
<>
|
||||
{previews.slice(1).map((threadId) => (
|
||||
<Preview key={threadId} threadId={threadId} />
|
||||
))}
|
||||
</>,
|
||||
),
|
||||
);
|
||||
act(() => jest.advanceTimersByTime(THREAD_LINGER_MS));
|
||||
expect([...mounted].sort()).toEqual(previews.slice(1).sort());
|
||||
});
|
||||
|
||||
it('tells a preview whether its thread is being followed, including once it loses its room', () => {
|
||||
const previews = Array.from({ length: MAX_PREVIEWED_THREADS + 1 }, (_, n) => `preview-${n}`);
|
||||
const overflow = previews[MAX_PREVIEWED_THREADS];
|
||||
const cards = previews.map((threadId) => <Preview key={threadId} threadId={threadId} />);
|
||||
const view = render(page(<>{cards}</>));
|
||||
expect(admitted[previews[0]]).toBe(true);
|
||||
expect(admitted[overflow]).toBe(false);
|
||||
|
||||
/** Opened, it is followed whatever the cap; closed again, it is back to having no room. */
|
||||
view.rerender(
|
||||
page(
|
||||
<>
|
||||
{cards}
|
||||
<Reader threadId={overflow} />
|
||||
</>,
|
||||
),
|
||||
);
|
||||
expect(admitted[overflow]).toBe(true);
|
||||
|
||||
view.rerender(page(<>{cards}</>));
|
||||
act(() => jest.advanceTimersByTime(THREAD_LINGER_MS));
|
||||
expect(admitted[overflow]).toBe(false);
|
||||
expect(mounted.has(overflow)).toBe(false);
|
||||
});
|
||||
|
||||
it('follows nothing where no page shares followers', () => {
|
||||
function Lone(): null {
|
||||
seen.lone = useFollowedThread('thread-1', { live: true, enabled: true });
|
||||
return null;
|
||||
}
|
||||
render(
|
||||
<SubagentsHostProvider host={host}>
|
||||
<Lone />
|
||||
</SubagentsHostProvider>,
|
||||
);
|
||||
expect(seen.lone).toBeUndefined();
|
||||
expect([...mounted]).toEqual([]);
|
||||
});
|
||||
});
|
||||
278
packages/chat/src/react/subagents/follows.tsx
Normal file
278
packages/chat/src/react/subagents/follows.tsx
Normal file
|
|
@ -0,0 +1,278 @@
|
|||
import { useMemo, useEffect, useContext, createContext } from 'react';
|
||||
import { selectAtom } from 'jotai/utils';
|
||||
import { atom, createStore, useAtomValue, useSetAtom } from 'jotai';
|
||||
import type { Atom, PrimitiveAtom } from 'jotai';
|
||||
import type { Context, ReactNode } from 'react';
|
||||
import type { FollowedChat } from '../follow';
|
||||
import { useSubagentsHost } from './host';
|
||||
|
||||
/**
|
||||
* How many threads a page follows only to preview them. A followed thread holds a stream open,
|
||||
* and over HTTP/1.1 a browser allows six connections to an origin, which main chat's own stream
|
||||
* and every request share. A thread someone opened is always followed; previews take what is
|
||||
* left of this many.
|
||||
*/
|
||||
export const MAX_PREVIEWED_THREADS = 3;
|
||||
|
||||
/**
|
||||
* How long a thread stays followed after its last reader leaves. A reader that is replaced, not
|
||||
* removed, leaves and returns within one commit: when a reply settles, its row is drawn again
|
||||
* under the reply's stored id, and the card in it with it. Letting go at once would close the
|
||||
* child's stream and open it again for that.
|
||||
*/
|
||||
export const THREAD_LINGER_MS = 250;
|
||||
|
||||
/** One reader's interest in a thread. */
|
||||
export type ThreadInterest = {
|
||||
/** Whether this reader knows a generation is running under the thread. */
|
||||
live: boolean;
|
||||
/** A preview: followed only while the page has room for it. */
|
||||
passive: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* A thread's readers, and what they last asked for between them, which holds for the moment
|
||||
* after the last one leaves.
|
||||
*/
|
||||
type ThreadReaders = { interests: readonly ThreadInterest[]; live: boolean; opened: boolean };
|
||||
type Readers = ReadonlyMap<string, ThreadReaders>;
|
||||
type FollowedThread = { threadId: string; live: boolean };
|
||||
|
||||
/**
|
||||
* The threads one page follows, each once, however many readers want it: the panel showing a
|
||||
* child's conversation and the card previewing the same child read one stream. A thread is
|
||||
* followed while any reader is interested and let go shortly after the last one leaves. The
|
||||
* atoms belong to one provider, so two pages' followers never meet.
|
||||
*/
|
||||
export type ThreadFollows = {
|
||||
/**
|
||||
* The store the atoms below are read and written in. Its own, so a reader under some other
|
||||
* Jotai provider than the followers reads the same state they do.
|
||||
*/
|
||||
store: ReturnType<typeof createStore>;
|
||||
readers: PrimitiveAtom<Readers>;
|
||||
/** The threads to follow now: every opened one, then previews in the order they asked. */
|
||||
followed: Atom<readonly FollowedThread[]>;
|
||||
/** What a thread's follower last reported; nothing until it has. */
|
||||
result: (threadId: string) => PrimitiveAtom<FollowedChat | undefined>;
|
||||
};
|
||||
|
||||
const noReaders: Readers = new Map();
|
||||
|
||||
const sameThreads = (a: readonly FollowedThread[], b: readonly FollowedThread[]): boolean =>
|
||||
a.length === b.length &&
|
||||
a.every(
|
||||
(thread, index) => thread.threadId === b[index].threadId && thread.live === b[index].live,
|
||||
);
|
||||
|
||||
const selectFollowed = (readers: Readers): readonly FollowedThread[] => {
|
||||
const followed: FollowedThread[] = [];
|
||||
let previews = 0;
|
||||
for (const [threadId, { live, opened }] of readers) {
|
||||
if (!opened) {
|
||||
if (previews >= MAX_PREVIEWED_THREADS) {
|
||||
continue;
|
||||
}
|
||||
previews += 1;
|
||||
}
|
||||
followed.push({ threadId, live });
|
||||
}
|
||||
return followed;
|
||||
};
|
||||
|
||||
const withInterests = (interests: readonly ThreadInterest[], previous?: ThreadReaders) =>
|
||||
interests.length === 0 && previous != null
|
||||
? { ...previous, interests }
|
||||
: {
|
||||
interests,
|
||||
live: interests.some((interest) => interest.live),
|
||||
opened: interests.some((interest) => !interest.passive),
|
||||
};
|
||||
|
||||
const createThreadFollows = (): ThreadFollows => {
|
||||
const readers = atom<Readers>(noReaders);
|
||||
const results = new Map<string, PrimitiveAtom<FollowedChat | undefined>>();
|
||||
return {
|
||||
store: createStore(),
|
||||
readers,
|
||||
followed: selectAtom(readers, selectFollowed, sameThreads),
|
||||
result: (threadId) => {
|
||||
const known = results.get(threadId);
|
||||
if (known != null) {
|
||||
return known;
|
||||
}
|
||||
const created = atom<FollowedChat | undefined>(undefined);
|
||||
results.set(threadId, created);
|
||||
return created;
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
/** Read where no page shares followers: nothing is ever written to these. */
|
||||
const unshared: ThreadFollows = createThreadFollows();
|
||||
|
||||
/** What a reader holds until the thread's follower has something to report. */
|
||||
const opening: FollowedChat = {
|
||||
chat: undefined,
|
||||
messages: [],
|
||||
status: 'ready',
|
||||
connection: 'idle',
|
||||
error: undefined,
|
||||
isLoading: true,
|
||||
isFollowing: false,
|
||||
isUnattached: false,
|
||||
isLoadError: false,
|
||||
retry: () => undefined,
|
||||
};
|
||||
|
||||
const ThreadFollowsContext: Context<ThreadFollows | undefined> = createContext<
|
||||
ThreadFollows | undefined
|
||||
>(undefined);
|
||||
|
||||
/** The page's shared followers, when a provider above offers them. */
|
||||
export const useThreadFollows = (): ThreadFollows | undefined => useContext(ThreadFollowsContext);
|
||||
|
||||
/** Follows one thread for everyone on the page and reports what it holds. */
|
||||
function ThreadFollower({
|
||||
follows,
|
||||
parentConversationId,
|
||||
threadId,
|
||||
live,
|
||||
}: {
|
||||
follows: ThreadFollows;
|
||||
parentConversationId: string;
|
||||
threadId: string;
|
||||
live: boolean;
|
||||
}): null {
|
||||
const host = useSubagentsHost();
|
||||
const followed = host.useThreadChat?.(parentConversationId, threadId, { live, enabled: true });
|
||||
const report = useSetAtom(follows.result(threadId), follows);
|
||||
useEffect(() => {
|
||||
report(followed);
|
||||
});
|
||||
useEffect(() => () => report(undefined), [report]);
|
||||
return null;
|
||||
}
|
||||
|
||||
function ThreadFollowers({
|
||||
follows,
|
||||
parentConversationId,
|
||||
}: {
|
||||
follows: ThreadFollows;
|
||||
parentConversationId: string;
|
||||
}): ReactNode {
|
||||
const threads = useAtomValue(follows.followed, follows);
|
||||
return threads.map((thread) => (
|
||||
<ThreadFollower
|
||||
key={thread.threadId}
|
||||
follows={follows}
|
||||
parentConversationId={parentConversationId}
|
||||
threadId={thread.threadId}
|
||||
live={thread.live}
|
||||
/>
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Shares one follower per child thread among every reader under it, for the children of one
|
||||
* parent conversation. Nothing is followed until a reader asks.
|
||||
*/
|
||||
export function ThreadFollowsProvider({
|
||||
parentConversationId,
|
||||
children,
|
||||
}: {
|
||||
parentConversationId: string;
|
||||
children: ReactNode;
|
||||
}): ReactNode {
|
||||
const follows = useMemo(
|
||||
() => ({ parentConversationId, atoms: createThreadFollows() }),
|
||||
[parentConversationId],
|
||||
).atoms;
|
||||
return (
|
||||
<ThreadFollowsContext.Provider value={follows}>
|
||||
<ThreadFollowers follows={follows} parentConversationId={parentConversationId} />
|
||||
{children}
|
||||
</ThreadFollowsContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Says this reader wants a thread followed, without reading what the follower holds: a card
|
||||
* reads its row from the thread's messages and has no use for every other change. Returns
|
||||
* whether the thread is being followed, which a preview with no room on the page is not. Where
|
||||
* no page shares followers there is nothing to be admitted to, and the answer is yes.
|
||||
*/
|
||||
export function useThreadInterest(
|
||||
threadId: string,
|
||||
{ live, enabled, passive = false }: { live: boolean; enabled: boolean; passive?: boolean },
|
||||
): boolean {
|
||||
const shared = useThreadFollows();
|
||||
const follows = shared ?? unshared;
|
||||
const setReaders = useSetAtom(follows.readers, follows);
|
||||
useEffect(() => {
|
||||
if (shared == null || !enabled || threadId === '') {
|
||||
return;
|
||||
}
|
||||
const interest: ThreadInterest = { live, passive };
|
||||
setReaders((readers) => {
|
||||
const previous = readers.get(threadId);
|
||||
const next = new Map(readers);
|
||||
next.set(threadId, withInterests([...(previous?.interests ?? []), interest], previous));
|
||||
return next;
|
||||
});
|
||||
return () => {
|
||||
setReaders((readers) => {
|
||||
const previous = readers.get(threadId);
|
||||
if (previous == null) {
|
||||
return readers;
|
||||
}
|
||||
const next = new Map(readers);
|
||||
next.set(
|
||||
threadId,
|
||||
withInterests(
|
||||
previous.interests.filter((reader) => reader !== interest),
|
||||
previous,
|
||||
),
|
||||
);
|
||||
return next;
|
||||
});
|
||||
setTimeout(() => {
|
||||
setReaders((readers) => {
|
||||
if (readers.get(threadId)?.interests.length !== 0) {
|
||||
return readers;
|
||||
}
|
||||
const next = new Map(readers);
|
||||
next.delete(threadId);
|
||||
return next;
|
||||
});
|
||||
}, THREAD_LINGER_MS);
|
||||
};
|
||||
}, [shared, setReaders, threadId, live, enabled, passive]);
|
||||
const admitted = useMemo(
|
||||
() =>
|
||||
selectAtom(follows.followed, (threads) =>
|
||||
threads.some((thread) => thread.threadId === threadId),
|
||||
),
|
||||
[follows, threadId],
|
||||
);
|
||||
const followed = useAtomValue(admitted, follows);
|
||||
return shared == null || followed;
|
||||
}
|
||||
|
||||
/**
|
||||
* The page's shared follower of a thread, and this reader's interest in it. Nothing while no
|
||||
* provider offers shared followers, or while `enabled` is false.
|
||||
*/
|
||||
export function useFollowedThread(
|
||||
threadId: string,
|
||||
options: { live: boolean; enabled: boolean; passive?: boolean },
|
||||
): FollowedChat | undefined {
|
||||
const shared = useThreadFollows();
|
||||
useThreadInterest(threadId, options);
|
||||
const follows = shared ?? unshared;
|
||||
const result = useAtomValue(follows.result(threadId), follows);
|
||||
if (shared == null || !options.enabled) {
|
||||
return undefined;
|
||||
}
|
||||
return result ?? opening;
|
||||
}
|
||||
|
|
@ -8,6 +8,7 @@ import type {
|
|||
ParentSubagentSummary,
|
||||
} from 'librechat-data-provider';
|
||||
import type { ReactNode } from 'react';
|
||||
import { ThreadFollowsProvider, useThreadFollows } from './follows';
|
||||
import { useStreamHost } from '../stream/host';
|
||||
|
||||
export type ParentSubagentsContextValue = {
|
||||
|
|
@ -15,6 +16,12 @@ export type ParentSubagentsContextValue = {
|
|||
byMessageId: ReadonlyMap<string, ParentSubagentSummary[]>;
|
||||
byThreadId: ReadonlyMap<string, ParentSubagentSummary>;
|
||||
refresh: () => Promise<ParentSubagentIndex | undefined>;
|
||||
/**
|
||||
* Says the page shows a child this index does not list, as one dispatched after the index was
|
||||
* last read is. The index is read again, once per child and once for every child named in the
|
||||
* same commit.
|
||||
*/
|
||||
discover: (threadId: string) => void;
|
||||
isError: boolean;
|
||||
discoveryEnabled: boolean;
|
||||
};
|
||||
|
|
@ -26,6 +33,7 @@ const defaultValue: ParentSubagentsContextValue = {
|
|||
byMessageId: emptyMap,
|
||||
byThreadId: emptyThreadMap,
|
||||
refresh: async () => undefined,
|
||||
discover: () => undefined,
|
||||
isError: false,
|
||||
discoveryEnabled: false,
|
||||
};
|
||||
|
|
@ -46,6 +54,7 @@ export function ParentSubagentsProvider({
|
|||
const queryClient = useQueryClient();
|
||||
const { useParentSubagentIndex } = useStreamHost();
|
||||
const parent = useContext(ParentSubagentsContext);
|
||||
const sharedFollows = useThreadFollows();
|
||||
const inherited =
|
||||
parent.conversationId === conversationId && parent.discoveryEnabled ? parent : null;
|
||||
// Observe already-loaded history without fetching it or rerendering on streamed text.
|
||||
|
|
@ -82,6 +91,24 @@ export function ParentSubagentsProvider({
|
|||
const result = await refetch();
|
||||
return result.data;
|
||||
}, [refetch]);
|
||||
/** Children already asked about under this conversation, and whether a read is scheduled. */
|
||||
const asks = useMemo(
|
||||
() => ({ conversationId, asked: new Set<string>(), scheduled: false }),
|
||||
[conversationId],
|
||||
);
|
||||
const discover = useCallback(
|
||||
(threadId: string) => {
|
||||
if (!discoveryEnabled || asks.asked.has(threadId)) return;
|
||||
asks.asked.add(threadId);
|
||||
if (asks.scheduled) return;
|
||||
asks.scheduled = true;
|
||||
queueMicrotask(() => {
|
||||
asks.scheduled = false;
|
||||
void refetch();
|
||||
});
|
||||
},
|
||||
[discoveryEnabled, asks, refetch],
|
||||
);
|
||||
const value = useMemo<ParentSubagentsContextValue>(() => {
|
||||
if (inherited != null) return inherited;
|
||||
const byMessageId = new Map<string, ParentSubagentSummary[]>();
|
||||
|
|
@ -99,11 +126,28 @@ export function ParentSubagentsProvider({
|
|||
return updated === 0 ? left.threadId.localeCompare(right.threadId) : updated;
|
||||
});
|
||||
}
|
||||
return { conversationId, byMessageId, byThreadId, refresh, isError, discoveryEnabled };
|
||||
}, [conversationId, data, refresh, isError, discoveryEnabled, inherited]);
|
||||
return {
|
||||
conversationId,
|
||||
byMessageId,
|
||||
byThreadId,
|
||||
refresh,
|
||||
discover,
|
||||
isError,
|
||||
discoveryEnabled,
|
||||
};
|
||||
}, [conversationId, data, refresh, discover, isError, discoveryEnabled, inherited]);
|
||||
|
||||
/** A provider nested under one for the same conversation shares that one's followers. */
|
||||
const followers =
|
||||
inherited != null && sharedFollows != null ? (
|
||||
children
|
||||
) : (
|
||||
<ThreadFollowsProvider parentConversationId={conversationId}>
|
||||
{children}
|
||||
</ThreadFollowsProvider>
|
||||
);
|
||||
return (
|
||||
<ParentSubagentsContext.Provider value={value}>{children}</ParentSubagentsContext.Provider>
|
||||
<ParentSubagentsContext.Provider value={value}>{followers}</ParentSubagentsContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue