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
151 changes: 151 additions & 0 deletions packages/cli/src/ui/hooks/useGeminiStream.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,8 @@ describe('useGeminiStream', () => {
getEmitToolUseSummaries: vi.fn(() => false),
getFastModel: vi.fn(() => undefined),
getBackgroundTaskRegistry: vi.fn(() => ({
canStartBackgroundAgent: vi.fn(() => true),
getMaxConcurrentBackgroundAgents: vi.fn(() => 10),
setNotificationCallback: vi.fn(),
})),
getBackgroundShellRegistry: vi.fn(() => mockBackgroundShellRegistry),
Expand Down Expand Up @@ -1266,6 +1268,155 @@ describe('useGeminiStream', () => {
);
});

it('waits for a background agent when its launch exhausts capacity', async () => {
const responseParts: Part[] = [
{
functionResponse: {
id: 'agent-call',
name: 'agent',
response: { result: 'Background agent launched successfully.' },
},
},
];
let notificationCallback:
| ((displayText: string, modelText: string) => void)
| undefined;
const getMaxConcurrentBackgroundAgents = vi.fn(() => 1);
mockConfig.getBackgroundTaskRegistry = vi.fn(() => ({
canStartBackgroundAgent: vi.fn(() => false),
getMaxConcurrentBackgroundAgents,
setNotificationCallback: vi.fn((callback) => {
notificationCallback = callback;
}),
})) as Config['getBackgroundTaskRegistry'];

let capturedOnComplete:
| ((completedTools: TrackedToolCall[]) => Promise<void>)
| null = null;
mockUseReactToolScheduler.mockImplementation((onComplete) => {
capturedOnComplete = onComplete;
return [[], mockScheduleToolCalls, mockMarkToolsAsSubmitted];
});

const client = new MockedGeminiClientClass(mockConfig);
renderHook(() =>
useGeminiStream(
client,
[],
mockAddItem,
mockConfig,
true,
mockLoadedSettings,
mockOnDebugMessage,
mockHandleSlashCommand,
false,
() => 'vscode' as EditorType,
() => {},
() => Promise.resolve(),
false,
() => {},
() => {},
() => {},
() => {},
80,
24,
),
);

await waitFor(() => expect(notificationCallback).toBeDefined());
await act(async () => {
await capturedOnComplete?.([
{
request: {
callId: 'agent-call',
name: 'agent',
args: { run_in_background: true },
isClientInitiated: false,
prompt_id: 'prompt-id-agent',
},
status: 'success',
responseSubmittedToGemini: false,
response: {
callId: 'agent-call',
responseParts,
errorType: undefined,
resultDisplay: {
type: 'task_execution',
subagentName: 'researcher',
taskDescription: 'Research',
taskPrompt: 'Inspect the code',
status: 'background',
},
},
tool: { displayName: 'Agent' },
invocation: {
getDescription: () => 'Research',
} as unknown as AnyToolInvocation,
} as TrackedCompletedToolCall,
]);
});

expect(mockMarkToolsAsSubmitted).toHaveBeenCalledWith(['agent-call']);
expect(client.addHistory).toHaveBeenCalledWith({
role: 'user',
parts: responseParts,
});
expect(mockSendMessageStream).not.toHaveBeenCalled();

act(() => {
notificationCallback?.(
'Background agent completed.',
'<task-notification>done</task-notification>',
);
});

await waitFor(() => expect(mockSendMessageStream).toHaveBeenCalledOnce());
expect(mockSendMessageStream).toHaveBeenCalledWith(
'<task-notification>done</task-notification>',
expect.any(AbortSignal),
expect.any(String),
expect.objectContaining({ type: SendMessageType.Notification }),
);

mockSendMessageStream.mockClear();
client.addHistory.mockClear();
getMaxConcurrentBackgroundAgents.mockReturnValue(2);
await act(async () => {
await capturedOnComplete?.([
{
request: {
callId: 'agent-call-2',
name: 'agent',
args: { run_in_background: true },
isClientInitiated: false,
prompt_id: 'prompt-id-agent-2',
},
status: 'success',
responseSubmittedToGemini: false,
response: {
callId: 'agent-call-2',
responseParts,
errorType: undefined,
resultDisplay: {
type: 'task_execution',
subagentName: 'researcher',
taskDescription: 'Research',
taskPrompt: 'Inspect the code',
status: 'background',
},
},
tool: { displayName: 'Agent' },
invocation: {
getDescription: () => 'Research',
} as unknown as AnyToolInvocation,
} as TrackedCompletedToolCall,
]);
});

await waitFor(() => expect(mockSendMessageStream).toHaveBeenCalledOnce());
expect(client.addHistory).not.toHaveBeenCalled();
});

it('records mid-turn queued user messages after tool results accept them', async () => {
const queuedPrompt = 'save the logs locally first';
const recordMidTurnUserMessage = vi.fn();
Expand Down
21 changes: 21 additions & 0 deletions packages/cli/src/ui/hooks/useGeminiStream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3463,6 +3463,27 @@ export const useGeminiStream = (
return;
}

const backgroundTaskRegistry = config.getBackgroundTaskRegistry();
const backgroundLaunchExhaustedCapacity =
backgroundTaskRegistry.getMaxConcurrentBackgroundAgents() === 1 &&
!backgroundTaskRegistry.canStartBackgroundAgent() &&
geminiTools.some((toolCall) => {
const display = toolCall.response.resultDisplay;
return (
toolCall.request.name === ToolNames.AGENT &&
typeof display === 'object' &&
display !== null &&
'type' in display &&
'status' in display &&
display.type === 'task_execution' &&
display.status === 'background'
);
});
if (backgroundLaunchExhaustedCapacity) {
geminiClient?.addHistory({ role: 'user', parts: responsesToSend });
return;
}

// Drain steerable user messages at this sampling boundary and append
// them after the tool responses as genuine user content.
// Skip if the turn was cancelled — messages stay in queue for next turn.
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/agents/background-tasks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -483,6 +483,7 @@ describe('BackgroundTaskRegistry', () => {
registry = new BackgroundTaskRegistry({
maxConcurrentBackgroundAgents: 2,
});
expect(registry.getMaxConcurrentBackgroundAgents()).toBe(2);

registry.register(makeRegistration('bg-1'));
registry.register(makeRegistration('bg-2'));
Expand Down
4 changes: 4 additions & 0 deletions packages/core/src/agents/background-tasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -530,6 +530,10 @@ export class BackgroundTaskRegistry {
return true;
}

getMaxConcurrentBackgroundAgents(): number {
return this.maxConcurrentBackgroundAgents;
}

assertCanStartBackgroundAgent(model?: string): void {
const claimed = this.getClaimedBackgroundSlotCount();
if (claimed >= this.maxConcurrentBackgroundAgents) {
Expand Down
Loading