Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions packages/cli/src/ui/components/messages/ToolGroupMessage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,7 @@ export const ToolGroupMessage: React.FC<ToolGroupMessageProps> = ({
availableTerminalHeight,
contentWidth,
isFocused = true,
// `isPending` stays on the props interface for upstream compat
// (HistoryItemDisplay et al. forward it) but the group body no
// longer reads it. Skip the destructure so TS catches accidental
// re-introductions of dead state.
isPending = false,
activeShellPtyId,
Comment thread
wenshao marked this conversation as resolved.
Resolved
embeddedShellFocused,
memoryWriteCount,
Expand Down Expand Up @@ -327,6 +324,7 @@ export const ToolGroupMessage: React.FC<ToolGroupMessageProps> = ({
isAgentWithPendingConfirmation(tool.resultDisplay)
Comment thread
wenshao marked this conversation as resolved.
Resolved
Comment thread
wenshao marked this conversation as resolved.
Resolved
}
isFocused={isSubagentFocused}
isPending={isPending}
Comment thread
wenshao marked this conversation as resolved.
Resolved
/>
</Box>
{tool.status === ToolCallStatus.Confirming &&
Expand Down
32 changes: 31 additions & 1 deletion packages/cli/src/ui/components/messages/ToolMessage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,7 @@ describe('<ToolMessage />', () => {
terminateReason?: string;
};
isFocused?: boolean;
isPending?: boolean;
}): ToolMessageProps => {
const resultDisplay = {
type: 'task_execution' as const,
Expand All @@ -331,6 +332,7 @@ describe('<ToolMessage />', () => {
callId: 'gated-task-call',
forceShowResult: true, // mirror ToolGroupMessage's forceShowResult
isFocused: overrides.isFocused,
isPending: overrides.isPending,
};
};

Expand All @@ -355,7 +357,7 @@ describe('<ToolMessage />', () => {
expect(output).not.toContain('Queued approval:');
});

it('completed subagent → renders a one-line scrollback summary', () => {
it('committed (`!isPending`) terminal subagent → renders a one-line scrollback summary', () => {
// The verbose 15-row inline frame is retired (it caused
// scrollback flicker), but the conversation history needs to
// keep a permanent record after the panel's 8s window expires
Expand All @@ -370,6 +372,7 @@ describe('<ToolMessage />', () => {
taskPrompt: 'Already done',
status: 'completed',
},
isPending: false,
})}
/>,
StreamingState.Idle,
Expand All @@ -384,6 +387,33 @@ describe('<ToolMessage />', () => {
expect(output).not.toContain('MockApprovalPrompt');
});

it('live (`isPending`) terminal subagent → no scrollback summary (panel owns the row)', () => {
// While the parent turn is still in `pendingHistoryItems`,
// LiveAgentPanel below the composer renders the synthesized /
// terminal row — emitting the summary here too would duplicate
// it visually. The summary fires only when the tool message
// commits to <Static> (`isPending=false`), guaranteeing exactly
// one inline copy in the eventual scrollback record.
const { lastFrame } = renderWithContext(
<ToolMessage
{...buildProps({
data: {
subagentName: 'live-terminal',
taskDescription: 'Just finished mid-turn',
taskPrompt: 'Mid-turn',
status: 'completed',
},
isPending: true,
})}
/>,
StreamingState.Responding,
);
const output = lastFrame() ?? '';
// No inline summary — the panel renders this row instead.
expect(output).not.toContain('✔');
expect(output).not.toContain('Just finished mid-turn');
});

it('failed subagent → renders summary with terminate reason', () => {
const { lastFrame } = renderWithContext(
<ToolMessage
Expand Down
39 changes: 35 additions & 4 deletions packages/cli/src/ui/components/messages/ToolMessage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -262,14 +262,30 @@ const PlanResultRenderer: React.FC<{
* single-line scrollback summary so the conversation history retains
* a permanent record after the panel's 8s window expires and the
* dialog closes. Format: `<icon> <type>: <description> · N tools · Xs · Yk tokens`.
*
* The committed-phase summary is gated on `!isPending` — without the
* gate the summary would also paint into `pendingHistoryItems`
* (the live area) the moment a subagent terminates, duplicating the
* row LiveAgentPanel already renders synthesized below the composer.
* `isPending=true` means we're still in the live area; `isPending=false`
* means the item has committed to `<Static>` and the summary is the
* one and only place the user can find this run after the panel evicts.
*/
const SubagentExecutionRenderer: React.FC<{
data: AgentResultDisplay;
availableHeight?: number;
childWidth: number;
config: Config;
isFocused?: boolean;
}> = ({ data, availableHeight, childWidth, config, isFocused }) => {
isPending?: boolean;
}> = ({
data,
availableHeight,
childWidth,
config,
isFocused,
isPending = false,
}) => {
if (data.pendingConfirmation && isFocused) {
const agentLabel = data.subagentName || 'agent';
return (
Comment thread
wenshao marked this conversation as resolved.
Resolved
Expand Down Expand Up @@ -308,10 +324,14 @@ const SubagentExecutionRenderer: React.FC<{
// 8s visibility window expires (LiveAgentPanel evicts terminal rows;
// BackgroundTasksDialog only retains them while open). Skip
// `running` / `background` since the panel + dialog cover those.
// ALSO skip while `isPending` — the live area is already painted by
// the panel, so emitting the summary into `pendingHistoryItems` would
// duplicate the row visually until the parent turn commits.
if (
data.status === 'completed' ||
data.status === 'failed' ||
data.status === 'cancelled'
!isPending &&
(data.status === 'completed' ||
data.status === 'failed' ||
data.status === 'cancelled')
) {
return <SubagentScrollbackSummary data={data} />;
}
Expand Down Expand Up @@ -478,6 +498,15 @@ export interface ToolMessageProps extends IndividualToolCallDisplay {
* sibling subagents render a dim "Queued approval" marker instead.
*/
isFocused?: boolean;
/**
* True while the tool message is rendered inside `pendingHistoryItems`
* (live area), false once committed to `<Static>`. Used by the
* subagent renderer to gate the scrollback summary so the live area
* stays panel-only — without this gate the summary would duplicate
* the synthesized row LiveAgentPanel already renders below the
* composer the moment a subagent terminates.
Comment thread
wenshao marked this conversation as resolved.
Resolved
*/
isPending?: boolean;
}

export const ToolMessage: React.FC<ToolMessageProps> = ({
Expand All @@ -495,6 +524,7 @@ export const ToolMessage: React.FC<ToolMessageProps> = ({
config,
forceShowResult,
isFocused,
isPending,
executionStartTime,
}) => {
const settings = useSettings();
Expand Down Expand Up @@ -649,6 +679,7 @@ export const ToolMessage: React.FC<ToolMessageProps> = ({
childWidth={innerWidth}
config={config}
isFocused={isFocused}
isPending={isPending}
/>
)}
{effectiveDisplayRenderer.type === 'diff' && (
Expand Down
78 changes: 68 additions & 10 deletions packages/core/src/agents/background-tasks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -999,7 +999,7 @@ describe('BackgroundTaskRegistry', () => {
}
});

it('unregisterForeground removes the entry and emits a status change', () => {
it('unregisterForeground removes the entry and emits status change twice (pre + post delete)', () => {
const onStatusChange = vi.fn();
registry.setStatusChangeCallback(onStatusChange);

Expand All @@ -1016,7 +1016,56 @@ describe('BackgroundTaskRegistry', () => {
registry.unregisterForeground('fg-5');

expect(registry.get('fg-5')).toBeUndefined();
expect(onStatusChange).toHaveBeenCalledTimes(1);
// Two emits: the pre-delete one matches the
// complete/fail/cancel/finalize ordering so callbacks that
// re-read `registry.get(agentId)` see the entry; the post-delete
// one lets snapshot-based views (`useBackgroundTaskView` calling
// `registry.getAll()`) observe the entry-less state without
// needing per-tick reconciliation. Both fire synchronously, so
// React batches the resulting setState calls into one re-render.
expect(onStatusChange).toHaveBeenCalledTimes(2);
});

it('unregisterForeground post-delete emit observes registry-less state', () => {
// The second emit is the contract that lets snapshot consumers
// (e.g. BackgroundTasksDialog list mode) drop ghost rows for
// foreground subagents that just unregistered. Without it the
// snapshot would freeze at the pre-delete entry-as-running state
// until the next unrelated transition.
registry.register({
agentId: 'fg-post-delete',
description: 'sync agent',
flavor: 'foreground',
status: 'running',
startTime: Date.now(),
abortController: new AbortController(),
});

const observations: Array<{
getAtCallback: BackgroundTaskEntry | undefined;
getAllCount: number;
}> = [];
registry.setStatusChangeCallback((entry) => {
if (entry?.agentId !== 'fg-post-delete') return;
observations.push({
getAtCallback: registry.get('fg-post-delete'),
getAllCount: registry
.getAll()
.filter((e) => e.agentId === 'fg-post-delete').length,
});
});

registry.unregisterForeground('fg-post-delete');

expect(observations).toHaveLength(2);
// First emit (pre-delete): entry still in the registry.
expect(observations[0].getAtCallback?.agentId).toBe('fg-post-delete');
expect(observations[0].getAllCount).toBe(1);
// Second emit (post-delete): entry gone. This is what
// `useBackgroundTaskView.refresh()` sees, so its merged
// entries no longer include the agent.
expect(observations[1].getAtCallback).toBeUndefined();
expect(observations[1].getAllCount).toBe(0);
});

it('unregisterForeground throws if asked to remove a background entry', () => {
Expand Down Expand Up @@ -1078,10 +1127,15 @@ describe('BackgroundTaskRegistry', () => {
expect(onRegister.mock.calls[0]![0].agentId).toBe('bg-fires-register-cb');
});

it('unregisterForeground emits status change before removing the entry', () => {
// Mirrors the ordering used by complete/fail/cancel/finalize so a
// statusChange callback that re-reads `registry.get(agentId)` from
// inside the callback sees the entry across every terminal path.
it('unregisterForeground first emit sees entry; later emits see registry-less state', () => {
// The first emit mirrors the ordering used by
// complete/fail/cancel/finalize so a statusChange callback that
// re-reads `registry.get(agentId)` from inside the callback sees
// the entry across every terminal path. The second emit (added
// for snapshot consumers like `useBackgroundTaskView`) sees the
// registry-less state — both paths are documented + tested
// separately so a future refactor that collapsed the two emits
// would surface here.
registry.register({
agentId: 'fg-unregister-order',
description: 'sync agent',
Expand All @@ -1091,17 +1145,21 @@ describe('BackgroundTaskRegistry', () => {
abortController: new AbortController(),
});

let observedFromCallback: BackgroundTaskEntry | undefined;
const observed: Array<BackgroundTaskEntry | undefined> = [];
registry.setStatusChangeCallback((entry) => {
if (entry?.agentId === 'fg-unregister-order') {
observedFromCallback = registry.get(entry.agentId);
observed.push(registry.get(entry.agentId));
}
});

registry.unregisterForeground('fg-unregister-order');

expect(observedFromCallback).toBeDefined();
expect(observedFromCallback!.agentId).toBe('fg-unregister-order');
expect(observed).toHaveLength(2);
// First emit: pre-delete, callback sees the entry.
expect(observed[0]).toBeDefined();
expect(observed[0]!.agentId).toBe('fg-unregister-order');
// Second emit: post-delete, callback sees the registry-less state.
expect(observed[1]).toBeUndefined();
expect(registry.get('fg-unregister-order')).toBeUndefined();
});

Expand Down
17 changes: 14 additions & 3 deletions packages/core/src/agents/background-tasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,11 +275,22 @@ export class BackgroundTaskRegistry {
`Background entries must terminate via complete/fail/finalizeCancelled.`,
);
}
// Emit before delete so any future BackgroundStatusChangeCallback that
// re-reads `registry.get(agentId)` from inside the callback sees the
// entry, matching the ordering used by complete/fail/cancel/finalize.
// Emit BEFORE delete so callbacks that re-read `registry.get(agentId)`
// from inside see the entry — matches the ordering used by
// complete/fail/cancel/finalize. This is the "agent reached its
// last live state" signal.
this.emitStatusChange(entry);
this.agents.delete(agentId);
Comment thread
wenshao marked this conversation as resolved.
Resolved
Comment thread
wenshao marked this conversation as resolved.
Resolved
// Emit AGAIN after delete so views that re-snapshot the registry
// on statusChange (e.g. `useBackgroundTaskView.refresh()` calling
// `registry.getAll()`) see the entry-less state and stop showing
// a stale "running" row. Without this second emit the snapshot
// freezes at the pre-delete state until the next unrelated
// statusChange event, leaving ghost rows in `BackgroundTasksDialog`
// list mode and forcing each consumer to re-implement registry
// re-pull. The two emits are batched by React's setState batching,
// so consumers only re-render once.
Comment thread
wenshao marked this conversation as resolved.
Resolved
Comment thread
wenshao marked this conversation as resolved.
Resolved
this.emitStatusChange(entry);
debugLogger.info(`Unregistered foreground agent: ${agentId}`);
Comment on lines 303 to +304
}

Expand Down
Loading