Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
41 changes: 40 additions & 1 deletion packages/web-shell/client/App.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,7 @@ const {
}) => void;
isResponding?: boolean;
activeTurnStartedAt?: number;
terminalBackgroundShellTaskIds?: ReadonlySet<string>;
} | null,
latestBtwMessageProps: null as {
question: string;
Expand Down Expand Up @@ -800,6 +801,7 @@ vi.mock('./components/MessageList', async () => {
}) => void;
isResponding?: boolean;
activeTurnStartedAt?: number;
terminalBackgroundShellTaskIds?: ReadonlySet<string>;
welcomeHeader?: React.ReactNode;
},
ref: React.ForwardedRef<{ scrollToBottom: () => void }>,
Expand Down Expand Up @@ -1779,6 +1781,13 @@ describe('task activity key', () => {
status: 'completed',
args: { is_background: true },
},
{
callId: 'promoted-shell',
toolName: 'run_shell_command',
status: 'completed',
args: { is_background: false },
rawOutput: 'Promoted to background: bg_1234abcd',
},
{
callId: 'monitor-call',
toolName: 'monitor',
Expand All @@ -1790,7 +1799,7 @@ describe('task activity key', () => {
] satisfies Message[];

expect(getTaskActivityKey(messages)).toBe(
'shell-call:in_progress|agent-call:pending|nested-shell:completed|completed-shell:completed|monitor-call:completed',
'shell-call:in_progress|agent-call:pending|nested-shell:completed|completed-shell:completed|promoted-shell:completed|monitor-call:completed',
);
});

Expand Down Expand Up @@ -7816,6 +7825,36 @@ describe('App session callbacks', () => {
expect(testState.latestStatusBarTasks).toEqual([monitor]);
});

it('passes terminal background shell task ids to the message list', async () => {
const running: DaemonSessionShellTaskStatus = {
kind: 'shell',
id: 'shell-running',
label: 'Running shell',
description: 'Running shell',
status: 'running',
startTime: 1_000,
runtimeMs: 5_000,
command: 'npm run dev',
cwd: '/tmp/project',
};
testState.backgroundTasks = [
running,
{
...running,
id: 'shell-completed',
status: 'completed',
},
];

renderApp();
await flush();

expect([
...(testState.latestMessageListProps?.terminalBackgroundShellTaskIds ??
[]),
]).toEqual(['shell-completed']);
});

it('controls the built-in chat header actions through header items', () => {
const { container } = renderApp({
header: { items: ['environment'] },
Expand Down
27 changes: 26 additions & 1 deletion packages/web-shell/client/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,10 @@ import {
import { isDefinitelyRejectedPromptAdmission } from './utils/promptAdmission';
import { base64ToBlob } from './utils/base64';
import type { ACPToolCall, Message, PermissionRequest } from './adapters/types';
import { isBackgroundSubAgentToolCall } from './adapters/toolClassification';
import {
backgroundShellTaskId,
isBackgroundSubAgentToolCall,
} from './adapters/toolClassification';
import {
computeTodoDetails,
computeTodoTimeline,
Expand Down Expand Up @@ -1313,6 +1316,7 @@ function parseRenameArgument(
function isBackgroundTaskToolCall(tool: ACPToolCall): boolean {
const name = tool.toolName.toLowerCase();
if (name === 'monitor') return true;
if (backgroundShellTaskId(tool) !== undefined) return true;
if (tool.args?.is_background !== true) return false;
return (
name === 'shell' ||
Expand Down Expand Up @@ -4014,6 +4018,24 @@ export function App({
connection.status === 'connected',
backgroundTasksRefreshTrigger,
);
const terminalBackgroundShellTaskIdsKey = useMemo(
() =>
sessionTasks
.filter((task) => task.kind === 'shell' && task.status !== 'running')
.map((task) => task.id)
.join(','),
[sessionTasks],
);
// Preserve Set identity when polling returns an equivalent task snapshot.
const terminalBackgroundShellTaskIds = useMemo(
() =>
new Set(
terminalBackgroundShellTaskIdsKey
? terminalBackgroundShellTaskIdsKey.split(',')
: [],
),
[terminalBackgroundShellTaskIdsKey],
);
const environmentAgentTasks = useMemo(
() => getEnvironmentAgentTasks(messages, sessionTasks),
[messages, sessionTasks],
Expand Down Expand Up @@ -12378,6 +12400,9 @@ export function App({
<MessageList
ref={messageListRef}
messages={displayMessages}
terminalBackgroundShellTaskIds={
terminalBackgroundShellTaskIds
}
pendingApproval={pendingToolApproval}
onShowContextDetail={handleShowContextDetail}
loadingTranscript={connection.loadingTranscript}
Expand Down
51 changes: 51 additions & 0 deletions packages/web-shell/client/adapters/toolClassification.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest';
import type { ACPToolCall } from './types';
import {
backgroundShellTaskId,
isActiveToolStatus,
isBackgroundSubAgentToolCall,
} from './toolClassification';
Expand Down Expand Up @@ -95,3 +96,53 @@ describe('isBackgroundSubAgentToolCall', () => {
).toBe(true);
});
});

describe('backgroundShellTaskId', () => {
it.each([
['Background shell bg_1234abcd started.', 'bg_1234abcd'],
['background shell bg_1234abcd started.', 'bg_1234abcd'],
['Promoted to background: bg_abcd-1234', 'bg_abcd-1234'],
])('extracts the task id from %s', (rawOutput, taskId) => {
expect(
backgroundShellTaskId({
callId: 'shell-1',
toolName: 'shell',
status: 'completed',
rawOutput,
}),
).toBe(taskId);
});

it('ignores failed shell calls', () => {
expect(
backgroundShellTaskId({
callId: 'shell-1',
toolName: 'shell',
status: 'failed',
rawOutput: 'Background shell bg_1234abcd started.',
}),
).toBeUndefined();
});

it('ignores non-shell tool names', () => {
expect(
backgroundShellTaskId({
callId: 'read-1',
toolName: 'Read',
status: 'completed',
rawOutput: 'Background shell bg_1234abcd started.',
}),
).toBeUndefined();
});

it('ignores non-string rawOutput', () => {
expect(
backgroundShellTaskId({
callId: 'shell-1',
toolName: 'shell',
status: 'completed',
rawOutput: { taskId: 'bg_1234abcd' },
}),
).toBeUndefined();
});
});
21 changes: 21 additions & 0 deletions packages/web-shell/client/adapters/toolClassification.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,24 @@ export function isBackgroundSubAgentToolCall(tool: ACPToolCall): boolean {
defaultsToBackground
);
}

const BACKGROUND_SHELL_NAMES = new Set([
'shell',
'bash',
'run_shell_command',
'exec',
]);
const BACKGROUND_SHELL_ID_PATTERN =
/^(?:Background shell|Promoted to background:)\s+(bg_[\w-]+)/i;

export function backgroundShellTaskId(tool: ACPToolCall): string | undefined {
if (
tool.status === 'failed' ||
!BACKGROUND_SHELL_NAMES.has(tool.toolName.toLowerCase())
) {
return undefined;
}
return typeof tool.rawOutput === 'string'
? BACKGROUND_SHELL_ID_PATTERN.exec(tool.rawOutput)?.[1]
: undefined;
}
133 changes: 133 additions & 0 deletions packages/web-shell/client/components/MessageList.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,36 @@ function makeBackgroundNotification(id: string, toolUseId?: string): Message {
};
}

function makeBackgroundShellToolGroup(
id: string,
taskId: string,
): Extract<Message, { role: 'tool_group' }> {
return {
id,
role: 'tool_group',
tools: [
{
callId: `call-${id}`,
toolName: 'shell',
status: 'completed',
args: { command: 'npm test', is_background: true },
rawOutput: `Background shell ${taskId} started.`,
},
],
};
}

function makeBackgroundShellNotification(id: string, taskId: string): Message {
return {
id,
role: 'system',
content: 'Background shell completed.',
variant: 'info',
source: 'background_notification',
data: { kind: 'shell', taskId, status: 'completed' },
};
}

function makePlanMessage(id: string): Message {
return { id, role: 'plan', todos: [] };
}
Expand Down Expand Up @@ -1101,6 +1131,7 @@ function collapseItems(
pendingApprovalCallId: string | null;
backgroundSummaryGraceActive: boolean;
waitForUnmatchedAgentCompletions: boolean;
terminalBackgroundShellTaskIds: ReadonlySet<string>;
automaticallyExpandedAgentKeys: ReadonlySet<string>;
enabled: boolean;
}> = {},
Expand All @@ -1112,6 +1143,7 @@ function collapseItems(
backgroundSummaryGraceActive: opts.backgroundSummaryGraceActive ?? true,
waitForUnmatchedAgentCompletions:
opts.waitForUnmatchedAgentCompletions ?? true,
terminalBackgroundShellTaskIds: opts.terminalBackgroundShellTaskIds,
automaticallyExpandedAgentKeys: opts.automaticallyExpandedAgentKeys,
enabled: opts.enabled ?? true,
});
Expand Down Expand Up @@ -1899,6 +1931,107 @@ describe('applyTurnCollapse', () => {
expect(collapseOf(out, 'u2')?.collapsed).toBe(true);
});

it('keeps a completed turn open while its background shell is running', () => {
const items = groupParallelAgents([
makeUserMessage('u1'),
makeBackgroundShellToolGroup('shell', 'bg_1234abcd'),
makeAssistantMessage('launched'),
]);

const turn = collapseOf(collapseItems(items), 'u1');
expect(turn?.collapsed).toBe(false);
expect(turn?.liveStartedAt).toBeUndefined();
});

it('uses a terminal task snapshot when the shell notification is missing', () => {
const items = groupParallelAgents([
makeUserMessage('u1'),
makeBackgroundShellToolGroup('shell', 'bg_1234abcd'),
makeAssistantMessage('launched'),
]);

const out = collapseItems(items, {
terminalBackgroundShellTaskIds: new Set(['bg_1234abcd']),
});

expect(collapseOf(out, 'u1')?.collapsed).toBe(true);
});

it('releases the launch turn when its background shell notification arrives', () => {
const running = [
makeUserMessage('u1'),
makeBackgroundShellToolGroup('shell', 'bg_1234abcd'),
makeAssistantMessage('launched'),
];
const notified = [
...running,
makeBackgroundShellNotification('shell-done', 'bg_1234abcd'),
];
const summarized = [...notified, makeAssistantMessage('summary')];

expect(
collapseOf(collapseItems(groupParallelAgents(running)), 'u1')?.collapsed,
).toBe(false);
expect(
collapseOf(collapseItems(groupParallelAgents(notified)), 'u1')?.collapsed,
).toBe(false);
expect(
collapseOf(collapseItems(groupParallelAgents(summarized)), 'u1')
?.collapsed,
).toBe(true);
});

it('matches a shell completion back to its original turn', () => {
const running = [
makeUserMessage('u1'),
makeBackgroundShellToolGroup('shell', 'bg_1234abcd'),
makeAssistantMessage('launched'),
makeUserMessage('u2'),
makeMultiToolGroup('other'),
makeAssistantMessage('other-answer'),
];
const completed = [
...running,
makeBackgroundShellNotification('shell-done', 'bg_1234abcd'),
makeAssistantMessage('summary'),
];

const before = collapseItems(groupParallelAgents(running));
expect(collapseOf(before, 'u1')?.collapsed).toBe(false);
expect(collapseOf(before, 'u2')?.collapsed).toBe(true);

const after = collapseItems(groupParallelAgents(completed));
expect(collapseOf(after, 'u1')?.collapsed).toBe(true);
expect(collapseOf(after, 'u2')?.collapsed).toBe(true);
});

it('ignores malformed background shell notifications', () => {
const running = [
makeUserMessage('u1'),
makeBackgroundShellToolGroup('shell', 'bg_1234abcd'),
makeAssistantMessage('launched'),
];
const malformed = [
{
...makeBackgroundShellNotification('bad-data', 'bg_1234abcd'),
data: 'oops',
},
{
...makeBackgroundShellNotification('bad-kind', 'bg_1234abcd'),
data: { kind: 'agent', taskId: 'bg_1234abcd' },
},
{
...makeBackgroundShellNotification('bad-task-id', 'bg_1234abcd'),
data: { kind: 'shell', taskId: 42 },
},
];

for (const notification of malformed) {
const items = groupParallelAgents([...running, notification]);
expect(collapseOf(collapseItems(items), 'u1')?.collapsed).toBe(false);
}
});

it('still allows manually collapsing a turn with no final answer', () => {
const items = groupParallelAgents([
makeUserMessage('u1'),
Expand Down
Loading
Loading