Compare commits

...

21 Commits

Author SHA1 Message Date
matt korwel 061ed12c4f Merge branch 'main' into afw/idle-wake-on-completion 2026-03-30 19:55:54 -07:00
matt korwel ecbdbea6d5 Merge branch 'main' into afw/idle-wake-on-completion 2026-03-30 11:10:26 -07:00
mkorwel 515dd420ea refactor(cli): consolidate injection pipeline and fix consumeUserHints typing 2026-03-30 09:03:30 -07:00
mkorwel a8dcff4229 chore: merge main and resolve Part 4 conflicts with agnostic task UI and sanitization 2026-03-30 08:14:26 -07:00
Adam Weidman 76c96cc4be feat(core): enable shell background completion injection
With the idle wake-up listener in place, shell background
completions can now use 'inject' to feed output back into the
model conversation when the agent is idle.
2026-03-17 09:56:42 -04:00
Adam Weidman 6880859fdb feat(cli): auto-restart agent on background task completion
When the agent is idle and a backgrounded execution completes, the
completion output is now automatically submitted as a new turn
instead of being silently dropped. Uses the same InjectionService
listener pattern as user steering hints.
2026-03-17 09:56:41 -04:00
Adam Weidman bb80f5fd67 Merge remote-tracking branch 'origin/main' into afw/agnostic-background-ui
# Conflicts:
#	packages/a2a-server/src/commands/memory.test.ts
#	packages/a2a-server/src/commands/memory.ts
#	packages/cli/src/acp/commands/memory.ts
#	packages/core/src/services/executionLifecycleService.test.ts
#	packages/core/src/services/executionLifecycleService.ts
2026-03-17 09:56:20 -04:00
Adam Weidman ccfd2a48ad fix(cli): only add shell PTYs to backgroundedPids set
Non-shell executions rely on the onBackground listener to register
in the UI panel. Adding their PID to backgroundedPids before firing
the listener caused them to be skipped and disappear from the UI.
2026-03-16 18:17:37 -04:00
Adam Weidman aabc27c12d fix(core): set shell background completionBehavior to silent
Shell background completions are set to silent until the idle
wake-up listener is in place, otherwise injections get buffered
but never consumed when the agent is idle.
2026-03-16 17:56:58 -04:00
Adam Weidman 6362e3cc15 fix: remove duplicate rebase artifacts in executionLifecycleService
Remove duplicated import, field, method, and injection call that
were introduced by rebase conflict resolution.
2026-03-16 12:04:39 -04:00
Adam Weidman 8751910572 refactor(core): move background injection from UI to ExecutionLifecycleService
settleExecution now calls injectionService.addInjection() directly
when a backgrounded execution completes, removing the bridge useEffect
from AppContainer. The UI just wires the injection service once at init
via setInjectionService().
2026-03-16 12:04:39 -04:00
Adam Weidman 708d0e7016 feat(core): add CompletionBehavior for background task injection control
Introduce inject/notify/silent completion behaviors that control what
happens when a backgrounded execution completes:
- inject: full output injected into conversation, auto-dismiss from UI
- notify: short pointer message injected (e.g. log file path), auto-dismiss
- silent: nothing injected, stays in Ctrl+B until manually dismissed

Shell commands use 'notify' (output saved to log file), remote agents
will use 'inject' (full output reinjected). Default is 'silent' when
no formatInjection callback is provided.
2026-03-16 12:04:39 -04:00
Adam Weidman d68cc3a88f feat(cli): make background task UI agnostic to execution type
Add onBackground event to ExecutionLifecycleService that fires when any
execution is moved to the background. The CLI subscribes to this event
and automatically registers background tasks in the UI — no per-tool
changes needed.

Any tool that calls ExecutionLifecycleService.createExecution() or
attachExecution() now automatically gets Ctrl+B support. Shell-specific
concerns (PTY log files) stay in ShellExecutionService.

Forward setExecutionIdCallback through SubAgentInvocation so agents
can expose their execution ID to the scheduler for backgrounding.

Route registerBackgroundTask and dismissBackgroundTask through
ExecutionLifecycleService instead of ShellExecutionService for
agnostic subscribe/onExit/kill support.
2026-03-16 12:04:39 -04:00
Adam Weidman 6510587725 refactor(core): replace positional execute params with ExecuteOptions bag
Collapse shellExecutionConfig and setExecutionIdCallback into a single
optional ExecuteOptions object on ToolInvocation.execute(). This avoids
forcing every tool implementation to accept shell-specific parameters
just to reach later positional args.
2026-03-16 12:01:39 -04:00
Adam Weidman 1d86b6504b test(core): add integration tests for background completion injection flow
Tests cover XML tag wrapping with safety instruction, ordering
(background completions before user hints), and source filtering
to prevent background output from leaking into user hint getters.
2026-03-16 11:57:36 -04:00
Adam Weidman 1dc55b278b fix(core): harden injection safety and listener resilience
Wrap background completion output in <background_output> XML tags with
inline instructions to treat as data, consistent with <user_input> tags
used for user steering hints.

Guard listener iteration in InjectionService.addInjection and
ExecutionLifecycleService.settleExecution with try/catch so a throwing
listener doesn't block subsequent listeners or crash the caller.
2026-03-16 11:00:52 -04:00
Adam Weidman 2727a871c3 fix(core): source-aware injection getters, fix unshift ordering, remove dead code
Rename getUserHints/getUserHintsAfter/getLatestHintIndex to
getInjections/getInjectionsAfter/getLatestInjectionIndex with optional
source filter so bg completions don't get formatted as user hints.

Swap unshift ordering so bg completions appear before user hints in the
message — the model sees context before the user's reaction to it.

Remove unused getLastUserHintAt().
2026-03-15 22:16:38 -04:00
Adam Weidman 8fcb18996a refactor(core): unify InjectionService API to single onInjection interface
Remove legacy onUserHint/offUserHint/addUserHint methods. All callers
now use addInjection(text, source) and onInjection/offInjection with
source-based filtering where needed.
2026-03-15 21:38:11 -04:00
Adam Weidman f46a1c7e8b refactor(core): move background completion consumption from UI to agent loop
The agent loop in local-executor now listens via onInjection (all sources)
instead of onUserHint (steering only), picking up background completions
between turns. This removes the separate bg completion useEffect, refs,
state, and callback from AppContainer entirely.
2026-03-15 15:43:34 -04:00
Adam Weidman 8b7321ea8d refactor(core): move background injection wiring from UI to backend
Wire ExecutionLifecycleService.setInjectionService() in Config constructor
so backgrounded executions inject directly via settleExecution instead of
routing through a useEffect bridge in AppContainer.
2026-03-15 15:11:13 -04:00
Adam Weidman 931b80206b refactor(core): rename UserHintService to InjectionService and add background completion support
Rename UserHintService to InjectionService as a generic, source-agnostic
injection mechanism. InjectionService supports typed sources ('user_steering'
and 'background_completion') with source-specific gating — user_steering
respects the model steering toggle while background_completion always fires.

Add background completion lifecycle to ExecutionLifecycleService: tracks
backgrounded executions, fires onBackgroundComplete listeners when they
settle, and supports FormatInjectionFn callbacks so execution creators
control how their output is formatted for reinjection.

Wire AppContainer to route background completions through InjectionService
and submit them to the model when idle, independent of model steering.
2026-03-12 13:23:52 -04:00
4 changed files with 61 additions and 33 deletions
+53 -28
View File
@@ -80,6 +80,7 @@ import {
ChangeAuthRequestedError,
ProjectIdRequiredError,
buildUserSteeringHintPrompt,
formatBackgroundCompletionForModel,
logBillingEvent,
ApiKeyUpdatedEvent,
type InjectionSource,
@@ -1099,30 +1100,49 @@ Logging in with Google... Restarting Gemini CLI to continue.
}
}, [pendingRestorePrompt, inputHistory, historyManager.history]);
const pendingHintsRef = useRef<string[]>([]);
const [pendingHintCount, setPendingHintCount] = useState(0);
const pendingInjectionsRef = useRef<
Array<{ text: string; source: InjectionSource }>
>([]);
const [pendingInjectionCount, setPendingInjectionCount] = useState(0);
const consumePendingHints = useCallback(() => {
if (pendingHintsRef.current.length === 0) {
return null;
}
const hint = pendingHintsRef.current.join('\n');
pendingHintsRef.current = [];
setPendingHintCount(0);
return hint;
}, []);
const consumePendingInjections = useCallback(
(source?: InjectionSource) => {
if (pendingInjectionsRef.current.length === 0) {
return [];
}
if (!source) {
const injections = [...pendingInjectionsRef.current];
pendingInjectionsRef.current = [];
setPendingInjectionCount(0);
return injections;
}
const matching = pendingInjectionsRef.current.filter(
(inj) => inj.source === source,
);
pendingInjectionsRef.current = pendingInjectionsRef.current.filter(
(inj) => inj.source !== source,
);
setPendingInjectionCount(pendingInjectionsRef.current.length);
return matching;
},
[pendingInjectionsRef],
);
const consumeUserHints = useCallback(() => {
const hints = consumePendingInjections('user_steering');
return hints.length > 0 ? hints.map((h) => h.text).join('\n') : null;
}, [consumePendingInjections]);
useEffect(() => {
const hintListener = (text: string, source: InjectionSource) => {
if (source !== 'user_steering' && source !== 'background_completion') {
return;
}
pendingHintsRef.current.push(text);
setPendingHintCount((prev) => prev + 1);
const injectionListener = (text: string, source: InjectionSource) => {
pendingInjectionsRef.current.push({ text, source });
setPendingInjectionCount((prev) => prev + 1);
};
config.injectionService.onInjection(hintListener);
config.injectionService.onInjection(injectionListener);
return () => {
config.injectionService.offInjection(hintListener);
config.injectionService.offInjection(injectionListener);
};
}, [config]);
@@ -1164,7 +1184,7 @@ Logging in with Google... Restarting Gemini CLI to continue.
terminalWidth,
terminalHeight,
embeddedShellFocused,
consumePendingHints,
consumeUserHints,
);
const pendingHistoryItems = useMemo(
@@ -2184,30 +2204,35 @@ Logging in with Google... Restarting Gemini CLI to continue.
useEffect(() => {
if (
!isConfigInitialized ||
!config.isModelSteeringEnabled() ||
streamingState !== StreamingState.Idle ||
!isMcpReady ||
pendingInjectionCount === 0 ||
isToolAwaitingConfirmation(pendingHistoryItems)
) {
return;
}
const pendingHint = consumePendingHints();
if (!pendingHint) {
const pendingInjections = consumePendingInjections();
if (pendingInjections.length === 0) {
return;
}
void submitQuery([{ text: buildUserSteeringHintPrompt(pendingHint) }]);
const prompts = pendingInjections.map((inj) => {
if (inj.source === 'user_steering') {
return { text: buildUserSteeringHintPrompt(inj.text) };
}
return { text: formatBackgroundCompletionForModel(inj.text) };
});
void submitQuery(prompts);
}, [
config,
historyManager,
isConfigInitialized,
isMcpReady,
streamingState,
submitQuery,
consumePendingHints,
pendingInjectionCount,
pendingHistoryItems,
pendingHintCount,
consumePendingInjections,
]);
const allToolCalls = useMemo(
@@ -188,6 +188,7 @@ describe('SubAgentInvocation', () => {
expect(mockInnerInvocation.execute).toHaveBeenCalledWith(
abortSignal,
updateOutput,
undefined,
);
expect(runInDevTraceSpan).toHaveBeenCalledWith(
+3 -1
View File
@@ -13,6 +13,7 @@ import {
type ToolCallConfirmationDetails,
isTool,
type ToolLiveOutput,
type ExecuteOptions,
} from '../tools/tools.js';
import type { Config } from '../config/config.js';
import { type AgentLoopContext } from '../config/agent-loop-context.js';
@@ -161,6 +162,7 @@ class SubAgentInvocation extends BaseToolInvocation<AgentInputs, ToolResult> {
async execute(
signal: AbortSignal,
updateOutput?: (output: ToolLiveOutput) => void,
options?: ExecuteOptions,
): Promise<ToolResult> {
const validationError = SchemaValidator.validate(
this.definition.inputConfig.inputSchema,
@@ -189,7 +191,7 @@ class SubAgentInvocation extends BaseToolInvocation<AgentInputs, ToolResult> {
},
async ({ metadata }) => {
metadata.input = this.params;
const result = await invocation.execute(signal, updateOutput);
const result = await invocation.execute(signal, updateOutput, options);
metadata.output = result;
return result;
},
@@ -553,12 +553,12 @@ export class ShellExecutionService {
formatInjection: (output, error) =>
ShellExecutionService.formatShellBackgroundCompletion(
child.pid!,
shellExecutionConfig.backgroundCompletionBehavior || 'silent',
shellExecutionConfig.backgroundCompletionBehavior ?? 'inject',
output,
error ?? undefined,
),
completionBehavior:
shellExecutionConfig.backgroundCompletionBehavior || 'silent',
shellExecutionConfig.backgroundCompletionBehavior ?? 'inject',
})
: undefined;
@@ -892,12 +892,12 @@ export class ShellExecutionService {
formatInjection: (output, error) =>
ShellExecutionService.formatShellBackgroundCompletion(
ptyPid,
shellExecutionConfig.backgroundCompletionBehavior || 'silent',
shellExecutionConfig.backgroundCompletionBehavior ?? 'inject',
output,
error ?? undefined,
),
completionBehavior:
shellExecutionConfig.backgroundCompletionBehavior || 'silent',
shellExecutionConfig.backgroundCompletionBehavior ?? 'inject',
}).result;
let processingChain = Promise.resolve();