From 80a1e162bbc6fad22e37d077f24fcb34cd8eef72 Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Fri, 13 Nov 2026 02:05:39 +0000 Subject: [PATCH] feat(native-chat): open each subagent in its own view inside the chat pane Clicking a roster entry, an agent in the agents strip or a subagent row in the sidebar now opens that subagent's own rows in the chat pane, with a bar to switch between agents and a status bar with its state, Stop and the way back in place of the composer. Subagent rows are no longer inlined in the main transcript, which stays mounted underneath so going back keeps the reader's place. The inline-section machinery is removed. --- .../native-chat/NativeChatMessageList.tsx | 94 ++++---- .../native-chat/NativeChatResolvedView.tsx | 7 +- .../NativeChatStructuredSession.tsx | 30 +-- .../native-chat-response-actions-hang.ts | 9 +- .../slots/native-chat-timed-rows.ts | 2 +- .../slots/native-chat-transcript-input.ts | 9 +- .../native-chat-transcript-slot-selection.ts | 4 +- .../slots/native-chat-transcript-slots.ts | 92 ++++---- .../use-native-chat-transcript-row-context.ts | 6 +- .../slots/use-native-chat-transcript-slots.ts | 9 +- .../native-chat-side-chat-fork-point.ts | 2 +- .../actions/use-native-chat-reveal-latest.ts | 12 +- .../rows/NativeChatAssistantMessageRow.tsx | 5 +- .../messages/rows/NativeChatMessageRow.tsx | 11 +- .../messages/rows/NativeChatTranscriptRow.tsx | 46 ++-- ...ionHead.tsx => NativeChatSubagentHead.tsx} | 48 ++-- .../NativeChatSubagentRun.fixture.tsx | 2 +- .../subagents/NativeChatSubagentRun.tsx | 62 ++--- .../subagents/NativeChatSubagentStatusBar.tsx | 134 +++++++++++ .../NativeChatSubagentTranscripts.tsx | 80 +++++++ .../NativeChatSubagentViewBar.fixture.tsx | 70 ++++++ .../subagents/NativeChatSubagentViewBar.tsx | 110 +++++++++ .../subagents/native-chat-open-subagent.ts | 57 +++++ .../native-chat-subagent-delegation.ts | 87 ------- ...-chat-subagent-handoff-copy-budget.test.ts | 137 ----------- .../subagents/native-chat-subagent-history.ts | 46 ++++ .../native-chat-subagent-live-frontier.ts | 169 -------------- .../subagents/native-chat-subagent-reveal.ts | 142 ------------ .../subagents/native-chat-subagent-scope.ts | 133 +++++++++++ .../native-chat-subagent-section-slots.ts | 201 ---------------- .../native-chat-subagent-sections.ts | 216 ------------------ .../use-native-chat-subagent-scope.tsx | 132 +++++++++++ .../use-native-chat-subagent-sections.ts | 81 ------- .../use-structured-native-chat-subagents.tsx | 56 +++++ ...tiveChatStructuredSession.test-harness.tsx | 3 +- .../tools/diffs/use-native-chat-turn-diffs.ts | 14 +- ...e-native-chat-turn-opened-pull-requests.ts | 2 +- .../tools/runs/NativeChatToolRun.tsx | 22 +- .../runs/native-chat-transcript-work-runs.ts | 20 +- .../tasks/NativeChatBackgroundTasksStatus.tsx | 17 +- ...NativeChatStructuredSessionStatus.test.tsx | 19 +- .../NativeChatStructuredSessionStatus.tsx | 123 ++-------- .../tools/tasks/background-task-roster.ts | 15 ++ .../tasks/use-structured-session-task-stop.ts | 96 ++++++++ .../use-native-chat-history-jump.ts | 39 +--- .../use-native-chat-transcript-navigation.ts | 94 +++----- .../new-rows/native-chat-new-rows-marker.ts | 2 +- .../rail/native-chat-message-rail-items.ts | 3 +- .../native-chat-row-height-estimate.ts | 11 +- src/renderer/src/i18n/locales/en.json | 5 +- .../navigation/claude-agent-row-view.test.ts | 30 +++ .../navigation/claude-agent-row-view.ts | 11 +- 52 files changed, 1276 insertions(+), 1551 deletions(-) rename src/renderer/src/components/native-chat/subagents/{NativeChatSubagentSectionHead.tsx => NativeChatSubagentHead.tsx} (52%) create mode 100644 src/renderer/src/components/native-chat/subagents/NativeChatSubagentStatusBar.tsx create mode 100644 src/renderer/src/components/native-chat/subagents/NativeChatSubagentTranscripts.tsx create mode 100644 src/renderer/src/components/native-chat/subagents/NativeChatSubagentViewBar.fixture.tsx create mode 100644 src/renderer/src/components/native-chat/subagents/NativeChatSubagentViewBar.tsx create mode 100644 src/renderer/src/components/native-chat/subagents/native-chat-open-subagent.ts delete mode 100644 src/renderer/src/components/native-chat/subagents/native-chat-subagent-delegation.ts delete mode 100644 src/renderer/src/components/native-chat/subagents/native-chat-subagent-handoff-copy-budget.test.ts create mode 100644 src/renderer/src/components/native-chat/subagents/native-chat-subagent-history.ts delete mode 100644 src/renderer/src/components/native-chat/subagents/native-chat-subagent-live-frontier.ts delete mode 100644 src/renderer/src/components/native-chat/subagents/native-chat-subagent-reveal.ts create mode 100644 src/renderer/src/components/native-chat/subagents/native-chat-subagent-scope.ts delete mode 100644 src/renderer/src/components/native-chat/subagents/native-chat-subagent-section-slots.ts delete mode 100644 src/renderer/src/components/native-chat/subagents/native-chat-subagent-sections.ts create mode 100644 src/renderer/src/components/native-chat/subagents/use-native-chat-subagent-scope.tsx delete mode 100644 src/renderer/src/components/native-chat/subagents/use-native-chat-subagent-sections.ts create mode 100644 src/renderer/src/components/native-chat/subagents/use-structured-native-chat-subagents.tsx create mode 100644 src/renderer/src/components/native-chat/tools/tasks/use-structured-session-task-stop.ts create mode 100644 src/renderer/src/lib/agent-session/navigation/claude-agent-row-view.test.ts diff --git a/src/renderer/src/components/native-chat/NativeChatMessageList.tsx b/src/renderer/src/components/native-chat/NativeChatMessageList.tsx index 91f07967fda..7165eca9d04 100644 --- a/src/renderer/src/components/native-chat/NativeChatMessageList.tsx +++ b/src/renderer/src/components/native-chat/NativeChatMessageList.tsx @@ -41,9 +41,11 @@ import { useNativeChatTranscriptSlots } from './conversation/slots/use-native-ch import type { NativeChatTimedRow } from './conversation/slots/native-chat-timed-rows' import { useNativeChatTranscriptWindow } from './viewport/virtualization/use-native-chat-transcript-window' import { useNativeChatHistoryRetention } from './viewport/history/use-native-chat-history-retention' -import { useNativeChatSubagentSections } from './subagents/use-native-chat-subagent-sections' +import { useNativeChatSubagentScope } from './subagents/use-native-chat-subagent-scope' +import type { NativeChatSubagentView } from './subagents/native-chat-open-subagent' +import type { StructuredAgentSubagentRoster } from '../../../../shared/agent-session/view/structured-agent-session-subagent-roster' +import type { NativeChatTranscriptSlot } from './conversation/slots/native-chat-transcript-slots' import { toggleNativeChatExpandedKey } from './messages/disclosure/native-chat-expanded-keys' -import { useNativeChatTurnMembership } from './conversation/slots/use-native-chat-turn-membership' import { useNativeChatSideChatForkOffer, useNativeChatSideChatForkPointReport @@ -75,6 +77,8 @@ import { NativeChatPullRequestChangeContext } from './tools/pull-requests/Native import { transcriptTailRow } from './conversation/slots/native-chat-transcript-tail-row' import type { NativeChatAwaitingInput } from '../../../../shared/native-chat/native-chat-terminal-turn' +const NO_SLOTS: readonly NativeChatTranscriptSlot[] = [] + export function NativeChatMessageList({ ref, session, @@ -83,6 +87,7 @@ export function NativeChatMessageList({ journalLatestTurn: latestTurn, journalHostWork: hostWork, subagentRoster, + subagentView, railOutline = null, isVisible = true, isWorking, @@ -108,7 +113,9 @@ export function NativeChatMessageList({ /** The host's prompts still waiting on the person and its working answer (an older host: none). */ journalHostWork?: StructuredAgentSessionHostWork /** Every subagent the session's rosters named, whether or not its roster row is loaded. */ - subagentRoster?: Parameters[2] + subagentRoster?: StructuredAgentSubagentRoster + /** The subagent shown in place of the conversation (its own rows, no turns), and how to open one. */ + subagentView?: NativeChatSubagentView /** User messages older than the loaded window, from the host's outline. */ railOutline?: readonly NativeChatRailOutlineEntry[] | null isVisible?: boolean @@ -145,34 +152,28 @@ export function NativeChatMessageList({ root: contentRef, sourceKey: `${session.agent}:${session.sessionId}` }) - // Pending/failed reads cannot page; recovery remounts the sentinel to recheck its range. - const showOlderHistory = hasMore && session.readPhase === 'ready' - const { messages, subagentRows } = useNativeChatTranscriptProjection( + const { messages: conversation, subagentRows } = useNativeChatTranscriptProjection( session, journalItems, journalSubmissions, latestTurn ) - const { - sections: subagentSections, - subagentRowsInOrder, - subagentChoices, - subagentDisclosure, - openSubagentSections - } = useNativeChatSubagentSections(messages, subagentRows, subagentRoster) - // Folded subagent rows stay loaded, so a reopened reply keeps its reveal. - const loadedMessageIds = useMemo( - () => new Set([...messages.map(({ id }) => id), ...subagentSections.pathOf.keys()]), - [messages, subagentSections] - ) - const taskListPredecessors = useMemo(() => nativeChatTaskListPredecessors(messages), [messages]) - const turnRows = useNativeChatTurnMembership( - messages, + const scope = useNativeChatSubagentScope({ + view: subagentView, + conversation, + subagentRows, + roster: subagentRoster, journalItems, journalSubmissions, - latestTurn - ) + latestTurn, + isWorking + }) + const { agentId: subagentId, messages, turnRows, working, rowsInOrder } = scope + // Pending/failed reads cannot page; recovery remounts the sentinel to recheck its range. + const showOlderHistory = hasMore && session.readPhase === 'ready' && scope.pagesHistory + const loadedMessageIds = useMemo(() => new Set(messages.map(({ id }) => id)), [messages]) + const taskListPredecessors = useMemo(() => nativeChatTaskListPredecessors(messages), [messages]) const { liveTurnKey } = turnRows const showCiResultLines = useAppStore((state) => nativeChatShowsCiResultLines(state.settings)) // Hidden lines leave the transcript entirely, so they reserve no row or gap. @@ -182,28 +183,27 @@ export function NativeChatMessageList({ ) const latestTurnKey = turnKeys.findLast((key) => key !== undefined) const showTurnDiffs = useAppStore((state) => nativeChatShowsTurnDiffSummary(state.settings)) - const turnDiffs = useNativeChatTurnDiffs( - showTurnDiffs ? turnRows : null, - subagentRowsInOrder, - subagentSections.pathOf - ) - const openedPullRequests = useNativeChatTurnOpenedPullRequests(turnRows, subagentRowsInOrder) + const turns = scope.conversationTurns + const turnDiffs = useNativeChatTurnDiffs(showTurnDiffs ? turns : null, rowsInOrder) + const openedPullRequests = useNativeChatTurnOpenedPullRequests(turns, rowsInOrder) // Only real tail reasoning counts as thinking; an in-flight request with no output does not. const thinking = useMemo( - () => isStructuredAgentSessionThinking({ items: journalItems ?? [], latestTurn }), - [journalItems, latestTurn] + () => + subagentId === null && + isStructuredAgentSessionThinking({ items: journalItems ?? [], latestTurn }), + [journalItems, latestTurn, subagentId] ) const turnStatuses = useNativeChatTurnStatus({ turnKeys, liveTurnKey, - isWorking, + isWorking: working, workingStartedAt, settledTurns, thinking }) // Only unshown prompts need a waiting tail row; prompt cards explain their own wait. - const tailRow = transcriptTailRow(isWorking, awaitingInput) - const lifecycleWorking = session.transcriptLifecycle?.state === 'working' + const tailRow = transcriptTailRow(working, awaitingInput) + const lifecycleWorking = subagentId === null && session.transcriptLifecycle?.state === 'working' const { measureContent, typography } = useNativeChatRowTypography(contentRef) const forkOffer = useNativeChatSideChatForkOffer(latestTurnKey) const transcript = useNativeChatTranscriptSlots({ @@ -217,10 +217,9 @@ export function NativeChatMessageList({ turnDiffs, openedPullRequests: openedPullRequests.byTurn, expandedTurnKeys: expandedTurnIds, - isWorking, + isWorking: working, lifecycleWorking, - subagentSections, - subagentChoices, + subagentHeads: scope.heads, forkOffer, line: { tailRow, @@ -243,7 +242,7 @@ export function NativeChatMessageList({ ), [allSlots, journalItems, stopping, journalSubmissions, latestTurn, hostWork] ) - const navigationRequest = useNativeChatNavigationRequest(slots, messages, subagentSections) + const navigationRequest = useNativeChatNavigationRequest(slots) const newRows = useNativeChatNewRowsMarker( slots, waitingSlots, @@ -262,7 +261,7 @@ export function NativeChatMessageList({ scrollRef, contentRef, itemCount: slots.length, - isWorking, + isWorking: working, showsTailRow: tailRow !== null, isVisible, alignToViewportTop: transcriptWindow.alignToViewportTop, @@ -289,7 +288,8 @@ export function NativeChatMessageList({ }) const rail = useNativeChatMessageRail({ scrollRef, - slots, + // The rail outlines the conversation's prompts; a subagent's view has none. + slots: subagentId === null ? slots : NO_SLOTS, turnRows, virtualItems: transcriptWindow.virtualItems, outline: railOutline @@ -298,15 +298,15 @@ export function NativeChatMessageList({ request: navigationRequest, rail, slots, - conversation: messages, - sections: subagentSections, + conversation, + subagentRows, roster: subagentRoster, journalItems, - openSubagentSections, - subagentDisclosure, + subagentId, sessionKey: `${session.agent}:${session.sessionId}`, isVisible, loadEarlier, + holdHistory: historyRetention.leaveEnd, scrollRef, scrollMessageToTop, readerLeavesEnd, @@ -339,8 +339,7 @@ export function NativeChatMessageList({ scrollToBottom, onSent: newRows.dismiss, revealFindMatch: readerInput.revealFindMatch, - slots: allSlots, - revealSubagent: navigation.revealSubagent + slots: allSlots }) const rowContext = useNativeChatTranscriptRowContext({ @@ -355,7 +354,7 @@ export function NativeChatMessageList({ deliveryNotices, runtimeContext, onToggleExpandedTurn: toggleExpandedTurn, - subagentDisclosure, + onOpenSubagent: scope.open, onScrollMessageToTop: scrollMessageToTop, onRevealDiff: navigation.revealDiff }) @@ -364,6 +363,7 @@ export function NativeChatMessageList({
+ {scope.bar}
closeNativeChatSubagentOnEscape(event, paneKey)} onContextMenuCapture={contextMenu.onContextMenuCapture} className={cn( NATIVE_CHAT_APPEARANCE_ROOT_CLASS, @@ -348,7 +350,8 @@ export function NativeChatResolvedView({ ) : viewState.kind === 'empty' ? ( ) : ( - {(timedRows) => ( - - + {subagents.strip} {/* Workers' open prompts stay pinned here, above this chat's own prompt. */} - {prompt ? null : ( + {prompt || subagents.openId !== null ? null : ( )} - {composerShown ? null : } + {composerShown || subagents.openId !== null ? null : ( + + )} {nativeChatStructuredAsyncQuestion(props, controller, session, transport, submits)} {composerShown && } + {subagents.statusBar} {composerShown ? ( - slot.kind === 'message' && slot.depth === 0 && slot.message.timestamp !== null + slot.kind === 'message' && slot.message.timestamp !== null ? [{ id: slot.message.id, at: slot.message.timestamp }] : [] ) diff --git a/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-input.ts b/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-input.ts index 91efb9c108a..1f70971fa76 100644 --- a/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-input.ts +++ b/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-input.ts @@ -5,10 +5,7 @@ import type { NativeChatTurnDiff } from '../../../../../../shared/native-chat/to import type { NativeChatOpenedPullRequest } from '../../../../../../shared/native-chat/tools/native-chat-opened-pull-requests' import type { NativeChatRowTypography } from '../../viewport/virtualization/native-chat-row-height-estimate' import type { NativeChatSideChatForkOffer } from '../../messages/actions/native-chat-side-chat-fork-point' -import type { - NativeChatSubagentChoices, - NativeChatSubagentSections -} from '../../subagents/native-chat-subagent-sections' +import type { NativeChatSubagentHead } from '../../subagents/native-chat-subagent-scope' import type { NativeChatMarkdownImageSources } from '../../../../../../shared/native-chat/transcript/native-chat-generated-image-answers' @@ -34,8 +31,8 @@ export type NativeChatTranscriptSlotsInput = { lifecycleWorking: boolean /** Only where `/btw` listens: find the newest response that offers Fork. */ forkOffer?: NativeChatSideChatForkOffer - subagentSections?: NativeChatSubagentSections - subagentChoices?: NativeChatSubagentChoices + /** Subagents no roster row in this transcript names, each drawn as a head at its first row. */ + subagentHeads?: readonly NativeChatSubagentHead[] /** The open reasoning block the live activity line discloses: its row takes no slot meanwhile. */ liveReasoningId?: string | null } diff --git a/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-slot-selection.ts b/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-slot-selection.ts index 1c66b2ececd..e43e5fff5df 100644 --- a/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-slot-selection.ts +++ b/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-slot-selection.ts @@ -10,9 +10,7 @@ export function nativeChatSlotKey(slot: NativeChatTranscriptSlot): string { case 'message': return slot.message.id case 'subagent': - return `subagent-section:${slot.agentId}` - case 'subagent-entries': - return `subagent-entries:${slot.rosterRowId}:${slot.agents[0]?.id}` + return `subagent-head:${slot.agentId}` } } diff --git a/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-slots.ts b/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-slots.ts index 170731386b1..57c11686826 100644 --- a/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-slots.ts +++ b/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-slots.ts @@ -1,6 +1,9 @@ // Count only rendered rows: virtualized entries reserve height even when React would render null. -import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types' +import type { + NativeChatMessage, + NativeChatSubagentEntry +} from '../../../../../../shared/native-chat/native-chat-types' import type { NativeChatTurnStatus } from '../../../../../../shared/native-chat/transcript/native-chat-turn-status' import { isNativeChatRowInLiveWorkingTurn } from '../../../../../../shared/native-chat/transcript/native-chat-live-turn-membership' import { nativeChatTurnBarRows } from '../../../../../../shared/native-chat/transcript/native-chat-turn-grouping' @@ -13,22 +16,14 @@ import { nativeChatGeneratedImageAnswers } from '../../../../../../shared/native import { nativeChatMarkdownImageSources } from '../../markdown/native-chat-markdown-image-sources' import { estimateNativeChatRowHeight, - nativeChatRowContentMetrics + nativeChatRowContentMetrics, + NATIVE_CHAT_SUBAGENT_HEAD_PX } from '../../viewport/virtualization/native-chat-row-height-estimate' import type { NativeChatResolvedPrompt } from '../../../../../../shared/native-chat/native-chat-resolution-receipt' import type { NativeChatTurnDiff } from '../../../../../../shared/native-chat/tools/native-chat-turn-diffs' import type { NativeChatOpenedPullRequest } from '../../../../../../shared/native-chat/tools/native-chat-opened-pull-requests' -import { - NO_NATIVE_CHAT_SUBAGENT_CHOICES, - NO_NATIVE_CHAT_SUBAGENT_SECTIONS, - type NativeChatSubagentRosterState -} from '../../subagents/native-chat-subagent-sections' -import { nativeChatSubagentLiveSections } from '../../subagents/native-chat-subagent-live-frontier' -import { - nativeChatSubagentSectionSlots, - type NativeChatSubagentEntriesSlot, - type NativeChatSubagentSectionSlot -} from '../../subagents/native-chat-subagent-section-slots' +import type { NativeChatSubagentHead } from '../../subagents/native-chat-subagent-scope' +import { compareNativeChatDisplayMessages as compareMessages } from '../../../../../../shared/native-chat/transcript/native-chat-message-order' import { isGeneratedImageOperation } from '../../../../../../shared/native-chat/native-chat-generated-image' import { nativeChatRowRendersProse, @@ -49,10 +44,18 @@ import { import { markNativeChatResponseActionsHang } from './native-chat-response-actions-hang' import type { Translate } from '../../../../i18n/use-translate' -export type NativeChatTranscriptSlot = - | NativeChatMessageSlot - | NativeChatSubagentSectionSlot - | NativeChatSubagentEntriesSlot +export type NativeChatTranscriptSlot = NativeChatMessageSlot | NativeChatSubagentHeadSlot + +/** Opens a subagent no loaded roster row names, at its first row. */ +export type NativeChatSubagentHeadSlot = { + kind: 'subagent' + agentId: string + /** The conversation turn the head sits in, so the outline rail can place it. */ + turnKey: string | undefined + /** The roster's entry for the agent; absent when no roster names it. */ + entry: NativeChatSubagentEntry | undefined + estimatedHeight: number +} export type NativeChatMessageSlot = { kind: 'message' @@ -77,28 +80,25 @@ export type NativeChatMessageSlot = { /** The agent's next row in the same turn follows directly, so the two sit close. */ continuesTurn?: boolean /** In a turn: whether this row holds its response actions, even when tools or thoughts follow: - * the last drawn response with words, else the last with images. Absent outside a turn and in - * subagent sections. */ + * the last drawn response with words, else the last with images. Absent outside a turn. */ endsResponse?: boolean /** This response is the newest one in the conversation. */ latestResponse?: boolean /** Response controls under this row may hang into the gap below it: the row draws nothing after * its message, and what follows is the person's own right-aligned bubble or nothing. Absent when * something left-side follows (an agent's card, a notice, a task or subagent row, the turn's bar, - * diff rollup or PR card), where the controls keep their own height, and in subagent sections. */ + * diff rollup or PR card), where the controls keep their own height. */ actionsHang?: boolean turnDiff: NativeChatTurnDiff | undefined /** Pull requests this row's turn opened, drawn after it. */ openedPullRequests?: readonly NativeChatOpenedPullRequest[] - /** A closed roster list hides child sections regardless of their individual expansion state. */ - subagentRoster: NativeChatSubagentRosterState | undefined - /** Subagent sections this row sits inside; 0 is the conversation. */ - depth: number estimatedHeight: number /** Members of an unbroken work run, with message as its head. */ workRun?: readonly NativeChatMessage[] } +const NO_SUBAGENT_HEADS: readonly NativeChatSubagentHead[] = [] + export function buildNativeChatTranscriptSlots( input: NativeChatTranscriptSlotsInput, t?: Translate @@ -128,8 +128,7 @@ export function buildNativeChatTranscript( expandedTurnKeys, isWorking, lifecycleWorking, - subagentSections: sections = NO_NATIVE_CHAT_SUBAGENT_SECTIONS, - subagentChoices: choices = NO_NATIVE_CHAT_SUBAGENT_CHOICES, + subagentHeads = NO_SUBAGENT_HEADS, liveReasoningId = null, forkOffer } = input @@ -166,18 +165,25 @@ export function buildNativeChatTranscript( } }) const slots: NativeChatTranscriptSlot[] = [] - const live = nativeChatSubagentLiveSections(messages, sections, isWorking || lifecycleWorking) - const sectionSlots = nativeChatSubagentSectionSlots({ - sections, - choices, - live, - receipts, - slots, - typography - }) - const pending = [...(sections.openAt.get(null) ?? [])] + let nextHead = 0 + /** Heads whose first row comes before `message`; undefined flushes the rest. */ + const pushHeadsBefore = (message: NativeChatMessage | undefined): void => { + for (; nextHead < subagentHeads.length; nextHead += 1) { + const head = subagentHeads[nextHead]! + if (message !== undefined && compareMessages(head.first.message, message) >= 0) { + return + } + slots.push({ + kind: 'subagent', + agentId: head.agentId, + turnKey: head.first.turnKey, + entry: head.entry, + estimatedHeight: NATIVE_CHAT_SUBAGENT_HEAD_PX * (typography?.spacingScale ?? 1) + }) + } + } for (const [index, message] of messages.entries()) { - sectionSlots.openBefore(pending, message, 0) + pushHeadsBefore(message) const turnKey = turnKeys[index] const receipt = receipts.get(message.id) const bar = turnKey === undefined ? undefined : bars.get(turnKey) @@ -204,7 +210,6 @@ export function buildNativeChatTranscript( (!folded && (message.agentStart || nativeChatRowRendersContent(message.blocks)) && message.id !== liveReasoningId) - const roster = sectionSlots.rosterAt(message.id) if ( drawsRow || status !== undefined || @@ -225,8 +230,6 @@ export function buildNativeChatTranscript( turnFolds: turnKey !== undefined && foldableTurnKeys.has(turnKey), turnDiff, openedPullRequests, - subagentRoster: roster, - depth: 0, estimatedHeight: estimateNativeChatRowHeight( nativeChatRowContentMetrics(message, typography), { @@ -241,9 +244,8 @@ export function buildNativeChatTranscript( ) }) } - sectionSlots.openAnchoredAt(message, roster, turnKey) } - sectionSlots.openBefore(pending, undefined, 0) + pushHeadsBefore(undefined) const drawn = nativeChatTranscriptWorkRuns(slots, typography) // One action holder per turn: its last drawn response with words, else (when folding hid them) // its last drawn image response. Tools and thoughts never hold them. @@ -251,7 +253,7 @@ export function buildNativeChatTranscript( const lastImageByTurn = new Map() let newestOffered: NativeChatMessageSlot | undefined for (const slot of drawn) { - if (slot.kind !== 'message' || slot.depth !== 0) { + if (slot.kind !== 'message') { continue } if (forkOffer && nativeChatSlotOffersFork(slot, forkOffer)) { @@ -284,7 +286,6 @@ export function buildNativeChatTranscript( const latestResponse = drawn.findLast( (slot) => slot.kind === 'message' && - slot.depth === 0 && slot.drawsMessage && !slot.receipt && slot.message.role === 'assistant' && @@ -300,9 +301,6 @@ export function buildNativeChatTranscript( if ( slot.kind === 'message' && next.kind === 'message' && - // A subagent's section keeps the transcript's gap as part of its frame. - slot.depth === 0 && - next.depth === 0 && slot.turnKey !== undefined && next.turnKey === slot.turnKey && // The agent's own next step, not a notice or task row that trails its answer. diff --git a/src/renderer/src/components/native-chat/conversation/slots/use-native-chat-transcript-row-context.ts b/src/renderer/src/components/native-chat/conversation/slots/use-native-chat-transcript-row-context.ts index 012a58dbf12..1e112c2f917 100644 --- a/src/renderer/src/components/native-chat/conversation/slots/use-native-chat-transcript-row-context.ts +++ b/src/renderer/src/components/native-chat/conversation/slots/use-native-chat-transcript-row-context.ts @@ -24,7 +24,7 @@ export function useNativeChatTranscriptRowContext({ runtimeContext, structuredAttachments, onToggleExpandedTurn, - subagentDisclosure, + onOpenSubagent, onScrollMessageToTop, onRevealDiff }: NativeChatTranscriptRowContextInput): NativeChatTranscriptRowContext { @@ -41,7 +41,7 @@ export function useNativeChatTranscriptRowContext({ runtimeContext, structuredAttachments, onToggleExpandedTurn, - subagentDisclosure, + onOpenSubagent, onScrollMessageToTop, onRevealDiff }), @@ -58,7 +58,7 @@ export function useNativeChatTranscriptRowContext({ structuredAttachments, onScrollMessageToTop, taskListPredecessors, - subagentDisclosure, + onOpenSubagent, onToggleExpandedTurn ] ) diff --git a/src/renderer/src/components/native-chat/conversation/slots/use-native-chat-transcript-slots.ts b/src/renderer/src/components/native-chat/conversation/slots/use-native-chat-transcript-slots.ts index 92bb31c8821..cbd124834d2 100644 --- a/src/renderer/src/components/native-chat/conversation/slots/use-native-chat-transcript-slots.ts +++ b/src/renderer/src/components/native-chat/conversation/slots/use-native-chat-transcript-slots.ts @@ -50,8 +50,7 @@ export function useNativeChatTranscriptSlots({ expandedTurnKeys, isWorking, lifecycleWorking, - subagentSections, - subagentChoices, + subagentHeads, forkOffer } = input const { tailRow, thinking, stopping = false, activityText } = line @@ -102,8 +101,7 @@ export function useNativeChatTranscriptSlots({ expandedTurnKeys, isWorking, lifecycleWorking, - subagentSections, - subagentChoices, + subagentHeads, liveReasoningId, forkOffer }), @@ -118,8 +116,7 @@ export function useNativeChatTranscriptSlots({ messages, openedPullRequests, receipts, - subagentChoices, - subagentSections, + subagentHeads, turnDiffs, turnKeys, turnStatuses, diff --git a/src/renderer/src/components/native-chat/messages/actions/native-chat-side-chat-fork-point.ts b/src/renderer/src/components/native-chat/messages/actions/native-chat-side-chat-fork-point.ts index ef6c6e56698..4d26e3b13b1 100644 --- a/src/renderer/src/components/native-chat/messages/actions/native-chat-side-chat-fork-point.ts +++ b/src/renderer/src/components/native-chat/messages/actions/native-chat-side-chat-fork-point.ts @@ -21,7 +21,7 @@ export function nativeChatSlotOffersFork( return nativeChatRowOffersFork( { message: slot.message, - inSubagentSection: slot.depth > 0, + inSubagentSection: false, turnWorking: slot.activeTurnIsWorking, inLatestTurn: slot.turnKey !== undefined && slot.turnKey === offer.latestTurnKey }, diff --git a/src/renderer/src/components/native-chat/messages/actions/use-native-chat-reveal-latest.ts b/src/renderer/src/components/native-chat/messages/actions/use-native-chat-reveal-latest.ts index 492a8fb14fa..9bd811f738e 100644 --- a/src/renderer/src/components/native-chat/messages/actions/use-native-chat-reveal-latest.ts +++ b/src/renderer/src/components/native-chat/messages/actions/use-native-chat-reveal-latest.ts @@ -60,8 +60,6 @@ export type NativeChatMessageListHandle = { revealFindMatch: (match: Range, bar: DOMRectReadOnly | null) => void /** What the row drawing this message copies from its Copy button; null when none draws it. */ messageCopyText: (messageId: string) => string | null - /** Open a subagent's activity where it sits in the conversation and bring it into view. */ - revealSubagent: (agentId: string) => void } /** This pane's own transcript; an unmounted pane's reveal reaches nothing. */ @@ -97,9 +95,8 @@ export function useNativeChatMessageListHandle( scrollToBottom, onSent, revealFindMatch, - slots, - revealSubagent - }: Pick & { + slots + }: Pick & { beginNavigation: () => void scrollToBottom: (reason: 'send') => void /** The reader answered, whether or not the view moves. */ @@ -124,9 +121,8 @@ export function useNativeChatMessageListHandle( revealLatest, readerAtEnd, revealFindMatch, - messageCopyText: (messageId) => nativeChatSlotCopyText(slots, messageId), - revealSubagent + messageCopyText: (messageId) => nativeChatSlotCopyText(slots, messageId) }), - [readerAtEnd, revealLatest, revealFindMatch, revealSubagent, slots] + [readerAtEnd, revealLatest, revealFindMatch, slots] ) } diff --git a/src/renderer/src/components/native-chat/messages/rows/NativeChatAssistantMessageRow.tsx b/src/renderer/src/components/native-chat/messages/rows/NativeChatAssistantMessageRow.tsx index e709e5008dd..5020d7ff3ec 100644 --- a/src/renderer/src/components/native-chat/messages/rows/NativeChatAssistantMessageRow.tsx +++ b/src/renderer/src/components/native-chat/messages/rows/NativeChatAssistantMessageRow.tsx @@ -54,7 +54,6 @@ export function NativeChatAssistantMessageRow({ endsResponse, latestResponse = true, actionsHang = false, - inSubagentSection = false, runtimeContext, fork } = props @@ -76,7 +75,6 @@ export function NativeChatAssistantMessageRow({ message.role === 'assistant' && message.source === 'transcript' && !message.agentStart && - !inSubagentSection && isRootAgentJournalItem(message) return ( @@ -157,8 +155,7 @@ function toolRunProps( revealedDiff: run ? run.revealedDiff : props.revealedDiff, onRevealDiff: props.onScrollMessageToTop, subagentGroups: content.subagentGroups, - subagentRoster: props.subagentRoster, - subagentDisclosure: props.subagentDisclosure, + onOpenSubagent: props.onOpenSubagent, backgroundTasks: content.backgroundTasks, followsProse: content.markdown.length > 0 || content.hasImages, expandSignal: props.expandSignal, diff --git a/src/renderer/src/components/native-chat/messages/rows/NativeChatMessageRow.tsx b/src/renderer/src/components/native-chat/messages/rows/NativeChatMessageRow.tsx index 0ee81443a4a..3d338bf9b07 100644 --- a/src/renderer/src/components/native-chat/messages/rows/NativeChatMessageRow.tsx +++ b/src/renderer/src/components/native-chat/messages/rows/NativeChatMessageRow.tsx @@ -15,10 +15,6 @@ import { nativeChatNoticeBlock } from '../../../../../../shared/native-chat/nati import { nativeChatMessageRowBlocks } from './native-chat-message-row-words' import { ProviderFrameRow } from '../diagnostics/NativeChatProviderDetails' import type { NativeChatDiffReveal } from '../../../../../../shared/native-chat/tools/native-chat-turn-diffs' -import type { - NativeChatSubagentDisclosure, - NativeChatSubagentRosterState -} from '../../subagents/native-chat-subagent-sections' import type { RuntimeFileOperationArgs } from '@/runtime/files/runtime-file-client-types' import { useNativeChatWorkRun } from '../../tools/runs/use-native-chat-work-run' import { useNativeChatRowNavigation } from '../actions/use-native-chat-row-navigation' @@ -65,11 +61,8 @@ export type MessageRowProps = { /** Align this message's top to the top of the scroll viewport. */ onScrollMessageToTop: (el: HTMLElement) => void deliveryNotice?: NativeChatDeliveryNotice - /** On a roster row: its list's state and the subagents whose rows open below it. */ - subagentRoster?: NativeChatSubagentRosterState - subagentDisclosure?: NativeChatSubagentDisclosure - /** Inside a subagent's section, whose border has to reach past the row's controls. */ - inSubagentSection?: boolean + /** On a roster row: opens one of its subagents in its own view. */ + onOpenSubagent?: (agentId: string) => void structuredAttachments?: boolean runtimeContext?: RuntimeFileOperationArgs | null /** On a user row: discards it and everything after it. */ diff --git a/src/renderer/src/components/native-chat/messages/rows/NativeChatTranscriptRow.tsx b/src/renderer/src/components/native-chat/messages/rows/NativeChatTranscriptRow.tsx index 0b8694affa9..10811057885 100644 --- a/src/renderer/src/components/native-chat/messages/rows/NativeChatTranscriptRow.tsx +++ b/src/renderer/src/components/native-chat/messages/rows/NativeChatTranscriptRow.tsx @@ -6,9 +6,7 @@ import { NativeChatResolutionReceipt } from '../../prompts/NativeChatResolutionR import { NativeChatWorkingStatus } from '../../conversation/turns/NativeChatWorkingStatus' import { NativeChatTurnDiffRollup } from '../../tools/diffs/NativeChatTurnDiffRollup' import { NativeChatOpenedPullRequestCard } from '../../tools/pull-requests/NativeChatOpenedPullRequestCard' -import { NativeChatSubagentSectionHead } from '../../subagents/NativeChatSubagentSectionHead' -import { NativeChatSubagentEntries } from '../../subagents/NativeChatSubagentRun' -import type { NativeChatSubagentDisclosure } from '../../subagents/native-chat-subagent-sections' +import { NativeChatSubagentHead } from '../../subagents/NativeChatSubagentHead' import type { NativeChatTaskListPredecessors } from '../../../../../../shared/native-chat/input/native-chat-task-list-history' import type { NativeChatTranscriptSlot } from '../../conversation/slots/native-chat-transcript-slots' import type { NativeChatTimedRow } from '../../conversation/slots/native-chat-timed-rows' @@ -42,7 +40,8 @@ export type NativeChatTranscriptRowContext = { structuredAttachments?: boolean runtimeContext?: RuntimeFileOperationArgs | null onToggleExpandedTurn: (turnKey: string) => void - subagentDisclosure: NativeChatSubagentDisclosure + /** Opens a subagent's own view; absent where the transcript has none to open. */ + onOpenSubagent?: (agentId: string) => void onScrollMessageToTop: (element: HTMLElement) => void onRevealDiff: (target: NativeChatDiffTarget) => void } @@ -64,30 +63,12 @@ export const NativeChatTranscriptRow = memo(function NativeChatTranscriptRow({ // Offered only on the conversation's own turn-opening prompts (`nativeChatRowOffersRewind`). const rewind = useContext(NativeChatRewindContext) const fork = useContext(NativeChatForkContext) - const sectionClassName = cn( - slot.depth > 0 && 'border-l-2 border-border/60 pl-3', - slot.depth > 1 && 'ml-4' - ) if (slot.kind === 'subagent') { return ( -
- -
- ) - } - if (slot.kind === 'subagent-entries') { - return ( - ) } @@ -116,8 +97,7 @@ export const NativeChatTranscriptRow = memo(function NativeChatTranscriptRow({
{newRowsMarker?.place === 'above-row' ? marker : null} @@ -152,13 +132,15 @@ export const NativeChatTranscriptRow = memo(function NativeChatTranscriptRow({ actionsHang={slot.actionsHang === true && !newRowsMarkerBelow} onScrollMessageToTop={context.onScrollMessageToTop} deliveryNotice={deliveryNotice} - subagentRoster={slot.subagentRoster} - subagentDisclosure={context.subagentDisclosure} - inSubagentSection={slot.depth > 0} + onOpenSubagent={context.onOpenSubagent} runtimeContext={context.runtimeContext} structuredAttachments={context.structuredAttachments} rewind={ - nativeChatRowOffersRewind(message, slot, deliveryNotice !== undefined) && + nativeChatRowOffersRewind( + message, + { depth: 0, turnKey }, + deliveryNotice !== undefined + ) && (!rewind?.eligibleItemIds || rewind.eligibleItemIds.has(message.id)) ? rewind : undefined diff --git a/src/renderer/src/components/native-chat/subagents/NativeChatSubagentSectionHead.tsx b/src/renderer/src/components/native-chat/subagents/NativeChatSubagentHead.tsx similarity index 52% rename from src/renderer/src/components/native-chat/subagents/NativeChatSubagentSectionHead.tsx rename to src/renderer/src/components/native-chat/subagents/NativeChatSubagentHead.tsx index 4b43dcaae04..8a878f37960 100644 --- a/src/renderer/src/components/native-chat/subagents/NativeChatSubagentSectionHead.tsx +++ b/src/renderer/src/components/native-chat/subagents/NativeChatSubagentHead.tsx @@ -1,43 +1,49 @@ import { Bot, ChevronRight } from 'lucide-react' -import { cn } from '@/lib/class-names' import { useTranslate } from '@/i18n/use-translate' import { normalizeSubagentState } from '../../../../../shared/native-chat/transcript/native-chat-subagent-summary' import type { NativeChatSubagentEntry } from '../../../../../shared/native-chat/native-chat-types' import { StatusDot } from './NativeChatSubagentRun' -/** Head a section whose roster entry is unloaded or nested; unnamed agents have no invented label or state. */ -export function NativeChatSubagentSectionHead({ +/** Head for a subagent no loaded roster row names; unnamed agents have no invented label or state. */ +export function NativeChatSubagentHead({ agentId, entry, - expanded, - onSetOpen + onOpen }: { agentId: string entry: NativeChatSubagentEntry | undefined - expanded: boolean - onSetOpen: (agentId: string, open: boolean) => void + onOpen?: (agentId: string) => void }): React.JSX.Element { const t = useTranslate() const state = entry === undefined ? null : normalizeSubagentState(entry.state) - return ( - ) } diff --git a/src/renderer/src/components/native-chat/subagents/NativeChatSubagentRun.fixture.tsx b/src/renderer/src/components/native-chat/subagents/NativeChatSubagentRun.fixture.tsx index fd2881cdd75..65a7bc773eb 100644 --- a/src/renderer/src/components/native-chat/subagents/NativeChatSubagentRun.fixture.tsx +++ b/src/renderer/src/components/native-chat/subagents/NativeChatSubagentRun.fixture.tsx @@ -46,7 +46,7 @@ const block: NativeChatSubagentGroupBlock = { function Roster() { return (
- {}} /> + {}} />
) } diff --git a/src/renderer/src/components/native-chat/subagents/NativeChatSubagentRun.tsx b/src/renderer/src/components/native-chat/subagents/NativeChatSubagentRun.tsx index aba13b19bc6..18d3860253f 100644 --- a/src/renderer/src/components/native-chat/subagents/NativeChatSubagentRun.tsx +++ b/src/renderer/src/components/native-chat/subagents/NativeChatSubagentRun.tsx @@ -1,6 +1,6 @@ -import { useState } from 'react' import { Bot, ChevronRight } from 'lucide-react' import { cn } from '@/lib/class-names' +import { useTranslate } from '@/i18n/use-translate' import { HoverCard, HoverCardContent, HoverCardTrigger } from '@/components/ui/hover-card' import { useNow } from '@/hooks/use-now' import { @@ -21,7 +21,7 @@ import type { NativeChatSubagentState } from '../../../../../shared/native-chat/native-chat-types' import { formatNativeChatDuration } from '../../../../../shared/native-chat/transcript/native-chat-turn-status' -import { nativeChatSubagentEntryRuns } from './native-chat-subagent-sections' +import { useNativeChatDisclosure } from '../messages/disclosure/native-chat-disclosure-store' import { sayNativeChatSubagentGroupTranslated as say } from './native-chat-subagent-group-words-text' import { sayNativeChatSessionOptionTranslated as sayOption } from '../session/options/controls/native-chat-session-option-labels-text' @@ -64,7 +64,7 @@ export function StatusDot({ } /** Leaf so the shared 1s clock re-renders only the digits, never the roster. */ -function SubagentElapsed({ +export function SubagentElapsed({ startedAt, settledAt, counting @@ -78,23 +78,21 @@ function SubagentElapsed({ return <>{formatNativeChatDuration(Math.max(0, (end - startedAt) / 1000))} } -/** Each child entry controls its section; the transcript inserts its rows after the entry. */ +/** Each entry opens its subagent's own view. */ export function NativeChatSubagentEntries({ agents, - sections, - onSetSectionOpen, + onOpen, className }: { agents: readonly NativeChatSubagentEntry[] - sections?: ReadonlyMap - onSetSectionOpen?: (agentId: string, open: boolean) => void + onOpen?: (agentId: string) => void className?: string }): React.JSX.Element { + const t = useTranslate() return (
    {agents.map((agent) => { const state = normalizeSubagentState(agent.state) - const sectionOpen = sections?.get(agent.id) const detail = subagentEntryDetail(agent) const runsOn = subagentEntryRunsOn(agent, sayOption) const entry = ( @@ -129,27 +127,23 @@ export function NativeChatSubagentEntries({ ) return ( - // Named so a reveal from the agents strip can bring this entry into view.
  • - {sectionOpen === undefined ? ( + {onOpen === undefined ? (
    {entry}
    ) : ( )} @@ -215,25 +209,22 @@ function SubagentEntryPreview({ /** Trust journal child states: children outlive their spawning turn, and only host/provider settlement proves lost contact. */ export function NativeChatSubagentRun({ block, - open: heldOpen, - onSetOpen, - sections, - onSetSectionOpen + disclosureId, + onOpenSubagent }: { block: NativeChatSubagentGroupBlock - /** Whether the entries show, when the transcript holds that past this row's lifetime. */ - open?: boolean - onSetOpen?: (open: boolean) => void - /** The children whose rows open under their entries, and whether each is open. */ - sections?: ReadonlyMap - onSetSectionOpen?: (agentId: string, open: boolean) => void + /** Remembers the reader's open/closed choice past this row's lifetime. */ + disclosureId?: string + onOpenSubagent?: (agentId: string) => void }): React.JSX.Element | null { - const [localOpen, setLocalOpen] = useState(false) - const open = heldOpen ?? localOpen - const setOpen = onSetOpen ?? setLocalOpen const agents = block.agents // Not memoized: its words follow the reader's language, which can change under the same roster. const header = nativeChatSubagentGroupHeader(agents, say) + // The list shows while any child works, until the reader says otherwise. + const { open, setOpen } = useNativeChatDisclosure( + disclosureId === undefined ? undefined : `subagent-roster:${disclosureId}:${block.groupId}`, + header.working + ) if (header.total === 0) { return null } @@ -277,12 +268,7 @@ export function NativeChatSubagentRun({ /> {open ? ( - + ) : null}
) diff --git a/src/renderer/src/components/native-chat/subagents/NativeChatSubagentStatusBar.tsx b/src/renderer/src/components/native-chat/subagents/NativeChatSubagentStatusBar.tsx new file mode 100644 index 00000000000..8d9e98f4d34 --- /dev/null +++ b/src/renderer/src/components/native-chat/subagents/NativeChatSubagentStatusBar.tsx @@ -0,0 +1,134 @@ +import { useMemo } from 'react' +import { ChevronLeft } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { useTranslate } from '@/i18n/use-translate' +import { + formatSubagentTokens, + subagentStateLabel +} from '../../../../../shared/native-chat/transcript/native-chat-subagent-group-header' +import { normalizeSubagentState } from '../../../../../shared/native-chat/transcript/native-chat-subagent-summary' +import type { NativeChatSubagentEntry } from '../../../../../shared/native-chat/native-chat-types' +import type { AgentChildRowModel } from '../../../../../shared/agent-status/presentation/agent-child-row-model' +import { backgroundTaskRowStopId } from '../../../../../shared/background-task-roster' +import type { StructuredSessionBackgroundTasksView } from '../../../../../shared/structured-session-background-tasks-view' +import { structuredSessionBackgroundTaskGroups } from '../tools/tasks/background-task-roster' +import { sayBackgroundTaskTranslated as sayTask } from '../tools/tasks/background-task-words-text' +import { useStructuredSessionChildRowContext } from '../tools/tasks/use-structured-session-child-row-context' +import type { StructuredSessionTaskStop } from '../tools/tasks/use-structured-session-task-stop' +import { StatusDot, SubagentElapsed } from './NativeChatSubagentRun' +import { sayNativeChatSubagentGroupTranslated as say } from './native-chat-subagent-group-words-text' + +/** Stands in for the composer while a subagent's view is open: its state, its Stop, and the way back. */ +export function NativeChatSubagentStatusBar({ + entry, + stop, + onBack +}: { + entry: NativeChatSubagentEntry | undefined + /** Present while the agents strip could stop this subagent. */ + stop?: { stopping: boolean; onStop: () => void } + onBack: () => void +}): React.JSX.Element { + const t = useTranslate() + const state = entry ? normalizeSubagentState(entry.state) : null + return ( +
+
+ {state ? ( + + + + {subagentStateLabel(state, 1, 1, say)} + + {entry?.startedAt !== undefined ? ( + // Ticking digits stay out of live announcements. + + {' · '} + + + ) : null} + {typeof entry?.tokens === 'number' ? ( + {` · ${formatSubagentTokens(entry.tokens)}`} + ) : null} + + ) : null} + + {stop ? ( + + ) : null} + + +
+
+ ) +} + +function rowFor( + rows: readonly AgentChildRowModel[], + providerId: string +): AgentChildRowModel | undefined { + for (const row of rows) { + const found = row.providerId === providerId ? row : rowFor(row.owned, providerId) + if (found) { + return found + } + } + return undefined +} + +/** A structured chat's bar: the roster's entry for the agent, with the agents strip's own Stop. */ +export function NativeChatStructuredSubagentStatusBar({ + agentId, + entry, + paneKey, + backgroundTasks, + stop, + onBack +}: { + agentId: string + entry: NativeChatSubagentEntry | undefined + paneKey: string + backgroundTasks: StructuredSessionBackgroundTasksView + stop: StructuredSessionTaskStop + onBack: () => void +}): React.JSX.Element { + const childRowContext = useStructuredSessionChildRowContext(paneKey) + const { tasks, settledTasks, children, supportsStop } = backgroundTasks + const stopId = useMemo(() => { + const rows = structuredSessionBackgroundTaskGroups( + tasks, + settledTasks, + children, + childRowContext + ).flatMap((group) => group.tasks.map(({ row }) => row)) + const row = rowFor(rows, agentId) + return row ? backgroundTaskRowStopId(row, supportsStop) : null + }, [agentId, childRowContext, children, settledTasks, supportsStop, tasks]) + const { onStop, stoppingTaskIds } = stop + return ( + onStop(stopId) } + } + onBack={onBack} + /> + ) +} diff --git a/src/renderer/src/components/native-chat/subagents/NativeChatSubagentTranscripts.tsx b/src/renderer/src/components/native-chat/subagents/NativeChatSubagentTranscripts.tsx new file mode 100644 index 00000000000..89d5dfca859 --- /dev/null +++ b/src/renderer/src/components/native-chat/subagents/NativeChatSubagentTranscripts.tsx @@ -0,0 +1,80 @@ +import { useCallback, useEffect, useMemo, useRef } from 'react' +import { cn } from '@/lib/class-names' +import { NativeChatMessageList } from '../NativeChatMessageList' +import { NativeChatSideChatForkPointContext } from '../messages/actions/native-chat-fork-context' +import { + openNativeChatSubagent, + useNativeChatOpenSubagent, + type NativeChatSubagentView +} from './native-chat-open-subagent' + +/** The conversation stays mounted, hidden, under an open subagent's view, so going back keeps the reader's place. */ +export function NativeChatSubagentTranscripts({ + paneKey, + ...props +}: React.ComponentProps & { + /** The chat's status pane key, which also names it to the sidebar's subagent rows. */ + paneKey: string +}): React.JSX.Element { + const openId = useNativeChatOpenSubagent(paneKey) + const open = useCallback( + (agentId: string | null) => openNativeChatSubagent(paneKey, agentId), + [paneKey] + ) + const main = useMemo(() => ({ agentId: null, open }), [open]) + const shown = useMemo( + () => (openId === null ? null : { agentId: openId, open }), + [open, openId] + ) + const isVisible = props.isVisible ?? true + const mainRef = useRef(null) + const viewRef = useRef(null) + const shownId = shown?.agentId ?? null + useEffect(() => { + // Focus the hidden conversation dropped stays in the pane, so Esc can bring it back. + const active = document.activeElement + if (shownId !== null && (active === document.body || mainRef.current?.contains(active))) { + viewRef.current?.focus({ preventScroll: true }) + } + }, [shownId]) + return ( +
+
+ +
+ {shown ? ( +
+ {/* `/btw` forks from the conversation, never from a subagent's rows. */} + + + +
+ ) : null} +
+ ) +} diff --git a/src/renderer/src/components/native-chat/subagents/NativeChatSubagentViewBar.fixture.tsx b/src/renderer/src/components/native-chat/subagents/NativeChatSubagentViewBar.fixture.tsx new file mode 100644 index 00000000000..6e8a811aa4a --- /dev/null +++ b/src/renderer/src/components/native-chat/subagents/NativeChatSubagentViewBar.fixture.tsx @@ -0,0 +1,70 @@ +import { defineFixture } from '../../../component-fixtures/component-fixture' +import type { NativeChatSubagentEntry } from '../../../../../shared/native-chat/native-chat-types' +import { nativeChatAppearanceStyle } from '../appearance/native-chat-appearance-style' +import { NativeChatSubagentViewBar } from './NativeChatSubagentViewBar' +import { NativeChatSubagentStatusBar } from './NativeChatSubagentStatusBar' + +const now = Date.now() + +const agents: NativeChatSubagentEntry[] = [ + { + id: 'a1', + label: 'Audit auth flow', + state: 'working', + tokens: 31_200, + startedAt: now - 42_000, + agentType: 'general-purpose', + model: 'claude-opus-5-5', + effort: 'high' + }, + { + id: 'a2', + label: 'Fix flaky login test', + state: 'completed', + tokens: 48_900, + startedAt: now - 63_000, + settledAt: now - 12_000, + model: 'gpt-5.5' + }, + { id: 'a3', label: 'Map token refresh', state: 'failed', tokens: 8_100 } +] +const entries = new Map(agents.map((agent) => [agent.id, agent])) + +function View() { + return ( +
+ {}} + /> +
+ {} }} + onBack={() => {}} + /> +
+ ) +} + +export const open = defineFixture({ + width: 640, + render: () => +}) + +export const switcher = defineFixture({ + width: 640, + render: () => , + interact: async (frame) => { + const trigger = frame.querySelector('[aria-haspopup="menu"]') + trigger?.dispatchEvent( + new PointerEvent('pointerdown', { bubbles: true, button: 0, pointerType: 'mouse' }) + ) + await new Promise((resolve) => setTimeout(resolve, 300)) + } +}) diff --git a/src/renderer/src/components/native-chat/subagents/NativeChatSubagentViewBar.tsx b/src/renderer/src/components/native-chat/subagents/NativeChatSubagentViewBar.tsx new file mode 100644 index 00000000000..c81cb5f3c5f --- /dev/null +++ b/src/renderer/src/components/native-chat/subagents/NativeChatSubagentViewBar.tsx @@ -0,0 +1,110 @@ +import { ChevronDown, ChevronLeft } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuTrigger +} from '@/components/ui/dropdown-menu' +import { useTranslate } from '@/i18n/use-translate' +import { subagentStateLabel } from '../../../../../shared/native-chat/transcript/native-chat-subagent-group-header' +import { normalizeSubagentState } from '../../../../../shared/native-chat/transcript/native-chat-subagent-summary' +import { + subagentEntryRunsOn, + subagentRoleLabel +} from '../../../../../shared/native-chat/transcript/native-chat-subagent-entry-detail' +import type { NativeChatSubagentEntry } from '../../../../../shared/native-chat/native-chat-types' +import { StatusDot } from './NativeChatSubagentRun' +import { sayNativeChatSubagentGroupTranslated as say } from './native-chat-subagent-group-words-text' +import { sayNativeChatSessionOptionTranslated as sayOption } from '../session/options/controls/native-chat-session-option-labels-text' + +const CHIP_CLASS = + 'min-w-0 shrink truncate rounded-full border border-border px-1.5 font-sans text-3xs text-chat-foreground-faint' + +/** Above a subagent's own transcript: back to the main agent, and a switcher over every subagent. */ +export function NativeChatSubagentViewBar({ + agentId, + entries, + agentsWithRows, + onOpen +}: { + agentId: string + /** Every subagent the session names, in roster order. */ + entries: ReadonlyMap + /** Subagents with rows, some of which no roster names. */ + agentsWithRows: ReadonlyMap + onOpen: (agentId: string | null) => void +}): React.JSX.Element { + const t = useTranslate() + const unnamed = t('components.native-chat.subagents.unnamed', 'Subagent') + const mainAgent = t('components.native-chat.subagents.mainAgent', 'Main agent') + const agentIds = [ + ...entries.keys(), + ...Array.from(agentsWithRows.keys()).filter((id) => !entries.has(id)) + ] + const entry = entries.get(agentId) + const state = entry ? normalizeSubagentState(entry.state) : null + const role = subagentRoleLabel(entry?.agentType) + const runsOn = entry ? subagentEntryRunsOn(entry, sayOption) : null + return ( +
+
+ + + / + + + + + + + onOpen(null)}> + + {mainAgent} + + + {agentIds.map((id) => { + const listed = entries.get(id) + const listedState = listed ? normalizeSubagentState(listed.state) : null + return ( + onOpen(id)} + > + + {listedState ? ( + + ) : null} + + {listed?.label ?? unnamed} + {listedState ? ( + + {subagentStateLabel(listedState, 1, 1, say)} + + ) : null} + + ) + })} + + + {role ? {role} : null} + {runsOn ? {runsOn} : null} +
+
+ ) +} diff --git a/src/renderer/src/components/native-chat/subagents/native-chat-open-subagent.ts b/src/renderer/src/components/native-chat/subagents/native-chat-open-subagent.ts new file mode 100644 index 00000000000..c6787d8bdb6 --- /dev/null +++ b/src/renderer/src/components/native-chat/subagents/native-chat-open-subagent.ts @@ -0,0 +1,57 @@ +// Which subagent each chat pane shows in place of its conversation; session-only, never persisted. + +import { useCallback, useSyncExternalStore } from 'react' +import { isEditableTarget } from '@/lib/text-input/focus/editable-target' + +/** The subagent a transcript shows (null: the conversation) and how its pane switches. */ +export type NativeChatSubagentView = { + agentId: string | null + open: (agentId: string | null) => void +} + +const openByPane = new Map() +const listeners = new Set<() => void>() + +function subscribe(listener: () => void): () => void { + listeners.add(listener) + return () => listeners.delete(listener) +} + +/** `paneKey` is the chat's status pane key; null returns the pane to its main agent. */ +export function openNativeChatSubagent(paneKey: string, agentId: string | null): void { + if ((openByPane.get(paneKey) ?? null) === agentId) { + return + } + if (agentId === null) { + openByPane.delete(paneKey) + } else { + openByPane.set(paneKey, agentId) + } + for (const listener of listeners) { + listener() + } +} + +export function useNativeChatOpenSubagent(paneKey: string): string | null { + const read = useCallback(() => openByPane.get(paneKey) ?? null, [paneKey]) + return useSyncExternalStore(subscribe, read, read) +} + +/** Esc outside inputs and menus takes the pane back to its main agent. */ +export function closeNativeChatSubagentOnEscape(event: React.KeyboardEvent, paneKey: string): void { + const target = event.target + if ( + event.key !== 'Escape' || + event.defaultPrevented || + !openByPane.has(paneKey) || + !(target instanceof Element) || + // Portaled menus bubble through React but sit outside this pane's DOM. + !event.currentTarget.contains(target) || + isEditableTarget(target) || + target.closest('[role="menu"], [role="dialog"], [role="listbox"]') !== null + ) { + return + } + event.preventDefault() + openNativeChatSubagent(paneKey, null) +} diff --git a/src/renderer/src/components/native-chat/subagents/native-chat-subagent-delegation.ts b/src/renderer/src/components/native-chat/subagents/native-chat-subagent-delegation.ts deleted file mode 100644 index f9c0f0cc921..00000000000 --- a/src/renderer/src/components/native-chat/subagents/native-chat-subagent-delegation.ts +++ /dev/null @@ -1,87 +0,0 @@ -// Codex delegates by the first thread id, including legacy raw frames; Claude spawn call ids change on resume, so join via the announcing roster. - -import { - codexCollabRowAgentIds, - isCodexCollabToolRowName -} from '../../../../../shared/codex-collab-agent-tools' -import { - isSubagentGroupBlock, - type NativeChatMessage -} from '../../../../../shared/native-chat/native-chat-types' - -export type NativeChatSubagentDelegation = - | { kind: 'roster'; agentIds: readonly string[] } - | { kind: 'call'; agentId: string } - | { kind: 'spawn' } - -/** Claude's subagent spawn tool, under its current and its older name. */ -const CLAUDE_SPAWN_TOOLS: ReadonlySet = new Set(['Agent', 'Task']) - -const CODEX_COLLAB_CALL_FRAME = 'item:collabAgentToolCall' - -const delegations = new WeakMap() - -/** An older journal's raw collab-call row: not drawn, but still the agent acting. */ -export function isNativeChatCodexCollabCallFrameRow(message: NativeChatMessage): boolean { - const [only] = message.blocks - return ( - message.blocks.length === 1 && - only?.type === 'text' && - only.providerFrame?.provider === 'codex' && - only.providerFrame.kind === CODEX_COLLAB_CALL_FRAME - ) -} - -export function nativeChatSubagentDelegation( - message: NativeChatMessage -): NativeChatSubagentDelegation | null { - const cached = delegations.get(message) - if (cached !== undefined) { - return cached - } - const delegation = derive(message) - delegations.set(message, delegation) - return delegation -} - -function derive(message: NativeChatMessage): NativeChatSubagentDelegation | null { - const rostered = message.blocks.flatMap((block) => - isSubagentGroupBlock(block) ? block.agents.map((agent) => agent.id) : [] - ) - if (rostered.length > 0) { - return { kind: 'roster', agentIds: rostered } - } - const [only] = message.blocks - const frame = - message.blocks.length === 1 && only?.type === 'text' ? only.providerFrame : undefined - if (frame?.provider === 'codex' && frame.kind === CODEX_COLLAB_CALL_FRAME) { - const [agentId] = frame.payload.truncated ? [] : receiverThreadIds(frame.payload.head) - return agentId === undefined ? null : { kind: 'call', agentId } - } - // A tool run folds into the message before it, so its last call is the newest thing in it. - const newest = message.blocks.findLast((block) => block.type !== 'tool-result') - if (newest?.type !== 'tool-call') { - return null - } - if (isCodexCollabToolRowName(newest.name)) { - const [agentId] = codexCollabRowAgentIds(newest.input) - return agentId === undefined ? null : { kind: 'call', agentId } - } - return CLAUDE_SPAWN_TOOLS.has(newest.name) ? { kind: 'spawn' } : null -} - -function receiverThreadIds(head: string): readonly string[] { - let item: unknown - try { - item = JSON.parse(head) - } catch { - return [] - } - if (typeof item !== 'object' || item === null || !('receiverThreadIds' in item)) { - return [] - } - const ids = item.receiverThreadIds - return Array.isArray(ids) - ? ids.filter((id): id is string => typeof id === 'string' && id.length > 0) - : [] -} diff --git a/src/renderer/src/components/native-chat/subagents/native-chat-subagent-handoff-copy-budget.test.ts b/src/renderer/src/components/native-chat/subagents/native-chat-subagent-handoff-copy-budget.test.ts deleted file mode 100644 index d2b4d8daad6..00000000000 --- a/src/renderer/src/components/native-chat/subagents/native-chat-subagent-handoff-copy-budget.test.ts +++ /dev/null @@ -1,137 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { NativeChatMessage } from '../../../../../shared/native-chat/native-chat-types' -import { nativeChatSubagentSections } from './native-chat-subagent-sections' -import { nativeChatSubagentLiveSections } from './native-chat-subagent-live-frontier' - -function message( - id: string, - blocks: NativeChatMessage['blocks'], - sequence: number, - extra: Partial = {} -): NativeChatMessage { - return { - id, - role: 'assistant', - blocks, - timestamp: 1, - source: 'transcript', - journalPosition: { sequence, index: 0 }, - ...extra - } -} - -function handoff(index: number, agents = ['child']): NativeChatMessage { - return message( - `handoff-${index}`, - [ - { - type: 'tool-call', - name: 'wait_agent', - input: { - agents, - future: { reason: 'observe', unicode: '🙂' }, - optional: undefined - } - } - ], - index + 10 - ) -} - -function fixture(calls: readonly NativeChatMessage[]) { - const roster = message( - 'root-roster', - [ - { - type: 'subagent-group', - groupId: 'root', - agents: [{ id: 'parent', label: 'parent', state: 'working' }] - } - ], - 1, - { role: 'system' } - ) - const parent = message('parent-row', [{ type: 'text', text: 'delegating' }], 2, { - agentId: 'parent', - producerKind: 'agent' - }) - const child = message('child-row', [{ type: 'text', text: 'reading' }], 3, { - agentId: 'child', - parentAgentId: 'parent', - producerKind: 'agent' - }) - const conversation = [roster, ...calls] - const sections = nativeChatSubagentSections( - conversation, - new Map([ - ['parent', [{ message: parent, turnKey: undefined }]], - ['child', [{ message: child, turnKey: undefined }]] - ]) - ) - return { conversation, sections, roster, parent, child } -} - -describe('nested subagent handoff accumulation', () => { - it.each([{ agents: [] }, { agents: [''] }, { agents: ['unknown'] }])( - 'keeps unknown or empty target behavior for %j', - ({ agents }) => { - const input = fixture([handoff(0), handoff(1, agents)]) - const before = structuredClone(input) - expect([...nativeChatSubagentLiveSections(input.conversation, input.sections, true)]).toEqual( - ['child'] - ) - expect(input).toEqual(before) - } - ) - - it('keeps live ordering for interleaved handoffs to different nested scopes', () => { - const input = fixture([handoff(0), handoff(1, ['other-child']), handoff(2)]) - const group = input.roster.blocks[0] - if (group?.type !== 'subagent-group') { - throw new Error('Missing root roster') - } - group.agents.push({ id: 'other-parent', label: 'other parent', state: 'working' }) - const otherParent = message('other-parent-row', [{ type: 'text', text: 'delegating' }], 4, { - agentId: 'other-parent', - producerKind: 'agent' - }) - const otherChild = message('other-child-row', [{ type: 'text', text: 'reading' }], 5, { - agentId: 'other-child', - parentAgentId: 'other-parent', - producerKind: 'agent' - }) - const sections = nativeChatSubagentSections( - input.conversation, - new Map([ - ['parent', [{ message: input.parent, turnKey: undefined }]], - ['child', [{ message: input.child, turnKey: undefined }]], - ['other-parent', [{ message: otherParent, turnKey: undefined }]], - ['other-child', [{ message: otherChild, turnKey: undefined }]] - ]) - ) - const before = structuredClone({ input, sections }) - expect([...nativeChatSubagentLiveSections(input.conversation, sections, true)]).toEqual([ - 'other-parent', - 'child', - 'other-child' - ]) - expect({ input, sections }).toEqual(before) - }) - - it('derives fresh results on interleaved sessions with identical IDs and no carried handoffs', () => { - const waiting = fixture([handoff(0)]) - const plain = fixture([]) - expect([ - ...nativeChatSubagentLiveSections(waiting.conversation, waiting.sections, true) - ]).toEqual(['parent', 'child']) - expect([...nativeChatSubagentLiveSections(plain.conversation, plain.sections, true)]).toEqual([ - 'parent' - ]) - expect([ - ...nativeChatSubagentLiveSections(waiting.conversation, waiting.sections, true) - ]).toEqual(['parent', 'child']) - expect(nativeChatSubagentLiveSections(waiting.conversation, waiting.sections, false)).toBe( - nativeChatSubagentLiveSections(plain.conversation, plain.sections, false) - ) - }) -}) diff --git a/src/renderer/src/components/native-chat/subagents/native-chat-subagent-history.ts b/src/renderer/src/components/native-chat/subagents/native-chat-subagent-history.ts new file mode 100644 index 00000000000..fb879746f89 --- /dev/null +++ b/src/renderer/src/components/native-chat/subagents/native-chat-subagent-history.ts @@ -0,0 +1,46 @@ +import type { StructuredAgentSubagentRoster } from '../../../../../shared/agent-session/view/structured-agent-session-subagent-roster' +import { + isSubagentGroupBlock, + type NativeChatMessage +} from '../../../../../shared/native-chat/native-chat-types' +import type { NativeChatSubagentRow } from '../../../../../shared/native-chat/transcript/native-chat-transcript-projection' + +function namesAgent(message: NativeChatMessage, agentId: string): boolean { + return message.blocks.some( + (block) => isSubagentGroupBlock(block) && block.agents.some(({ id }) => id === agentId) + ) +} + +/** + * Whether a subagent's view holds all its work: its spawning roster row is loaded ('landed'), older + * history still holds it ('page'), or nothing loadable does ('stop'). Scanned per open, not per frame. + */ +export function nativeChatSubagentHistoryStep({ + agentId, + conversation, + subagentRows, + roster, + historyFloor +}: { + agentId: string + conversation: readonly NativeChatMessage[] + subagentRows: ReadonlyMap + roster: StructuredAgentSubagentRoster | undefined + /** The sequence the transcript's history starts from (its latest `/clear`); 0 for none. */ + historyFloor: () => number +}): 'landed' | 'page' | 'stop' { + if ( + conversation.some((message) => namesAgent(message, agentId)) || + Array.from(subagentRows.values()).some((rows) => + rows.some(({ message }) => namesAgent(message, agentId)) + ) + ) { + return 'landed' + } + const named = roster?.get(agentId) + if (named === undefined) { + return 'stop' + } + // A spawn before the latest /clear is outside this conversation: no page reaches it. + return named.rosterPosition.sequence < historyFloor() ? 'stop' : 'page' +} diff --git a/src/renderer/src/components/native-chat/subagents/native-chat-subagent-live-frontier.ts b/src/renderer/src/components/native-chat/subagents/native-chat-subagent-live-frontier.ts deleted file mode 100644 index 2fc64b906a9..00000000000 --- a/src/renderer/src/components/native-chat/subagents/native-chat-subagent-live-frontier.ts +++ /dev/null @@ -1,169 +0,0 @@ -// Open the newest delegation’s section while its scope runs; newer output supersedes it, and explicit reader choices win. - -import { compareAgentJournalPositions } from '../../../../../shared/agent-session/journal/agent-session-journal-position' -import type { AgentJournalPosition } from '../../../../../shared/agent-session/journal/agent-session-journal-types' -import { normalizeSubagentState } from '../../../../../shared/native-chat/transcript/native-chat-subagent-summary' -import { nativeChatRowRendersContent } from '../../../../../shared/native-chat/transcript/native-chat-row-content' -import type { NativeChatMessage } from '../../../../../shared/native-chat/native-chat-types' -import { compareNativeChatDisplayMessages as compareMessages } from '../../../../../shared/native-chat/transcript/native-chat-message-order' -import { - isNativeChatCodexCollabCallFrameRow, - nativeChatSubagentDelegation -} from './native-chat-subagent-delegation' -import type { NativeChatSubagentSections } from './native-chat-subagent-sections' - -const NONE: ReadonlySet = new Set() - -/** A row the reader sees the scope's agent produce, or a collab call it made. */ -function isOutput(message: NativeChatMessage): boolean { - return ( - message.role !== 'user' && - (nativeChatRowRendersContent(message.blocks) || isNativeChatCodexCollabCallFrameRow(message)) - ) -} - -/** `scopeActive`: the session is running. */ -export function nativeChatSubagentLiveSections( - conversation: readonly NativeChatMessage[], - sections: NativeChatSubagentSections, - scopeActive: boolean -): ReadonlySet { - if (!scopeActive || sections.rows.size === 0) { - return NONE - } - // Each sectioned agent's scope: null for the session's, else the subagent that spawned it. - const scopeOf = new Map() - for (const agentIds of sections.anchoredAt.values()) { - agentIds.forEach((agentId) => scopeOf.set(agentId, null)) - } - for (const [scope, agentIds] of sections.openAt) { - agentIds.forEach((agentId) => scopeOf.set(agentId, scope)) - } - const handedDown = handDownNestedDelegations(conversation, scopeOf) - const live = new Set() - const visit = (scopeRows: readonly NativeChatMessage[], scope: string | null): void => { - const members = - scope === null - ? [...Array.from(sections.anchoredAt.values()).flat(), ...(sections.openAt.get(null) ?? [])] - : (sections.openAt.get(scope) ?? []) - const inScope = new Set(members) - const belongsHere = (agentId: string): boolean => - !scopeOf.has(agentId) || scopeOf.get(agentId) === scope - const atFrontier = (): readonly string[] => { - for (const row of newestFirst(scopeRows)) { - if (!isOutput(row) || (scope === null && handedDown.rowIds.has(row.id))) { - continue - } - const delegation = nativeChatSubagentDelegation(row) - if (delegation?.kind === 'spawn') { - continue - } - if (delegation === null) { - return [] - } - if (delegation.kind === 'call') { - return inScope.has(delegation.agentId) ? [delegation.agentId] : [] - } - const newest = delegation.agentIds.findLast(belongsHere) - return newest !== undefined && inScope.has(newest) ? [newest] : [] - } - // Nothing loaded since the newest roster naming this scope's agents. - const rostered = members.filter((agentId) => sections.rosters.has(agentId)) - const newest = rostered.reduce( - (best, agentId) => - best === undefined || compareAddedAt(sections, agentId, best) > 0 ? agentId : best, - undefined - ) - return newest === undefined ? [] : [newest] - } - atFrontier().forEach((agentId) => live.add(agentId)) - for (const agentId of members) { - const entry = sections.entries.get(agentId) - if (entry !== undefined && normalizeSubagentState(entry.state) === 'working') { - const own = (sections.rows.get(agentId) ?? []).map((row) => row.message) - const extra = handedDown.byScope.get(agentId) - visit(extra ? [...own, ...extra].sort(compareMessages) : own, agentId) - } - } - } - visit(conversation, null) - return live -} - -/** Use each folded run’s newest part, not its drawn position above later rosters; runs fold only into the latest assistant row. */ -function* newestFirst(rows: readonly NativeChatMessage[]): Generator { - let below: NativeChatMessage[] = [] - for (let index = rows.length - 1; index >= 0; index -= 1) { - const row = rows[index]! - if (row.role !== 'assistant') { - below.push(row) - continue - } - const newest = row.foldedJournalPosition ?? row.journalPosition - let next = 0 - while (next < below.length && (newest === undefined || isNewerThan(below[next]!, newest))) { - yield below[next]! - next += 1 - } - yield row - yield* below.slice(next) - below = [] - } - yield* below -} - -/** A row the journal does not hold yet is newer than any it does. */ -function isNewerThan(row: NativeChatMessage, position: AgentJournalPosition): boolean { - return ( - row.journalPosition === undefined || - compareAgentJournalPositions(row.journalPosition, position) > 0 - ) -} - -/** The session's roster rows and calls whose agents one subagent spawned, by that subagent. */ -function handDownNestedDelegations( - conversation: readonly NativeChatMessage[], - scopeOf: ReadonlyMap -): { rowIds: ReadonlySet; byScope: ReadonlyMap } { - const rowIds = new Set() - const byScope = new Map() - if (!Array.from(scopeOf.values()).some((scope) => scope !== null)) { - return { rowIds, byScope } - } - for (const message of conversation) { - const delegation = nativeChatSubagentDelegation(message) - if (delegation === null || delegation.kind === 'spawn') { - continue - } - const agentIds = delegation.kind === 'call' ? [delegation.agentId] : delegation.agentIds - const spawners = new Set( - agentIds.flatMap((agentId) => (scopeOf.has(agentId) ? [scopeOf.get(agentId) ?? null] : [])) - ) - const [spawner] = spawners - if (spawners.size === 1 && spawner !== undefined && spawner !== null) { - rowIds.add(message.id) - const rows = byScope.get(spawner) - if (rows) { - rows.push(message) - } else { - byScope.set(spawner, [message]) - } - } - } - return { rowIds, byScope } -} - -/** Later roster first; within one roster, the agent whose rows began later. */ -function compareAddedAt(sections: NativeChatSubagentSections, a: string, b: string): number { - const at = (agentId: string) => sections.rosters.get(agentId)?.position - const [rosterA, rosterB] = [at(a), at(b)] - if (rosterA !== undefined && rosterB !== undefined) { - const byRoster = compareAgentJournalPositions(rosterA, rosterB) - if (byRoster !== 0) { - return byRoster - } - } else if (rosterA !== rosterB) { - return rosterA === undefined ? -1 : 1 - } - return compareMessages(sections.rows.get(a)![0]!.message, sections.rows.get(b)![0]!.message) -} diff --git a/src/renderer/src/components/native-chat/subagents/native-chat-subagent-reveal.ts b/src/renderer/src/components/native-chat/subagents/native-chat-subagent-reveal.ts deleted file mode 100644 index 27a2dd7cc58..00000000000 --- a/src/renderer/src/components/native-chat/subagents/native-chat-subagent-reveal.ts +++ /dev/null @@ -1,142 +0,0 @@ -// Reveal a subagent named from outside the transcript (the agents strip): open what holds it, then land on its newest drawn activity, else its head or entry. - -import { useLayoutEffect, useRef } from 'react' -import type { StructuredAgentSubagentRoster } from '../../../../../shared/agent-session/view/structured-agent-session-subagent-roster' -import { - isSubagentGroupBlock, - type NativeChatMessage -} from '../../../../../shared/native-chat/native-chat-types' -import type { NativeChatSubagentSections } from './native-chat-subagent-sections' -import { nativeChatSlotIndexOf } from '../conversation/slots/native-chat-transcript-slot-selection' -import type { NativeChatTranscriptSlot } from '../conversation/slots/native-chat-transcript-slots' -import type { NativeChatAlignEdge } from '../viewport/virtualization/use-native-chat-viewport-align' - -/** - * The drawn "Kicked off" row first naming an agent. Siblings' roster items fold into the first - * sibling's row, so an agent's own roster item id can name a row that is never drawn. - * Scanned only on a reveal, never per frame. - */ -function rosterRowNaming( - conversation: readonly NativeChatMessage[], - agentId: string -): string | undefined { - return conversation.find((message) => - message.blocks.some( - (block) => isSubagentGroupBlock(block) && block.agents.some(({ id }) => id === agentId) - ) - )?.id -} - -/** Where a subagent is in the committed transcript, and what opening it takes. */ -export type NativeChatSubagentPlace = - | { kind: 'open'; agentIds: readonly string[]; rosterRowId?: string } - | { kind: 'page' } - | { kind: 'stop' } - -export function nativeChatSubagentPlace({ - agentId, - conversation, - sections, - roster, - slots, - historyFloor -}: { - agentId: string - conversation: readonly NativeChatMessage[] - sections: NativeChatSubagentSections - roster: StructuredAgentSubagentRoster | undefined - slots: readonly NativeChatTranscriptSlot[] - /** The sequence the transcript's history starts from (its latest `/clear`); 0 for none. Read only when nothing loaded names the agent. */ - historyFloor: () => number -}): NativeChatSubagentPlace { - const first = sections.rows.get(agentId)?.[0] - if (first !== undefined) { - // Nested sections open from the outermost, which also opens the roster anchoring it. - return { kind: 'open', agentIds: sections.pathOf.get(first.message.id) ?? [agentId] } - } - // No activity yet (just spawned, or an agent that reports only its final reply): its roster entry. - const rosterRowId = rosterRowNaming(conversation, agentId) - if (rosterRowId !== undefined && nativeChatSlotIndexOf(slots, rosterRowId) !== -1) { - return { kind: 'open', agentIds: [agentId], rosterRowId } - } - const named = roster?.get(agentId) - if (named === undefined) { - return { kind: 'stop' } - } - // A spawn before the latest /clear is outside this conversation: no page reaches it. - return named.rosterPosition.sequence < historyFloor() ? { kind: 'stop' } : { kind: 'page' } -} - -export type NativeChatSubagentLanding = { - index: number - edge: NativeChatAlignEdge - /** Set when the landing is the agent's entry inside a roster slot rather than a slot of its own. */ - entryId?: string -} - -/** Newest drawn activity (streaming stubs draw nothing), else the section head, else the roster entry. */ -export function nativeChatSubagentLanding( - slots: readonly NativeChatTranscriptSlot[], - conversation: readonly NativeChatMessage[], - sections: NativeChatSubagentSections, - agentId: string -): NativeChatSubagentLanding | null { - const rowIds = new Set(sections.rows.get(agentId)?.map(({ message }) => message.id)) - const activity = slots.findLastIndex( - (slot) => - slot.kind === 'message' && - (rowIds.has(slot.message.id) || slot.workRun?.some(({ id }) => rowIds.has(id)) === true) - ) - if (activity !== -1) { - return { index: activity, edge: 'end' } - } - const head = slots.findIndex((slot) => slot.kind === 'subagent' && slot.agentId === agentId) - if (head !== -1) { - return { index: head, edge: 'start' } - } - const entries = slots.findIndex( - (slot) => slot.kind === 'subagent-entries' && slot.agents.some(({ id }) => id === agentId) - ) - const rosterRowId = sections.rosters.get(agentId)?.rowId ?? rosterRowNaming(conversation, agentId) - const index = entries !== -1 ? entries : nativeChatSlotIndexOf(slots, rosterRowId) - return index >= 0 ? { index, edge: 'start', entryId: agentId } : null -} - -/** Land once per request: the row's end for activity, or the entry when the row's start would leave it below the view. */ -export function useNativeChatSubagentLanding({ - request, - landing, - scrollRef, - scrollMessageToTop, - release -}: { - request: { requestId: number } | null - landing: NativeChatSubagentLanding | null - scrollRef: React.RefObject - scrollMessageToTop: (element: HTMLElement, edge?: NativeChatAlignEdge) => void - release: (request: null) => void -}): void { - const servicedRef = useRef(0) - useLayoutEffect(() => { - if (request === null || servicedRef.current === request.requestId) { - return - } - servicedRef.current = request.requestId - const scroller = scrollRef.current - const row = - landing === null - ? null - : scroller?.querySelector(`[data-index="${landing.index}"]`) - if (scroller && landing && row) { - const entry = Array.from( - row.querySelectorAll('[data-native-chat-subagent-entry]') - ).find((element) => element.dataset.nativeChatSubagentEntry === landing.entryId) - const entryBelowView = - entry !== undefined && - entry.getBoundingClientRect().bottom - row.getBoundingClientRect().top > - scroller.clientHeight - scrollMessageToTop(entryBelowView ? entry : row, entryBelowView ? 'start' : landing.edge) - } - release(null) - }, [landing, release, request, scrollMessageToTop, scrollRef]) -} diff --git a/src/renderer/src/components/native-chat/subagents/native-chat-subagent-scope.ts b/src/renderer/src/components/native-chat/subagents/native-chat-subagent-scope.ts new file mode 100644 index 00000000000..eb910670bdd --- /dev/null +++ b/src/renderer/src/components/native-chat/subagents/native-chat-subagent-scope.ts @@ -0,0 +1,133 @@ +// A transcript shows one scope: the conversation, or one subagent's own rows. Subagents open in their own view, never inline. + +import { compareAgentJournalPositions } from '../../../../../shared/agent-session/journal/agent-session-journal-position' +import type { StructuredAgentSubagentRoster } from '../../../../../shared/agent-session/view/structured-agent-session-subagent-roster' +import { + isSubagentGroupBlock, + type NativeChatMessage, + type NativeChatSubagentEntry +} from '../../../../../shared/native-chat/native-chat-types' +import type { NativeChatSubagentRow } from '../../../../../shared/native-chat/transcript/native-chat-transcript-projection' +import { compareNativeChatDisplayMessages as compareMessages } from '../../../../../shared/native-chat/transcript/native-chat-message-order' + +const NO_HEADS: readonly NativeChatSubagentHead[] = [] + +/** A subagent no roster row in its scope names: it opens from a head at its first row. */ +export type NativeChatSubagentHead = { + agentId: string + entry: NativeChatSubagentEntry | undefined + first: NativeChatSubagentRow +} + +function* rosterAgents(rows: readonly NativeChatMessage[]): Generator { + for (const message of rows) { + for (const block of message.blocks) { + if (isSubagentGroupBlock(block)) { + yield* block.agents + } + } + } +} + +/** Every subagent the session names, oldest roster first: a loaded roster's entry, else the client's. */ +export function nativeChatSubagentEntries( + conversation: readonly NativeChatMessage[], + subagentRows: ReadonlyMap, + roster?: StructuredAgentSubagentRoster +): ReadonlyMap { + const loaded = new Map() + const take = (rows: readonly NativeChatMessage[]): void => { + for (const agent of rosterAgents(rows)) { + if (!loaded.has(agent.id)) { + loaded.set(agent.id, agent) + } + } + } + take(conversation) + for (const rows of subagentRows.values()) { + take(rows.map(({ message }) => message)) + } + const position = (agentId: string) => roster?.get(agentId)?.rosterPosition + const ids = Array.from(new Set([...(roster?.keys() ?? []), ...loaded.keys()])).sort((a, b) => { + const [left, right] = [position(a), position(b)] + return left && right ? compareAgentJournalPositions(left, right) : left ? -1 : right ? 1 : 0 + }) + return new Map( + ids.map((agentId) => [agentId, loaded.get(agentId) ?? roster!.get(agentId)!.entry]) + ) +} + +/** The subagent that spawned this one, when its rows are loaded; null for the session's own agent. */ +function spawnerOf( + agentId: string, + subagentRows: ReadonlyMap +): string | null { + const parent = subagentRows.get(agentId)?.[0]?.message.parentAgentId + return parent !== undefined && parent !== agentId && subagentRows.has(parent) ? parent : null +} + +/** Subagents the scope's agent (null: the session's) spawned that no roster row in `scopeRows` names. */ +export function nativeChatSubagentHeads( + scopeRows: readonly NativeChatMessage[], + subagentRows: ReadonlyMap, + entries: ReadonlyMap, + scopeAgentId: string | null +): readonly NativeChatSubagentHead[] { + if (subagentRows.size === 0) { + return NO_HEADS + } + const named = new Set(Array.from(rosterAgents(scopeRows), ({ id }) => id)) + const heads: NativeChatSubagentHead[] = [] + for (const [agentId, rows] of subagentRows) { + const first = rows[0] + if ( + first !== undefined && + !named.has(agentId) && + agentId !== scopeAgentId && + spawnerOf(agentId, subagentRows) === scopeAgentId + ) { + heads.push({ agentId, entry: entries.get(agentId), first }) + } + } + return heads.sort((a, b) => compareMessages(a.first.message, b.first.message)) +} + +/** Sort child rows separately so parent-only streaming updates reuse their order. */ +export function nativeChatSubagentRowsInOrder( + subagentRows: ReadonlyMap +): readonly NativeChatSubagentRow[] { + return Array.from(subagentRows.values()) + .flat() + .sort((a, b) => compareMessages(a.message, b.message)) +} + +/** Merge parent and child rows in transcript order so child edits remain in their actual turns. */ +export function nativeChatRowsInTranscriptOrder( + messages: readonly NativeChatMessage[], + turnKeys: readonly (string | undefined)[], + subagentRows: readonly NativeChatSubagentRow[] +): { messages: readonly NativeChatMessage[]; turnKeys: readonly (string | undefined)[] } { + if (subagentRows.length === 0) { + return { messages, turnKeys } + } + const merged: NativeChatMessage[] = [] + const mergedTurnKeys: (string | undefined)[] = [] + let next = 0 + for (const [index, message] of messages.entries()) { + while ( + next < subagentRows.length && + compareMessages(subagentRows[next]!.message, message) < 0 + ) { + merged.push(subagentRows[next]!.message) + mergedTurnKeys.push(subagentRows[next]!.turnKey) + next += 1 + } + merged.push(message) + mergedTurnKeys.push(turnKeys[index]) + } + for (const row of subagentRows.slice(next)) { + merged.push(row.message) + mergedTurnKeys.push(row.turnKey) + } + return { messages: merged, turnKeys: mergedTurnKeys } +} diff --git a/src/renderer/src/components/native-chat/subagents/native-chat-subagent-section-slots.ts b/src/renderer/src/components/native-chat/subagents/native-chat-subagent-section-slots.ts deleted file mode 100644 index 3168299ff4f..00000000000 --- a/src/renderer/src/components/native-chat/subagents/native-chat-subagent-section-slots.ts +++ /dev/null @@ -1,201 +0,0 @@ -import type { - NativeChatMessage, - NativeChatSubagentEntry -} from '../../../../../shared/native-chat/native-chat-types' -import { - normalizeSubagentState, - subagentGroupBlocks -} from '../../../../../shared/native-chat/transcript/native-chat-subagent-summary' -import { nativeChatRowRendersContent } from '../../../../../shared/native-chat/transcript/native-chat-row-content' -import { - type NativeChatRowTypography, - estimateNativeChatRowHeight, - nativeChatRowContentMetrics, - NATIVE_CHAT_SUBAGENT_SECTION_HEAD_PX -} from '../viewport/virtualization/native-chat-row-height-estimate' -import type { NativeChatResolvedPrompt } from '../../../../../shared/native-chat/native-chat-resolution-receipt' -import { compareNativeChatDisplayMessages as compareMessages } from '../../../../../shared/native-chat/transcript/native-chat-message-order' -import { - nativeChatSubagentEntryRuns, - type NativeChatSubagentChoices, - type NativeChatSubagentRosterState, - type NativeChatSubagentSections -} from './native-chat-subagent-sections' -import { - nativeChatRowRendersProse, - nativeChatRowSpeaksOrActs -} from '../../../../../shared/native-chat/native-chat-trailing-run' -import type { NativeChatTranscriptSlot } from '../conversation/slots/native-chat-transcript-slots' - -/** The head of a section no loaded roster row holds: it names whose rows follow it. */ -export type NativeChatSubagentSectionSlot = { - kind: 'subagent' - agentId: string - /** The conversation turn this head sits in, so the outline rail can place it. */ - turnKey: string | undefined - /** The roster's entry for the agent; absent when no loaded roster names it. */ - entry: NativeChatSubagentEntry | undefined - expanded: boolean - /** Sections this head sits inside; 0 is the conversation. */ - depth: number - estimatedHeight: number -} - -/** A roster row's entries after an open child's rows, through the next open one. */ -export type NativeChatSubagentEntriesSlot = { - kind: 'subagent-entries' - rosterRowId: string - agents: readonly NativeChatSubagentEntry[] - sections: ReadonlyMap - turnKey: string | undefined - depth: number - estimatedHeight: number -} - -/** Place children under loaded roster entries or their first rows; live-frontier defaults yield to reader section/list choices. */ -export function nativeChatSubagentSectionSlots({ - sections, - choices, - live, - receipts, - slots, - typography -}: { - sections: NativeChatSubagentSections - choices: NativeChatSubagentChoices - live: ReadonlySet - receipts: ReadonlyMap - slots: NativeChatTranscriptSlot[] - typography?: NativeChatRowTypography -}) { - const isOpen = (agentId: string): boolean => choices.sections.get(agentId) ?? live.has(agentId) - const pushHead = (agentId: string, depth: number, turnKey: string | undefined): void => { - slots.push({ - kind: 'subagent', - agentId, - turnKey, - entry: sections.entries.get(agentId), - expanded: isOpen(agentId), - depth, - estimatedHeight: NATIVE_CHAT_SUBAGENT_SECTION_HEAD_PX - }) - } - /** Use the section’s displayed turn for all child rows so the outline rail tracks reader position. */ - const pushRows = (agentId: string, depth: number, turnKey: string | undefined): void => { - const rows = sections.rows.get(agentId) ?? [] - const entry = sections.entries.get(agentId) - const working = entry !== undefined && normalizeSubagentState(entry.state) === 'working' - const trailing = rows.findLastIndex((row) => - nativeChatRowSpeaksOrActs(row.message, nativeChatRowRendersProse(row.message), receipts) - ) - const pending = [...(sections.openAt.get(agentId) ?? [])] - for (const [index, { message }] of rows.entries()) { - openBefore(pending, message, depth, { turnKey }) - const receipt = receipts.get(message.id) - if (receipt === undefined && !nativeChatRowRendersContent(message.blocks)) { - continue - } - slots.push({ - kind: 'message', - message, - turnKey, - activeTurnIsWorking: working, - trailingRun: index === trailing, - receipt, - status: undefined, - folded: false, - drawsMessage: true, - turnFolds: false, - turnDiff: undefined, - subagentRoster: undefined, - depth, - estimatedHeight: estimateNativeChatRowHeight( - nativeChatRowContentMetrics(message, typography), - { - hasReceipt: receipt !== undefined, - hasStatus: false, - hasTurnDiff: false, - inSubagentSection: true - }, - typography - ) - }) - } - openBefore(pending, undefined, depth, { turnKey }) - } - /** Emit heads before the next message; undefined flushes all. Nested sections inherit their enclosing turn. */ - function openBefore( - pending: string[], - message: NativeChatMessage | undefined, - depth: number, - section?: { turnKey: string | undefined } - ) { - while (pending.length > 0) { - const agentId = pending[0]! - const first = sections.rows.get(agentId)?.[0] - if ( - message !== undefined && - first !== undefined && - compareMessages(first.message, message) >= 0 - ) { - return - } - pending.shift() - const turnKey = section ? section.turnKey : first?.turnKey - pushHead(agentId, depth, turnKey) - if (isOpen(agentId)) { - pushRows(agentId, depth + 1, turnKey) - } - } - } - return { - openBefore, - /** Each open child's rows under its entry, then the entries up to the next open one. */ - openAnchoredAt( - message: NativeChatMessage, - roster: NativeChatSubagentRosterState | undefined, - turnKey: string | undefined - ): void { - // No child has rows yet (a reveal before first activity): the roster row draws every entry. - if (!roster?.open || roster.sections.size === 0) { - return - } - for (const group of subagentGroupBlocks(message.blocks)) { - let opened: string | undefined - for (const agents of nativeChatSubagentEntryRuns(group.agents, roster.sections)) { - if (opened !== undefined) { - pushRows(opened, 1, turnKey) - if (agents.length > 0) { - slots.push({ - kind: 'subagent-entries', - rosterRowId: message.id, - agents, - sections: roster.sections, - turnKey, - depth: 0, - estimatedHeight: agents.length * NATIVE_CHAT_SUBAGENT_SECTION_HEAD_PX - }) - } - } - opened = agents.at(-1)?.id - } - } - }, - rosterAt(messageId: string): NativeChatSubagentRosterState | undefined { - const anchored = sections.anchoredAt.get(messageId) - if (anchored === undefined) { - // A roster whose children have no rows yet still holds an open it was given (a strip reveal). - const chosen = choices.rosters.get(messageId) - return chosen === undefined ? undefined : { open: chosen, sections: NO_ROSTER_SECTIONS } - } - return { - open: - choices.rosters.get(messageId) ?? - anchored.some((agentId) => choices.sections.has(agentId) || live.has(agentId)), - sections: new Map(anchored.map((agentId) => [agentId, isOpen(agentId)])) - } - } - } -} - -const NO_ROSTER_SECTIONS: ReadonlyMap = new Map() diff --git a/src/renderer/src/components/native-chat/subagents/native-chat-subagent-sections.ts b/src/renderer/src/components/native-chat/subagents/native-chat-subagent-sections.ts deleted file mode 100644 index f260e3688ba..00000000000 --- a/src/renderer/src/components/native-chat/subagents/native-chat-subagent-sections.ts +++ /dev/null @@ -1,216 +0,0 @@ -// Retained roster metadata names windowed-out spawns; place children under loaded roster entries, their parent section or their first conversation row. - -import type { AgentJournalPosition } from '../../../../../shared/agent-session/journal/agent-session-journal-types' -import { - isSubagentGroupBlock, - type NativeChatMessage, - type NativeChatSubagentEntry -} from '../../../../../shared/native-chat/native-chat-types' -import type { NativeChatSubagentRow } from '../../../../../shared/native-chat/transcript/native-chat-transcript-projection' -import type { StructuredAgentSubagentRoster } from '../../../../../shared/agent-session/view/structured-agent-session-subagent-roster' -import { compareNativeChatDisplayMessages as compareMessages } from '../../../../../shared/native-chat/transcript/native-chat-message-order' - -export type NativeChatSubagentRosterPlace = { - rowId: string - position: AgentJournalPosition | undefined -} - -export type NativeChatSubagentSections = { - rows: ReadonlyMap - /** The entry of the first roster naming each subagent: a loaded one, else the client's. */ - entries: ReadonlyMap - rosters: ReadonlyMap - /** Roster row id → the subagents whose sections open under it, in roster order. */ - anchoredAt: ReadonlyMap - /** Unanchored sections by enclosing agent (null for conversation), ordered by first row. */ - openAt: ReadonlyMap - /** Row id → the sections enclosing it, outermost first. */ - pathOf: ReadonlyMap -} - -/** Explicit reader choices override defaults; closed roster lists hide their child sections. */ -export type NativeChatSubagentChoices = { - sections: ReadonlyMap - rosters: ReadonlyMap -} - -export const NO_NATIVE_CHAT_SUBAGENT_CHOICES: NativeChatSubagentChoices = { - sections: new Map(), - rosters: new Map() -} - -/** An open child’s rows follow its roster entry. */ -export type NativeChatSubagentRosterState = { - open: boolean - sections: ReadonlyMap -} - -/** Break roster entries after each open child; later entry runs follow that child’s rows. */ -export function nativeChatSubagentEntryRuns( - agents: readonly NativeChatSubagentEntry[], - sections: ReadonlyMap -): NativeChatSubagentEntry[][] { - let run: NativeChatSubagentEntry[] = [] - const runs = [run] - for (const agent of agents) { - run.push(agent) - if (sections.get(agent.id) === true) { - run = [] - runs.push(run) - } - } - return runs -} - -export type NativeChatSubagentDisclosure = { - setSectionOpen: (agentId: string, open: boolean) => void - setRosterOpen: (rosterRowId: string, open: boolean) => void -} - -export const NO_NATIVE_CHAT_SUBAGENT_SECTIONS: NativeChatSubagentSections = { - rows: new Map(), - entries: new Map(), - rosters: new Map(), - anchoredAt: new Map(), - openAt: new Map(), - pathOf: new Map() -} - -export function nativeChatSubagentSections( - conversation: readonly NativeChatMessage[], - subagentRows: ReadonlyMap, - roster?: StructuredAgentSubagentRoster -): NativeChatSubagentSections { - const rows = new Map(Array.from(subagentRows).filter(([, agentRows]) => agentRows.length > 0)) - if (rows.size === 0) { - return NO_NATIVE_CHAT_SUBAGENT_SECTIONS - } - const entries = new Map() - const rosters = new Map() - for (const message of conversation) { - for (const block of message.blocks) { - if (!isSubagentGroupBlock(block)) { - continue - } - for (const agent of block.agents) { - if (!entries.has(agent.id) && rows.has(agent.id)) { - entries.set(agent.id, agent) - rosters.set(agent.id, { rowId: message.id, position: message.journalPosition }) - } - } - } - } - // Loaded rosters anchor their sections; the client's names the rest. - const anchored = new Set(rosters.keys()) - for (const agentId of rows.keys()) { - const named = anchored.has(agentId) ? undefined : roster?.get(agentId) - if (named !== undefined) { - entries.set(agentId, named.entry) - rosters.set(agentId, { rowId: named.rosterItemId, position: named.rosterPosition }) - } - } - const firstRow = (agentId: string): NativeChatMessage => rows.get(agentId)![0]!.message - const spawnerOf = (agentId: string): string | null => { - const parent = firstRow(agentId).parentAgentId - return parent !== undefined && parent !== agentId && rows.has(parent) ? parent : null - } - // A chain of spawners that loops back has no outside to open in. - const scopeOf = (agentId: string): string | null => { - const spawner = spawnerOf(agentId) - const seen = new Set([agentId]) - for (let current = spawner; current !== null; current = spawnerOf(current)) { - if (seen.has(current)) { - return null - } - seen.add(current) - } - return spawner - } - const scopes = new Map() - const openAt = new Map() - for (const agentId of rows.keys()) { - const scope = scopeOf(agentId) - scopes.set(agentId, scope) - if (scope !== null || !anchored.has(agentId)) { - const inScope = openAt.get(scope) - if (inScope) { - inScope.push(agentId) - } else { - openAt.set(scope, [agentId]) - } - } - } - for (const inScope of openAt.values()) { - inScope.sort((a, b) => compareMessages(firstRow(a), firstRow(b))) - } - const anchoredAt = new Map() - for (const [agentId, { rowId }] of rosters) { - if (anchored.has(agentId) && scopes.get(agentId) === null) { - const anchored = anchoredAt.get(rowId) - if (anchored) { - anchored.push(agentId) - } else { - anchoredAt.set(rowId, [agentId]) - } - } - } - const paths = new Map() - const pathTo = (agentId: string): readonly string[] => { - const known = paths.get(agentId) - if (known) { - return known - } - const scope = scopes.get(agentId) ?? null - const path = scope === null ? [agentId] : [...pathTo(scope), agentId] - paths.set(agentId, path) - return path - } - const pathOf = new Map() - for (const [agentId, agentRows] of rows) { - const path = pathTo(agentId) - for (const row of agentRows) { - pathOf.set(row.message.id, path) - } - } - return { rows, entries, rosters, anchoredAt, openAt, pathOf } -} - -/** Sort child rows separately so parent-only streaming updates reuse their order. */ -export function nativeChatSubagentRowsInOrder( - subagentRows: ReadonlyMap -): readonly NativeChatSubagentRow[] { - return Array.from(subagentRows.values()) - .flat() - .sort((a, b) => compareMessages(a.message, b.message)) -} - -/** Merge parent and child rows in transcript order so child edits remain in their actual turns. */ -export function nativeChatRowsInTranscriptOrder( - messages: readonly NativeChatMessage[], - turnKeys: readonly (string | undefined)[], - subagentRows: readonly NativeChatSubagentRow[] -): { messages: readonly NativeChatMessage[]; turnKeys: readonly (string | undefined)[] } { - if (subagentRows.length === 0) { - return { messages, turnKeys } - } - const merged: NativeChatMessage[] = [] - const mergedTurnKeys: (string | undefined)[] = [] - let next = 0 - for (const [index, message] of messages.entries()) { - while ( - next < subagentRows.length && - compareMessages(subagentRows[next]!.message, message) < 0 - ) { - merged.push(subagentRows[next]!.message) - mergedTurnKeys.push(subagentRows[next]!.turnKey) - next += 1 - } - merged.push(message) - mergedTurnKeys.push(turnKeys[index]) - } - for (const row of subagentRows.slice(next)) { - merged.push(row.message) - mergedTurnKeys.push(row.turnKey) - } - return { messages: merged, turnKeys: mergedTurnKeys } -} diff --git a/src/renderer/src/components/native-chat/subagents/use-native-chat-subagent-scope.tsx b/src/renderer/src/components/native-chat/subagents/use-native-chat-subagent-scope.tsx new file mode 100644 index 00000000000..51ea32548a4 --- /dev/null +++ b/src/renderer/src/components/native-chat/subagents/use-native-chat-subagent-scope.tsx @@ -0,0 +1,132 @@ +import { useMemo } from 'react' +import { latestAgentSessionContextClearSequence } from '../../../../../shared/agent-session/agent-session-context-clear' +import type { AgentSessionLatestTurn } from '../../../../../shared/agent-session/agent-session-wire' +import type { + AgentJournalRenderItem, + AgentJournalSubmission +} from '../../../../../shared/agent-session/journal/agent-session-journal-types' +import type { StructuredAgentSubagentRoster } from '../../../../../shared/agent-session/view/structured-agent-session-subagent-roster' +import type { + NativeChatMessage, + NativeChatSubagentEntry +} from '../../../../../shared/native-chat/native-chat-types' +import { normalizeSubagentState } from '../../../../../shared/native-chat/transcript/native-chat-subagent-summary' +import type { NativeChatSubagentRow } from '../../../../../shared/native-chat/transcript/native-chat-transcript-projection' +import { + useNativeChatTurnMembership, + type NativeChatTurnRows +} from '../conversation/slots/use-native-chat-turn-membership' +import type { NativeChatSubagentView } from './native-chat-open-subagent' +import { nativeChatSubagentHistoryStep } from './native-chat-subagent-history' +import { + nativeChatSubagentEntries, + nativeChatSubagentHeads, + nativeChatSubagentRowsInOrder +} from './native-chat-subagent-scope' +import { NativeChatSubagentViewBar } from './NativeChatSubagentViewBar' + +const NO_MESSAGES: readonly NativeChatMessage[] = [] +const NO_SUBAGENT_ROWS: readonly NativeChatSubagentRow[] = [] +const NO_TURN_KEYS: readonly (string | undefined)[] = [] +const NO_ENTRIES: ReadonlyMap = new Map() + +/** What a transcript draws: the conversation in its turns, or one subagent's own rows with none. */ +export function useNativeChatSubagentScope({ + view, + conversation, + subagentRows, + roster, + journalItems, + journalSubmissions, + latestTurn, + isWorking +}: { + view: NativeChatSubagentView | undefined + conversation: readonly NativeChatMessage[] + subagentRows: ReadonlyMap + roster: StructuredAgentSubagentRoster | undefined + journalItems: readonly AgentJournalRenderItem[] | undefined + journalSubmissions: readonly AgentJournalSubmission[] | undefined + latestTurn: AgentSessionLatestTurn | null | undefined + isWorking: boolean +}) { + const agentId = view?.agentId ?? null + // The conversation names its subagents only for heads, which need rows; a subagent's bar lists them all. + const entries = useMemo( + () => + agentId === null && subagentRows.size === 0 + ? NO_ENTRIES + : nativeChatSubagentEntries(conversation, subagentRows, roster), + [agentId, conversation, roster, subagentRows] + ) + const messages = useMemo( + () => + agentId === null + ? conversation + : (subagentRows.get(agentId) ?? NO_SUBAGENT_ROWS).map(({ message }) => message), + [agentId, conversation, subagentRows] + ) + const heads = useMemo( + () => nativeChatSubagentHeads(messages, subagentRows, entries, agentId), + [agentId, entries, messages, subagentRows] + ) + // Child edits and PRs count in the conversation's turns, which a subagent's view does not draw. + const rowsInOrder = useMemo( + () => (agentId === null ? nativeChatSubagentRowsInOrder(subagentRows) : NO_SUBAGENT_ROWS), + [agentId, subagentRows] + ) + const conversationTurns = useNativeChatTurnMembership( + agentId === null ? messages : NO_MESSAGES, + journalItems, + journalSubmissions, + latestTurn + ) + const turnRows = useMemo( + () => + agentId === null + ? conversationTurns + : { messages, turnKeys: NO_TURN_KEYS, liveTurnKey: undefined }, + [agentId, conversationTurns, messages] + ) + // A subagent's view pages history only while older history still holds its spawn. + const pagesHistory = useMemo( + () => + agentId === null || + nativeChatSubagentHistoryStep({ + agentId, + conversation, + subagentRows, + roster, + historyFloor: () => latestAgentSessionContextClearSequence(journalItems ?? []) + }) === 'page', + [agentId, conversation, journalItems, roster, subagentRows] + ) + const entry = agentId === null ? undefined : entries.get(agentId) + const open = view?.open + return { + agentId, + open, + /** Drawn above a subagent's own transcript. */ + bar: + agentId !== null && open ? ( + + ) : null, + messages, + heads, + rowsInOrder, + turnRows, + /** The conversation's turns; null in a subagent's view. */ + conversationTurns: agentId === null ? turnRows : null, + pagesHistory, + // A subagent's rows sit in the conversation's turns, so its view runs on the agent's own state. + working: + agentId === null + ? isWorking + : entry !== undefined && normalizeSubagentState(entry.state) === 'working' + } +} diff --git a/src/renderer/src/components/native-chat/subagents/use-native-chat-subagent-sections.ts b/src/renderer/src/components/native-chat/subagents/use-native-chat-subagent-sections.ts deleted file mode 100644 index d332712c94d..00000000000 --- a/src/renderer/src/components/native-chat/subagents/use-native-chat-subagent-sections.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react' -import type { NativeChatMessage } from '../../../../../shared/native-chat/native-chat-types' -import type { NativeChatSubagentRow } from '../../../../../shared/native-chat/transcript/native-chat-transcript-projection' -import type { StructuredAgentSubagentRoster } from '../../../../../shared/agent-session/view/structured-agent-session-subagent-roster' -import { chooseNativeChatExpanded } from '../messages/disclosure/native-chat-expanded-keys' -import { - NO_NATIVE_CHAT_SUBAGENT_CHOICES, - nativeChatSubagentRowsInOrder, - nativeChatSubagentSections, - type NativeChatSubagentChoices, - type NativeChatSubagentDisclosure, - type NativeChatSubagentSections -} from './native-chat-subagent-sections' - -function choose( - current: NativeChatSubagentChoices, - kind: keyof NativeChatSubagentChoices, - key: string, - open: boolean -): NativeChatSubagentChoices { - const next = chooseNativeChatExpanded(current[kind], key, open) - return next === current[kind] ? current : { ...current, [kind]: next } -} - -/** Preserve manual section/roster choices; otherwise expand only at the running scope’s live frontier. */ -export function useNativeChatSubagentSections( - conversation: readonly NativeChatMessage[], - subagentRows: ReadonlyMap, - roster?: StructuredAgentSubagentRoster -): { - sections: NativeChatSubagentSections - /** Every subagent row in transcript order; kept while only the conversation changes. */ - subagentRowsInOrder: readonly NativeChatSubagentRow[] - subagentChoices: NativeChatSubagentChoices - subagentDisclosure: NativeChatSubagentDisclosure - /** Expand containing sections/rosters so reveals can land on these rows. */ - openSubagentSections: (agentIds: readonly string[]) => void -} { - const sections = useMemo( - () => nativeChatSubagentSections(conversation, subagentRows, roster), - [conversation, roster, subagentRows] - ) - const subagentRowsInOrder = useMemo( - () => nativeChatSubagentRowsInOrder(subagentRows), - [subagentRows] - ) - const [subagentChoices, setChoices] = useState(NO_NATIVE_CHAT_SUBAGENT_CHOICES) - const subagentDisclosure = useMemo( - () => ({ - setSectionOpen: (agentId, open) => - setChoices((current) => choose(current, 'sections', agentId, open)), - setRosterOpen: (rosterRowId, open) => - setChoices((current) => choose(current, 'rosters', rosterRowId, open)) - }), - [] - ) - // Read only by a reveal, so the callback keeps one identity while the transcript streams. - const sectionsRef = useRef(sections) - useLayoutEffect(() => { - sectionsRef.current = sections - }, [sections]) - const openSubagentSections = useCallback((agentIds: readonly string[]) => { - const opening = new Set(agentIds) - const rosterRowIds = Array.from(sectionsRef.current.anchoredAt).flatMap(([rowId, anchored]) => - anchored.some((agentId) => opening.has(agentId)) ? [rowId] : [] - ) - setChoices((current) => - rosterRowIds.reduce( - (choices, rowId) => choose(choices, 'rosters', rowId, true), - agentIds.reduce((choices, agentId) => choose(choices, 'sections', agentId, true), current) - ) - ) - }, []) - return { - sections, - subagentRowsInOrder, - subagentChoices, - subagentDisclosure, - openSubagentSections - } -} diff --git a/src/renderer/src/components/native-chat/subagents/use-structured-native-chat-subagents.tsx b/src/renderer/src/components/native-chat/subagents/use-structured-native-chat-subagents.tsx new file mode 100644 index 00000000000..7da498d9204 --- /dev/null +++ b/src/renderer/src/components/native-chat/subagents/use-structured-native-chat-subagents.tsx @@ -0,0 +1,56 @@ +import type { AgentSessionCancelResult } from '../../../../../shared/agent-session/agent-session-wire' +import type { StructuredAgentSubagentRoster } from '../../../../../shared/agent-session/view/structured-agent-session-subagent-roster' +import type { StructuredSessionBackgroundTasksView } from '../../../../../shared/structured-session-background-tasks-view' +import { NativeChatStructuredSessionStatus } from '../tools/tasks/NativeChatStructuredSessionStatus' +import { useStructuredSessionTaskStop } from '../tools/tasks/use-structured-session-task-stop' +import { + closeNativeChatSubagentOnEscape, + openNativeChatSubagent, + useNativeChatOpenSubagent +} from './native-chat-open-subagent' +import { NativeChatStructuredSubagentStatusBar } from './NativeChatSubagentStatusBar' + +/** A structured chat's agents strip and open subagent's bar, which share the strip's one Stop. */ +export function useStructuredNativeChatSubagents({ + sessionId, + paneKey, + isVisible, + controller +}: { + sessionId: string + paneKey: string + isVisible: boolean + controller: { + subagentRoster?: StructuredAgentSubagentRoster + backgroundTasks: StructuredSessionBackgroundTasksView + stopBackgroundTask: (taskId?: string) => Promise + } +}) { + const openId = useNativeChatOpenSubagent(paneKey) + const stop = useStructuredSessionTaskStop(sessionId, controller) + return { + /** The subagent whose view replaces the conversation and the composer; null for none. */ + openId, + onKeyDown: (event: React.KeyboardEvent) => closeNativeChatSubagentOnEscape(event, paneKey), + strip: ( + + ), + statusBar: + openId === null ? null : ( + openNativeChatSubagent(paneKey, null)} + /> + ) + } +} diff --git a/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.test-harness.tsx b/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.test-harness.tsx index 77585ea9c24..197d99f5048 100644 --- a/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.test-harness.tsx +++ b/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.test-harness.tsx @@ -315,8 +315,7 @@ export function createStructuredSessionMocks() { revealLatest: mocks.revealLatest, readerAtEnd: () => true, revealFindMatch: () => {}, - messageCopyText: () => null, - revealSubagent: () => {} + messageCopyText: () => null })) return } diff --git a/src/renderer/src/components/native-chat/tools/diffs/use-native-chat-turn-diffs.ts b/src/renderer/src/components/native-chat/tools/diffs/use-native-chat-turn-diffs.ts index ee56171deec..9f33e8a3437 100644 --- a/src/renderer/src/components/native-chat/tools/diffs/use-native-chat-turn-diffs.ts +++ b/src/renderer/src/components/native-chat/tools/diffs/use-native-chat-turn-diffs.ts @@ -1,6 +1,6 @@ import { useMemo } from 'react' import type { NativeChatSubagentRow } from '../../../../../../shared/native-chat/transcript/native-chat-transcript-projection' -import { nativeChatRowsInTranscriptOrder } from '../../subagents/native-chat-subagent-sections' +import { nativeChatRowsInTranscriptOrder } from '../../subagents/native-chat-subagent-scope' import { nativeChatTurnDiffs, type NativeChatTurnDiff @@ -12,19 +12,13 @@ const NO_TURN_DIFFS: ReadonlyMap = new Map() /** Count subagent edits in their owning turn; omit totals without a journal or for partially loaded turns. */ export function useNativeChatTurnDiffs( turns: NativeChatTurnRows | null, - subagentRows: readonly NativeChatSubagentRow[], - subagentSectionsOf: ReadonlyMap + subagentRows: readonly NativeChatSubagentRow[] ): ReadonlyMap { return useMemo(() => { if (!turns) { return NO_TURN_DIFFS } const merged = nativeChatRowsInTranscriptOrder(turns.messages, turns.turnKeys, subagentRows) - return nativeChatTurnDiffs( - merged.messages, - merged.turnKeys, - subagentSectionsOf, - turns.partialTurnKey - ) - }, [subagentRows, subagentSectionsOf, turns]) + return nativeChatTurnDiffs(merged.messages, merged.turnKeys, undefined, turns.partialTurnKey) + }, [subagentRows, turns]) } diff --git a/src/renderer/src/components/native-chat/tools/pull-requests/use-native-chat-turn-opened-pull-requests.ts b/src/renderer/src/components/native-chat/tools/pull-requests/use-native-chat-turn-opened-pull-requests.ts index 8c59c4b40f0..bcdb23fa1db 100644 --- a/src/renderer/src/components/native-chat/tools/pull-requests/use-native-chat-turn-opened-pull-requests.ts +++ b/src/renderer/src/components/native-chat/tools/pull-requests/use-native-chat-turn-opened-pull-requests.ts @@ -10,7 +10,7 @@ import { type NativeChatTurnOpenedPullRequests } from '../../../../../../shared/native-chat/tools/native-chat-opened-pull-requests' import { nativeChatToolFullPayload } from '../../../../../../shared/native-chat/tools/native-chat-tool-output' -import { nativeChatRowsInTranscriptOrder } from '../../subagents/native-chat-subagent-sections' +import { nativeChatRowsInTranscriptOrder } from '../../subagents/native-chat-subagent-scope' import { NativeChatMarkdownImageOwnerContext } from '../../media/images/native-chat-markdown-image-owner' import { useNativeChatVisualOwner } from '../../media/visuals/native-chat-visual-owner' import type { NativeChatTurnRows } from '../../conversation/slots/use-native-chat-turn-membership' diff --git a/src/renderer/src/components/native-chat/tools/runs/NativeChatToolRun.tsx b/src/renderer/src/components/native-chat/tools/runs/NativeChatToolRun.tsx index ac01158e0f2..a04390804a3 100644 --- a/src/renderer/src/components/native-chat/tools/runs/NativeChatToolRun.tsx +++ b/src/renderer/src/components/native-chat/tools/runs/NativeChatToolRun.tsx @@ -22,10 +22,6 @@ import { nativeChatAskRunSubject } from '../../../../../../shared/native-chat/in import { NativeChatAwaitingInputRow } from '../../prompts/NativeChatAwaitingInputRow' import { NativeChatBackgroundTaskRun } from '../tasks/NativeChatBackgroundTaskRun' import { NativeChatSubagentRun } from '../../subagents/NativeChatSubagentRun' -import type { - NativeChatSubagentDisclosure, - NativeChatSubagentRosterState -} from '../../subagents/native-chat-subagent-sections' import { NativeChatToolRunIcon } from '../lines/NativeChatToolIcon' import { NativeChatToolRunCallCounts } from './NativeChatToolRunCallCounts' import { NativeChatToolRunMembers, revealNativeChatToolRunMember } from './NativeChatToolRunMembers' @@ -52,8 +48,7 @@ export function NativeChatToolRun({ revealedDiff, onRevealDiff, subagentGroups = NO_SUBAGENT_GROUPS, - subagentRoster, - subagentDisclosure, + onOpenSubagent, backgroundTasks = NO_BACKGROUND_TASKS, followsProse = true, expandSignal, @@ -70,9 +65,8 @@ export function NativeChatToolRun({ onRevealDiff?: (element: HTMLElement) => void /** Spawn-group rosters that belong with this run's activity, one row each. */ subagentGroups?: NativeChatSubagentGroupBlock[] - /** The rosters' list state, and their children whose rows open below this run. */ - subagentRoster?: NativeChatSubagentRosterState - subagentDisclosure?: NativeChatSubagentDisclosure + /** Opens one of the rosters' subagents in its own view. */ + onOpenSubagent?: (agentId: string) => void /** Background tasks that belong with this run's activity, one row each. */ backgroundTasks?: NativeChatBackgroundTaskBlock[] /** The row draws prose above this run, which the run then sits just under. */ @@ -115,14 +109,8 @@ export function NativeChatToolRun({ subagentDisclosure.setRosterOpen(disclosureId, open) - : undefined - } - sections={subagentRoster?.sections} - onSetSectionOpen={subagentDisclosure?.setSectionOpen} + disclosureId={disclosureId} + onOpenSubagent={onOpenSubagent} /> )) // Roster/task rows bypass tool-header hiding because they carry durable state beyond the originating turn. diff --git a/src/renderer/src/components/native-chat/tools/runs/native-chat-transcript-work-runs.ts b/src/renderer/src/components/native-chat/tools/runs/native-chat-transcript-work-runs.ts index 3fc0f456745..ccbf81ca290 100644 --- a/src/renderer/src/components/native-chat/tools/runs/native-chat-transcript-work-runs.ts +++ b/src/renderer/src/components/native-chat/tools/runs/native-chat-transcript-work-runs.ts @@ -1,4 +1,4 @@ -// Combine calls/thoughts after slot selection so every intervening visible row or section boundary ends the run. +// Combine calls/thoughts after slot selection so every intervening visible row ends the run. import { agentJournalItemSubagentId } from '../../../../../../shared/agent-session/journal/agent-session-journal-producer' import { @@ -22,17 +22,12 @@ function workRunRow(slot: NativeChatTranscriptSlot): NativeChatWorkRunRow { return { member: null, draws: true, scope: undefined } } return { - member: - slot.drawsMessage && slot.subagentRoster === undefined - ? nativeChatWorkRunMember( - slot.message, - slot.receipt !== undefined, - // At the top level the live line owns the open thought; only a section has none. - slot.depth > 0 && slot.activeTurnIsWorking - ) - : null, + member: slot.drawsMessage + ? // The live line owns the open thought. + nativeChatWorkRunMember(slot.message, slot.receipt !== undefined, false) + : null, draws: true, - scope: `${slot.depth}:${agentJournalItemSubagentId(slot.message)}:${slot.turnKey}` + scope: `${agentJournalItemSubagentId(slot.message)}:${slot.turnKey}` } } @@ -60,8 +55,7 @@ function workRunSlot( hasStatus: head.status !== undefined, hasTurnDiff: turnDiff !== undefined, turnDiffFileCount: turnDiff?.files.length, - openedPullRequestCount: openedPullRequests?.length, - inSubagentSection: head.depth > 0 + openedPullRequestCount: openedPullRequests?.length }, typography ) diff --git a/src/renderer/src/components/native-chat/tools/tasks/NativeChatBackgroundTasksStatus.tsx b/src/renderer/src/components/native-chat/tools/tasks/NativeChatBackgroundTasksStatus.tsx index bb8528460f4..9b8034f670f 100644 --- a/src/renderer/src/components/native-chat/tools/tasks/NativeChatBackgroundTasksStatus.tsx +++ b/src/renderer/src/components/native-chat/tools/tasks/NativeChatBackgroundTasksStatus.tsx @@ -19,11 +19,13 @@ import { backgroundTaskRowMeta, backgroundTaskRowStopId, backgroundTasksStripTicks, - buildBackgroundTaskGroupsFromViews, type BackgroundTaskGroup } from '../../../../../../shared/background-task-roster' import { backgroundTasksHeaderContent } from './background-task-header-content' -import { backgroundTaskGroupLabel, buildBackgroundTaskGroups } from './background-task-roster' +import { + backgroundTaskGroupLabel, + structuredSessionBackgroundTaskGroups +} from './background-task-roster' import { sayBackgroundTaskTranslated as say } from './background-task-words-text' /** Use strip width in rem so narrow splits behave like narrow windows even on wide monitors. */ @@ -176,7 +178,7 @@ export function NativeChatBackgroundTasksStatus(props: { expanded: boolean onExpandedChange: (expanded: boolean) => void onStop: (taskId?: string) => void - /** Open a listed agent's activity where it sits in the conversation. */ + /** Open a listed agent's own view. */ onShowAgent?: (providerId: string) => void }): React.JSX.Element { const expanded = props.expanded @@ -186,9 +188,12 @@ export function NativeChatBackgroundTasksStatus(props: { // The 1 Hz elapsed tick must not re-group, re-sort and re-translate the whole roster. const groups: BackgroundTaskGroup[] = useMemo( () => - props.childViews !== undefined - ? buildBackgroundTaskGroupsFromViews(props.childViews, props.childRowContext) - : buildBackgroundTaskGroups(props.tasks, props.settledTasks), + structuredSessionBackgroundTaskGroups( + props.tasks, + props.settledTasks, + props.childViews, + props.childRowContext + ), [props.childViews, props.childRowContext, props.tasks, props.settledTasks] ) const now = useNow(1_000, props.isVisible && backgroundTasksStripTicks(groups, expanded)) diff --git a/src/renderer/src/components/native-chat/tools/tasks/NativeChatStructuredSessionStatus.test.tsx b/src/renderer/src/components/native-chat/tools/tasks/NativeChatStructuredSessionStatus.test.tsx index ff805ace800..1cc96a6bc2d 100644 --- a/src/renderer/src/components/native-chat/tools/tasks/NativeChatStructuredSessionStatus.test.tsx +++ b/src/renderer/src/components/native-chat/tools/tasks/NativeChatStructuredSessionStatus.test.tsx @@ -8,6 +8,7 @@ import type { AgentSessionCancelResult } from '../../../../../../shared/agent-se import type { AgentChildWorkView } from '../../../../../../shared/agent-status/child-work/agent-status-child-work-view' import { structuredSessionBackgroundTasksView } from '../../../../../../shared/structured-session-background-tasks-view' import { NativeChatStructuredSessionStatus } from './NativeChatStructuredSessionStatus' +import { useStructuredSessionTaskStop } from './use-structured-session-task-stop' vi.mock('./use-structured-session-child-row-context', () => ({ useStructuredSessionChildRowContext: () => undefined @@ -15,6 +16,19 @@ vi.mock('./use-structured-session-child-row-context', () => ({ afterEach(cleanup) +function Strip(props: { tasks: Parameters[1] }) { + const stop = useStructuredSessionTaskStop('session-1', props.tasks) + return ( + + ) +} + function helper(invocation: AgentChildWorkView['invocation']): AgentChildWorkView { return { id: 'helper', @@ -37,10 +51,7 @@ describe('NativeChatStructuredSessionStatus', () => { () => new Promise((resolve) => (finish = resolve)) ) const strip = (children: AgentChildWorkView[]) => ( - - all: boolean -} - -/** Each confirmed Stop's task, with the run it was pressed on. */ -type ConfirmedStops = { sessionId: string; taskIds: ReadonlyMap } - -const NO_STOPPING_TASKS: ReadonlySet = new Set() -const NO_CONFIRMED_STOPS: ReadonlyMap = new Map() +import type { StructuredSessionTaskStop } from './use-structured-session-task-stop' +import { openNativeChatSubagent } from '../../subagents/native-chat-open-subagent' export function NativeChatStructuredSessionStatus(props: { sessionId: string - /** The session's own status row, whose verdict the strip's children read. */ + /** The session's own status row, whose verdict the strip's children read; also names the pane a picked agent opens in. */ paneKey: string isVisible: boolean - /** The session's background work and its Stop. */ - tasks: { - backgroundTasks: StructuredSessionBackgroundTasksView - stopBackgroundTask: (taskId?: string) => Promise - } - /** The pane's transcript, where an agent picked in the strip opens. */ - messageListRef?: React.RefObject + /** The session's background work. */ + backgroundTasks: StructuredSessionBackgroundTasksView + stop: StructuredSessionTaskStop }): React.JSX.Element { - const [stopping, setStopping] = useState(null) - // Keep confirmed Stop buttons pending until that specific run leaves the strip. - const [confirmed, setConfirmed] = useState(null) const [expanded, setExpanded] = useState<{ sessionId: string; expanded: boolean } | null>(null) - const activeStopping = stopping?.sessionId === props.sessionId ? stopping : null - const activeConfirmed = confirmed?.sessionId === props.sessionId ? confirmed.taskIds : null - const confirmedListed = activeConfirmed - ? structuredSessionConfirmedStopsStillListed(props.tasks.backgroundTasks, activeConfirmed) - : null - if (confirmedListed !== activeConfirmed) { - // A row that left and came back is a task the Stop did not end, so it offers Stop again. - setConfirmed( - confirmedListed?.size ? { sessionId: props.sessionId, taskIds: confirmedListed } : null - ) - } - const stoppingTaskIds = confirmedListed?.size - ? new Set([...(activeStopping?.taskIds ?? NO_STOPPING_TASKS), ...confirmedListed.keys()]) - : (activeStopping?.taskIds ?? NO_STOPPING_TASKS) const childRowContext = useStructuredSessionChildRowContext(props.paneKey) - - const onStop = (taskId?: string) => { - const sessionId = props.sessionId - // A provider may reuse the row's id for the task's next run, which this Stop did not end. - const run = taskId ? structuredSessionListedTaskRun(props.tasks.backgroundTasks, taskId) : null - setStopping((current) => { - const taskIds = new Set( - current?.sessionId === sessionId ? current.taskIds : NO_STOPPING_TASKS - ) - if (taskId) { - taskIds.add(taskId) - } - return { - sessionId, - taskIds, - all: taskId ? current?.sessionId === sessionId && current.all : true - } - }) - void props.tasks - .stopBackgroundTask(taskId) - .then((result) => { - if (taskId && run !== null && result?.cancelled) { - setConfirmed((current) => ({ - sessionId, - taskIds: new Map([ - ...(current?.sessionId === sessionId ? current.taskIds : NO_CONFIRMED_STOPS), - [taskId, run] - ]) - })) - } - }) - .finally(() => { - setStopping((current) => { - if (current?.sessionId !== sessionId) { - return current - } - const taskIds = new Set(current.taskIds) - if (taskId) { - taskIds.delete(taskId) - } - const all = taskId ? current.all : false - return taskIds.size === 0 && !all ? null : { sessionId, taskIds, all } - }) - }) - } + const { backgroundTasks, stop } = props return ( <> - {props.tasks.backgroundTasks.show ? ( + {backgroundTasks.show ? ( setExpanded({ sessionId: props.sessionId, expanded: value })} - onStop={onStop} - onShowAgent={(providerId) => props.messageListRef?.current?.revealSubagent(providerId)} + onStop={stop.onStop} + onShowAgent={(providerId) => openNativeChatSubagent(props.paneKey, providerId)} /> ) : null} diff --git a/src/renderer/src/components/native-chat/tools/tasks/background-task-roster.ts b/src/renderer/src/components/native-chat/tools/tasks/background-task-roster.ts index 8149a680f23..42cae93b529 100644 --- a/src/renderer/src/components/native-chat/tools/tasks/background-task-roster.ts +++ b/src/renderer/src/components/native-chat/tools/tasks/background-task-roster.ts @@ -1,9 +1,12 @@ // Localize the shared background-task grouping vocabulary. import type { AgentSessionBackgroundTask } from '../../../../../../shared/agent-session/agent-session-background-task-wire' +import type { AgentChildRowContext } from '../../../../../../shared/agent-status/presentation/agent-child-row-model' +import type { AgentChildWorkView } from '../../../../../../shared/agent-status/child-work/agent-status-child-work-view' import { backgroundTaskGroupLabel as groupLabel, buildBackgroundTaskGroups as buildGroups, + buildBackgroundTaskGroupsFromViews, type BackgroundTaskGroup } from '../../../../../../shared/background-task-roster' import { sayBackgroundTaskTranslated as say } from './background-task-words-text' @@ -17,6 +20,18 @@ export function buildBackgroundTaskGroups( return buildGroups(tasks, settledTasks, say) } +/** The strip's rows: the host's child views when it publishes them, else its task roster. */ +export function structuredSessionBackgroundTaskGroups( + tasks: readonly AgentSessionBackgroundTask[], + settledTasks: readonly AgentSessionBackgroundTask[], + childViews: readonly AgentChildWorkView[] | undefined, + childRowContext: AgentChildRowContext | undefined +): BackgroundTaskGroup[] { + return childViews !== undefined + ? buildBackgroundTaskGroupsFromViews(childViews, childRowContext) + : buildBackgroundTaskGroups(tasks, settledTasks) +} + export function backgroundTaskGroupLabel(kind: TaskKind): string { return groupLabel(kind, say) } diff --git a/src/renderer/src/components/native-chat/tools/tasks/use-structured-session-task-stop.ts b/src/renderer/src/components/native-chat/tools/tasks/use-structured-session-task-stop.ts new file mode 100644 index 00000000000..8abbcc4301e --- /dev/null +++ b/src/renderer/src/components/native-chat/tools/tasks/use-structured-session-task-stop.ts @@ -0,0 +1,96 @@ +import { useState } from 'react' +import type { AgentSessionCancelResult } from '../../../../../../shared/agent-session/agent-session-wire' +import { + structuredSessionConfirmedStopsStillListed, + structuredSessionListedTaskRun, + type StructuredSessionBackgroundTasksView +} from '../../../../../../shared/structured-session-background-tasks-view' + +type StoppingBackgroundTasks = { + sessionId: string + taskIds: ReadonlySet + all: boolean +} + +/** Each confirmed Stop's task, with the run it was pressed on. */ +type ConfirmedStops = { sessionId: string; taskIds: ReadonlyMap } + +const NO_STOPPING_TASKS: ReadonlySet = new Set() +const NO_CONFIRMED_STOPS: ReadonlyMap = new Map() + +/** The session's background-work Stop, shared by the agents strip and an open subagent's bar. */ +export type StructuredSessionTaskStop = { + stoppingTaskIds: ReadonlySet + stoppingAll: boolean + onStop: (taskId?: string) => void +} + +export function useStructuredSessionTaskStop( + sessionId: string, + tasks: { + backgroundTasks: StructuredSessionBackgroundTasksView + stopBackgroundTask: (taskId?: string) => Promise + } +): StructuredSessionTaskStop { + const [stopping, setStopping] = useState(null) + // Keep confirmed Stop buttons pending until that specific run leaves the strip. + const [confirmed, setConfirmed] = useState(null) + const activeStopping = stopping?.sessionId === sessionId ? stopping : null + const activeConfirmed = confirmed?.sessionId === sessionId ? confirmed.taskIds : null + const confirmedListed = activeConfirmed + ? structuredSessionConfirmedStopsStillListed(tasks.backgroundTasks, activeConfirmed) + : null + if (confirmedListed !== activeConfirmed) { + // A row that left and came back is a task the Stop did not end, so it offers Stop again. + setConfirmed(confirmedListed?.size ? { sessionId, taskIds: confirmedListed } : null) + } + const stoppingTaskIds = confirmedListed?.size + ? new Set([...(activeStopping?.taskIds ?? NO_STOPPING_TASKS), ...confirmedListed.keys()]) + : (activeStopping?.taskIds ?? NO_STOPPING_TASKS) + + const onStop = (taskId?: string) => { + // A provider may reuse the row's id for the task's next run, which this Stop did not end. + const run = taskId ? structuredSessionListedTaskRun(tasks.backgroundTasks, taskId) : null + setStopping((current) => { + const taskIds = new Set( + current?.sessionId === sessionId ? current.taskIds : NO_STOPPING_TASKS + ) + if (taskId) { + taskIds.add(taskId) + } + return { + sessionId, + taskIds, + all: taskId ? current?.sessionId === sessionId && current.all : true + } + }) + void tasks + .stopBackgroundTask(taskId) + .then((result) => { + if (taskId && run !== null && result?.cancelled) { + setConfirmed((current) => ({ + sessionId, + taskIds: new Map([ + ...(current?.sessionId === sessionId ? current.taskIds : NO_CONFIRMED_STOPS), + [taskId, run] + ]) + })) + } + }) + .finally(() => { + setStopping((current) => { + if (current?.sessionId !== sessionId) { + return current + } + const taskIds = new Set(current.taskIds) + if (taskId) { + taskIds.delete(taskId) + } + const all = taskId ? current.all : false + return taskIds.size === 0 && !all ? null : { sessionId, taskIds, all } + }) + }) + } + + return { stoppingTaskIds, stoppingAll: activeStopping?.all ?? false, onStop } +} diff --git a/src/renderer/src/components/native-chat/viewport/navigation/use-native-chat-history-jump.ts b/src/renderer/src/components/native-chat/viewport/navigation/use-native-chat-history-jump.ts index 90288740be6..1a4bb8c1746 100644 --- a/src/renderer/src/components/native-chat/viewport/navigation/use-native-chat-history-jump.ts +++ b/src/renderer/src/components/native-chat/viewport/navigation/use-native-chat-history-jump.ts @@ -7,20 +7,15 @@ import type { NativeChatOlderPageResult } from '../history/native-chat-paginatio /** Bound runaway paging beyond any expected session size. */ export const NATIVE_CHAT_HISTORY_JUMP_MAX_PAGES = 1000 -/** A rail pick, or a subagent named from outside the transcript (the agents strip). */ +/** A rail pick, or the subagent a view shows, whose spawn may sit in older history. */ export type NativeChatHistoryJumpTarget = | { kind: 'rail'; id: string } | { kind: 'subagent'; agentId: string } -/** - * What the committed transcript can do for a target now: it landed, it needs older history, - * it needs one more commit (a disclosure the step just opened), or it cannot be reached. - * `waited` counts the commits waited since the last page, so a step opens once, then lands. - */ +/** What the committed transcript can do for a target now: it landed, it needs older history, or it cannot be reached. */ export type NativeChatHistoryJumpStep = ( - target: NativeChatHistoryJumpTarget, - waited: number -) => 'landed' | 'page' | 'commit' | 'stop' + target: NativeChatHistoryJumpTarget +) => 'landed' | 'page' | 'stop' /** A rail pick lands once its message has a slot; an omitted one stops. */ export function nativeChatRailJumpStep( @@ -88,28 +83,14 @@ export function useNativeChatHistoryJump({ const run = useCallback( async (target: NativeChatHistoryJumpTarget, signal: AbortSignal): Promise => { - let waited = 0 - for (let pages = 0; ;) { - const next = committedRef.current.step(target, waited) - if (next === 'landed' || next === 'stop') { + for (let pages = 0; ; pages += 1) { + const next = committedRef.current.step(target) + if (next !== 'page' || pages >= NATIVE_CHAT_HISTORY_JUMP_MAX_PAGES) { return } - if (next === 'commit') { - // A disclosure opens once; a target still missing after its commit is not coming. - if (waited > 0) { - return - } - waited += 1 - } else { - if (pages >= NATIVE_CHAT_HISTORY_JUMP_MAX_PAGES) { - return - } - pages += 1 - waited = 0 - const result = await committedRef.current.loadEarlier() - if (signal.aborted || result !== 'applied') { - return - } + const result = await committedRef.current.loadEarlier() + if (signal.aborted || result !== 'applied') { + return } await nextCommit(signal) if (signal.aborted) { diff --git a/src/renderer/src/components/native-chat/viewport/navigation/use-native-chat-transcript-navigation.ts b/src/renderer/src/components/native-chat/viewport/navigation/use-native-chat-transcript-navigation.ts index 97cdc5df756..6b576082c26 100644 --- a/src/renderer/src/components/native-chat/viewport/navigation/use-native-chat-transcript-navigation.ts +++ b/src/renderer/src/components/native-chat/viewport/navigation/use-native-chat-transcript-navigation.ts @@ -1,6 +1,6 @@ -// One navigation at a time — a rail pick, a diff reveal or a subagent named by the agents strip — pinned until it lands; rail picks and subagent reveals page through one cancellable history loop. +// One navigation at a time — a rail pick or a diff reveal — pinned until it lands; rail picks and a subagent view's history page through one cancellable history loop. -import { useCallback, useRef, useState } from 'react' +import { useCallback, useEffect, useRef, useState } from 'react' import { latestAgentSessionContextClearSequence } from '../../../../../../shared/agent-session/agent-session-context-clear' import type { AgentJournalRenderItem } from '../../../../../../shared/agent-session/journal/agent-session-journal-types' import type { StructuredAgentSubagentRoster } from '../../../../../../shared/agent-session/view/structured-agent-session-subagent-roster' @@ -9,18 +9,10 @@ import type { NativeChatDiffTarget } from '../../../../../../shared/native-chat/tools/native-chat-turn-diffs' import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types' +import type { NativeChatSubagentRow } from '../../../../../../shared/native-chat/transcript/native-chat-transcript-projection' import type { NativeChatRailItem } from '../rail/native-chat-message-rail-items' import type { NativeChatOlderPageResult } from '../history/native-chat-pagination' -import { - nativeChatSubagentLanding, - nativeChatSubagentPlace, - useNativeChatSubagentLanding, - type NativeChatSubagentLanding -} from '../../subagents/native-chat-subagent-reveal' -import type { - NativeChatSubagentDisclosure, - NativeChatSubagentSections -} from '../../subagents/native-chat-subagent-sections' +import { nativeChatSubagentHistoryStep } from '../../subagents/native-chat-subagent-history' import { nativeChatSlotIndexOf } from '../../conversation/slots/native-chat-transcript-slot-selection' import type { NativeChatTranscriptSlot } from '../../conversation/slots/native-chat-transcript-slots' import { nativeChatRailJumpStep, useNativeChatHistoryJump } from './use-native-chat-history-jump' @@ -30,13 +22,10 @@ import type { NativeChatAlignEdge } from '../virtualization/use-native-chat-view type NavigationRequest = | { kind: 'diff'; target: NativeChatDiffReveal } | { kind: 'rail'; messageId: string; requestId: number } - | { kind: 'subagent'; agentId: string; requestId: number } export type NativeChatNavigationRequest = { revealedDiff: NativeChatDiffReveal | null railJump: { messageId: string; requestId: number } | null - subagentJump: { agentId: string; requestId: number } | null - subagentLanding: NativeChatSubagentLanding | null /** The one slot the window keeps mounted until the request lands. */ revealIndex: number issue: (request: NavigationRequest | null) => void @@ -45,9 +34,7 @@ export type NativeChatNavigationRequest = { /** Read before the window mounts rows, so the request's slot stays drawn. */ export function useNativeChatNavigationRequest( - slots: readonly NativeChatTranscriptSlot[], - conversation: readonly NativeChatMessage[], - sections: NativeChatSubagentSections + slots: readonly NativeChatTranscriptSlot[] ): NativeChatNavigationRequest { const [request, issue] = useState(null) const sequence = useRef(0) @@ -57,18 +44,10 @@ export function useNativeChatNavigationRequest( }, []) const revealedDiff = request?.kind === 'diff' ? request.target : null const railJump = request?.kind === 'rail' ? request : null - const subagentJump = request?.kind === 'subagent' ? request : null - const subagentLanding = subagentJump - ? nativeChatSubagentLanding(slots, conversation, sections, subagentJump.agentId) - : null - const revealIndex = - subagentLanding?.index ?? - nativeChatSlotIndexOf(slots, railJump?.messageId ?? revealedDiff?.messageId) + const revealIndex = nativeChatSlotIndexOf(slots, railJump?.messageId ?? revealedDiff?.messageId) return { revealedDiff, railJump, - subagentJump, - subagentLanding, revealIndex, issue, nextRequestId @@ -80,14 +59,14 @@ export function useNativeChatNavigation({ rail, slots, conversation, - sections, + subagentRows, roster, journalItems, - openSubagentSections, - subagentDisclosure, + subagentId, sessionKey, isVisible, loadEarlier, + holdHistory, scrollRef, scrollMessageToTop, readerLeavesEnd, @@ -97,14 +76,16 @@ export function useNativeChatNavigation({ rail: { items: readonly NativeChatRailItem[]; onActivate: (id: string) => void } slots: readonly NativeChatTranscriptSlot[] conversation: readonly NativeChatMessage[] - sections: NativeChatSubagentSections + subagentRows: ReadonlyMap roster: StructuredAgentSubagentRoster | undefined journalItems: readonly AgentJournalRenderItem[] | undefined - openSubagentSections: (agentIds: readonly string[]) => void - subagentDisclosure: NativeChatSubagentDisclosure + /** A subagent's view, which pages older history until the agent's spawn is loaded. */ + subagentId: string | null sessionKey: string isVisible: boolean loadEarlier: () => Promise + /** Keeps paged history loaded while the reader stays at the end. */ + holdHistory: () => void scrollRef: React.RefObject scrollMessageToTop: (element: HTMLElement, edge?: NativeChatAlignEdge) => void readerLeavesEnd: () => void @@ -118,31 +99,22 @@ export function useNativeChatNavigation({ [issue, nextRequestId] ) const historyJump = useNativeChatHistoryJump({ - step: (target, waited) => { + step: (target) => { if (target.kind === 'rail') { return nativeChatRailJumpStep(rail.items, target.id, requestRailJump) } - const place = nativeChatSubagentPlace({ + const step = nativeChatSubagentHistoryStep({ agentId: target.agentId, conversation, - sections, + subagentRows, roster, - slots, // The transcript starts at its latest /clear divider; scanned only when a page is in question. historyFloor: () => latestAgentSessionContextClearSequence(journalItems ?? []) }) - if (place.kind !== 'open') { - return place.kind + if (step === 'page') { + holdHistory() } - if (waited === 0) { - openSubagentSections(place.agentIds) - if (place.rosterRowId !== undefined) { - subagentDisclosure.setRosterOpen(place.rosterRowId, true) - } - return 'commit' - } - issue({ kind: 'subagent', agentId: target.agentId, requestId: nextRequestId() }) - return 'landed' + return step }, sessionKey, isVisible, @@ -166,21 +138,15 @@ export function useNativeChatNavigation({ (target: NativeChatDiffTarget) => { beginNavigation() readerLeavesEnd() - if (target.subagentSections) { - openSubagentSections(target.subagentSections) - } issue({ kind: 'diff', target: { ...target, requestId: nextRequestId() } }) }, - [beginNavigation, issue, nextRequestId, readerLeavesEnd, openSubagentSections] - ) - const revealSubagent = useCallback( - (agentId: string) => { - beginNavigation() - readerLeavesEnd() - startHistoryJump({ kind: 'subagent', agentId }) - }, - [beginNavigation, readerLeavesEnd, startHistoryJump] + [beginNavigation, issue, nextRequestId, readerLeavesEnd] ) + useEffect(() => { + if (subagentId !== null && isVisible) { + startHistoryJump({ kind: 'subagent', agentId: subagentId }) + } + }, [isVisible, startHistoryJump, subagentId]) const jumpToLatest = useCallback(() => { beginNavigation() scrollToBottom() @@ -193,18 +159,10 @@ export function useNativeChatNavigation({ onActivate: rail.onActivate, release: issue }) - useNativeChatSubagentLanding({ - request: request.subagentJump, - landing: request.subagentLanding, - scrollRef, - scrollMessageToTop, - release: issue - }) return { beginNavigation, selectRailItem, revealDiff, - revealSubagent, jumpToLatest, pendingRailId: historyJump.pending?.kind === 'rail' ? historyJump.pending.id : null } diff --git a/src/renderer/src/components/native-chat/viewport/new-rows/native-chat-new-rows-marker.ts b/src/renderer/src/components/native-chat/viewport/new-rows/native-chat-new-rows-marker.ts index e31d5e1d225..b78d3c768a3 100644 --- a/src/renderer/src/components/native-chat/viewport/new-rows/native-chat-new-rows-marker.ts +++ b/src/renderer/src/components/native-chat/viewport/new-rows/native-chat-new-rows-marker.ts @@ -14,7 +14,7 @@ import type { NativeChatTranscriptSlot } from '../../conversation/slots/native-c /** Use journal positions for conversation rows, including folded-turn bars; terminal-backed rows have none and remain unmarked. */ function rowPosition(slot: NativeChatTranscriptSlot): AgentJournalPosition | undefined { - return slot.kind === 'message' && slot.depth === 0 && (slot.drawsMessage || slot.statusAbove) + return slot.kind === 'message' && (slot.drawsMessage || slot.statusAbove) ? slot.message.journalPosition : undefined } diff --git a/src/renderer/src/components/native-chat/viewport/rail/native-chat-message-rail-items.ts b/src/renderer/src/components/native-chat/viewport/rail/native-chat-message-rail-items.ts index 2707122d585..03cc15c7650 100644 --- a/src/renderer/src/components/native-chat/viewport/rail/native-chat-message-rail-items.ts +++ b/src/renderer/src/components/native-chat/viewport/rail/native-chat-message-rail-items.ts @@ -72,10 +72,9 @@ export function buildNativeChatRailItems( ): readonly NativeChatRailItem[] { const items: NativeChatRailItem[] = [] for (const [slotIndex, slot] of slots.entries()) { - // Exclude withdrawn sends and subagent prompts so rail contents do not depend on section expansion. + // Exclude withdrawn sends. if ( slot.kind !== 'message' || - slot.depth !== 0 || slot.message.role !== 'user' || slot.message.from !== undefined || slot.message.stoppedBeforeStart === true diff --git a/src/renderer/src/components/native-chat/viewport/virtualization/native-chat-row-height-estimate.ts b/src/renderer/src/components/native-chat/viewport/virtualization/native-chat-row-height-estimate.ts index 2cc1c228f09..2d55cf847bf 100644 --- a/src/renderer/src/components/native-chat/viewport/virtualization/native-chat-row-height-estimate.ts +++ b/src/renderer/src/components/native-chat/viewport/virtualization/native-chat-row-height-estimate.ts @@ -31,8 +31,6 @@ export type NativeChatRowChromeMetrics = { openedPullRequestCount?: number /** Folded prose/tools paint only a roster and must not reserve their expanded height. */ folded?: boolean - /** Inside a subagent's section, where assistant prose keeps its controls in flow. */ - inSubagentSection?: boolean } export type NativeChatRowTypography = { @@ -56,7 +54,7 @@ const TOOL_RUN_CHROME_PX = 16 const COLLAPSED_REASONING_PX = 24 const COMPACT_AGENT_MESSAGE_PX = 38 const SUBAGENT_ROW_PX = 32 -export const NATIVE_CHAT_SUBAGENT_SECTION_HEAD_PX = SUBAGENT_ROW_PX +export const NATIVE_CHAT_SUBAGENT_HEAD_PX = SUBAGENT_ROW_PX const STATUS_ROW_PX = 28 const TURN_DIFF_PX = 28 /** The opened-PR card: its heading, then one row per pull request. */ @@ -190,13 +188,6 @@ export function estimateNativeChatRowHeight( if (content.role === 'user' && content.textLines > 0) { height += USER_BUBBLE_CHROME_PX * scale } - if ( - chrome.inSubagentSection === true && - content.role === 'assistant' && - content.textLines > 0 - ) { - height += AGENT_CONTROLS_OVERHANG_PX * scale - } if (content.imageCount > 0) { height += IMAGE_STRIP_PX * scale } diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 6a175ad4c80..028197ea77c 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -21092,7 +21092,10 @@ "started_one": "Kicked off {{count}} subagent", "started_other": "Kicked off {{count}} subagents", "ran_one": "Ran {{count}} subagent", - "ran_other": "Ran {{count}} subagents" + "ran_other": "Ran {{count}} subagents", + "open": "Open subagent", + "backToMain": "Back to main agent", + "mainAgent": "Main agent" }, "rewind": { "unsupported": "This chat can't go back to an earlier message.", diff --git a/src/renderer/src/lib/agent-session/navigation/claude-agent-row-view.test.ts b/src/renderer/src/lib/agent-session/navigation/claude-agent-row-view.test.ts new file mode 100644 index 00000000000..d4066a01656 --- /dev/null +++ b/src/renderer/src/lib/agent-session/navigation/claude-agent-row-view.test.ts @@ -0,0 +1,30 @@ +// @vitest-environment happy-dom + +import { act, renderHook } from '@testing-library/react' +import { describe, expect, it, vi } from 'vitest' +import type { DashboardAgentRow } from '@/components/dashboard/useDashboardData' +import { useNativeChatOpenSubagent } from '@/components/native-chat/subagents/native-chat-open-subagent' +import { viewClaudeAgentFromRow } from './claude-agent-row-view' + +vi.mock('@/store/index', () => ({ + useAppStore: { getState: () => ({ agentStatusByPaneKey: {} }) } +})) + +function childRow(agentType: string): DashboardAgentRow { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the routing reads only these fields of the row. + return { + paneKey: 'tab-1:chat\u0000subagent:row-1', + activationPaneKey: 'tab-1:chat', + rowSource: 'subagent', + entry: { agentType, structuredHostOwned: true, paneKey: 'tab-1:chat' }, + childRow: { id: 'row-1', providerId: 'thread-child' } + } as unknown as DashboardAgentRow +} + +describe('viewClaudeAgentFromRow', () => { + it("opens a chat pane's subagent row in that chat's subagent view, for any agent", async () => { + const { result } = renderHook(() => useNativeChatOpenSubagent('tab-1:chat')) + await act(() => viewClaudeAgentFromRow(childRow('codex'))) + expect(result.current).toBe('thread-child') + }) +}) diff --git a/src/renderer/src/lib/agent-session/navigation/claude-agent-row-view.ts b/src/renderer/src/lib/agent-session/navigation/claude-agent-row-view.ts index 2adf21654c5..155a24a4270 100644 --- a/src/renderer/src/lib/agent-session/navigation/claude-agent-row-view.ts +++ b/src/renderer/src/lib/agent-session/navigation/claude-agent-row-view.ts @@ -10,6 +10,7 @@ import { findActiveRuntimeTerminal } from '../messaging/terminal/active-agent-no import { parsePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' import { authorityKey } from '../../../../../shared/host-authority' import type { ClaudeAgentViewResult } from '../../../../../shared/claude-agent-view' +import { openNativeChatSubagent } from '@/components/native-chat/subagents/native-chat-open-subagent' const pendingViews = new Map() @@ -35,10 +36,16 @@ export async function viewClaudeAgentFromRow(agent: DashboardAgentRow): Promise< const state = useAppStore.getState() const paneKey = agent.activationPaneKey ?? agent.paneKey const parent = state.agentStatusByPaneKey[paneKey] ?? agent.entry - if (parent.agentType !== 'claude' || parent.structuredHostOwned) { + const child = agent.rowSource === 'subagent' + if (parent.structuredHostOwned) { + // A chat pane opens the child in its own view, for any agent; the parent row shows the main agent. + const agentId = child ? agent.childRow?.providerId : undefined + openNativeChatSubagent(paneKey, agentId ?? null) + return + } + if (parent.agentType !== 'claude') { return } - const child = agent.rowSource === 'subagent' let parentDestination = !child || opensClaudeParentConversation(agent) // A newer click owns this pane even while terminal resolution or a local RPC is still pending. pendingViews.get(paneKey)?.abort()