Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 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
94 changes: 94 additions & 0 deletions packages/core/src/agents/background-agent-resume.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -473,6 +473,100 @@ describe('BackgroundAgentResumeService', () => {
});
});

it('returns only model-visible subagent output when resumed background agents complete', async () => {
const sessionId = 'session-resume-sanitized';
const agentId = 'agent-resume-sanitized';
const metaPath = getAgentMetaPath(tempDir, sessionId, agentId);
const outputFile = getAgentJsonlPath(tempDir, sessionId, agentId);

writeAgentMeta(metaPath, {
agentId,
agentType: 'researcher',
description: 'Resume with tagged result',
parentSessionId: sessionId,
parentAgentId: null,
createdAt: '2026-04-20T00:00:00.000Z',
status: 'running',
subagentName: 'researcher',
resolvedApprovalMode: 'auto-edit',
});
fs.writeFileSync(
outputFile,
JSON.stringify({
uuid: 'u1',
parentUuid: null,
sessionId,
timestamp: '2026-04-20T00:00:00.000Z',
type: 'user',
message: {
role: 'user',
parts: [{ text: 'Resume with tagged result' }],
},
}) + '\n',
'utf8',
);

registry.register({
agentId,
description: 'Resume with tagged result',
subagentType: 'researcher',
isBackgrounded: true,
status: 'paused',
startTime: Date.now(),
abortController: new AbortController(),
prompt: 'Resume with tagged result',
outputFile,
metaPath,
});

const subagent = {
execute: vi.fn(async () => undefined),
setExternalMessageProvider: vi.fn(),
getCore: () => ({ getEventEmitter: () => new AgentEventEmitter() }),
getExecutionSummary: () => ({
rounds: 0,
totalToolCalls: 0,
successfulToolCalls: 0,
failedToolCalls: 0,
successRate: 0,
inputTokens: 0,
outputTokens: 0,
thoughtTokens: 0,
cachedTokens: 0,
totalTokens: 0,
toolUsage: [],
totalDurationMs: 0,
}),
getTerminateMode: () => AgentTerminateMode.GOAL,
getFinalText: () =>
[
'<analysis>',
'Scratchpad details should stay out of the parent context.',
'</analysis>',
'',
'<summary>',
'Resume completed successfully',
'</summary>',
].join('\n'),
};

const { service, subagentManager } = createService();
subagentManager.createAgentHeadless.mockResolvedValue({
subagent,
dispose: vi.fn().mockResolvedValue(undefined),
});

const resumed = await service.resumeBackgroundAgent(agentId, 'continue');

expect(resumed).toBeDefined();
await vi.waitFor(() => {
expect(registry.get(agentId)?.status).toBe('completed');
});
expect(registry.get(agentId)?.result).toBe(
'Resume completed successfully',
);
});

it('can resume into the final background concurrency slot', async () => {
registry = new BackgroundTaskRegistry({
maxConcurrentBackgroundAgents: 1,
Expand Down
6 changes: 5 additions & 1 deletion packages/core/src/agents/background-agent-resume.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
appendStopHookBlockingCapWarning,
formatStopHookBlockingCapWarning,
} from '../hooks/stopHookCap.js';
import { toModelVisibleSubagentResult } from './subagent-result.js';
import { runWithAgentContext } from './runtime/agent-context.js';
import { createApprovalModeOverride } from '../tools/agent/agent.js';
import type { ApprovalMode } from '../config/config.js';
Expand Down Expand Up @@ -935,7 +936,10 @@ export class BackgroundAgentResumeService {

const terminateMode = subagent.getTerminateMode();
const finalText = appendStopHookBlockingCapWarning(
subagent.getFinalText(),
toModelVisibleSubagentResult(
subagent.getFinalText(),
terminateMode,
),
stopHookWarning,
);
const stats = getCompletionStats(subagent, liveToolCallCount);
Expand Down
152 changes: 92 additions & 60 deletions packages/core/src/agents/runtime/workflow-orchestrator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,34 +26,40 @@ import type { Config } from '../../config/config.js';
// FIX-C8 (TST-2-I2): record the full 9-arg signature of AgentHeadless.create
// and the (ctx, signal?) shape of execute so any drift between the production
// call site and the real AgentHeadless surface becomes a test failure.
const { created, nextTerminateMode, nextOutputTokens, nextExecuteThrow } =
vi.hoisted(() => ({
created: [] as Array<{
name: string;
prompt: string;
signal?: AbortSignal;
promptConfigSystemPrompt?: string;
runConfig?: { max_turns?: number; max_time_minutes?: number };
toolConfig?: { tools?: string[]; disallowedTools?: string[] };
}>,
// T10 (PR #4732 R1): the production dispatch checks getTerminateMode() and
// throws on non-GOAL. Tests set `nextTerminateMode.value` to simulate
// CANCELLED / MAX_TURNS / TIMEOUT outcomes.
nextTerminateMode: { value: 'GOAL' as string },
// R1 (#1 + #3): the production dispatch reads
// `subagent.getExecutionSummary().outputTokens` to feed budget. Tests
// set `nextOutputTokens.value` so the onTokens callback can be
// observed without standing up real telemetry.
nextOutputTokens: { value: 0 as number },
// R3 (wenshao #6): real `AgentHeadless.execute()` re-throws on
// reasoning-loop failure — its catch arm sets `terminateMode=ERROR`
// and then throws. Tests set `nextExecuteThrow.value` to a non-null
// error so the mock execute() re-throws the same way; R1's tests
// had execute() RETURN with ERROR mode, which is the rare
// `createChat` early-return path, NOT the production reasoning-
// loop throw path.
nextExecuteThrow: { value: null as Error | null },
}));
const {
created,
nextFinalText,
nextTerminateMode,
nextOutputTokens,
nextExecuteThrow,
} = vi.hoisted(() => ({
created: [] as Array<{
name: string;
prompt: string;
signal?: AbortSignal;
promptConfigSystemPrompt?: string;
runConfig?: { max_turns?: number; max_time_minutes?: number };
toolConfig?: { tools?: string[]; disallowedTools?: string[] };
}>,
nextFinalText: { value: undefined as string | undefined },
// T10 (PR #4732 R1): the production dispatch checks getTerminateMode() and
// throws on non-GOAL. Tests set `nextTerminateMode.value` to simulate
// CANCELLED / MAX_TURNS / TIMEOUT outcomes.
nextTerminateMode: { value: 'GOAL' as string },
// R1 (#1 + #3): the production dispatch reads
// `subagent.getExecutionSummary().outputTokens` to feed budget. Tests
// set `nextOutputTokens.value` so the onTokens callback can be
// observed without standing up real telemetry.
nextOutputTokens: { value: 0 as number },
// R3 (wenshao #6): real `AgentHeadless.execute()` re-throws on
// reasoning-loop failure — its catch arm sets `terminateMode=ERROR`
// and then throws. Tests set `nextExecuteThrow.value` to a non-null
// error so the mock execute() re-throws the same way; R1's tests
// had execute() RETURN with ERROR mode, which is the rare
// `createChat` early-return path, NOT the production reasoning-
// loop throw path.
nextExecuteThrow: { value: null as Error | null },
}));

// P3 R2 self-review (P3-T6 gap, batch): tests below for
// agent({isolation:'worktree'}) need to drive GitWorktreeService's
Expand Down Expand Up @@ -152,6 +158,7 @@ vi.mock('./agent-headless.js', () => ({
}
},
getFinalText: () =>
nextFinalText.value ??
`headless-said:${created[created.length - 1]!.prompt}`,
getTerminateMode: () => nextTerminateMode.value,
// R1 (#1 + #3): expose `getExecutionSummary` so the production
Expand Down Expand Up @@ -1075,6 +1082,7 @@ describe('createProductionDispatch', () => {
// terminate mode back to 'goal' (success).
beforeEach(() => {
created.length = 0;
nextFinalText.value = undefined;
nextTerminateMode.value = 'GOAL';
});

Expand All @@ -1087,6 +1095,16 @@ describe('createProductionDispatch', () => {
expect(created[0]!.prompt).toBe('hello');
});

it('strips internal tags from fast-path final text', async () => {
nextFinalText.value =
'<analysis>scratch</analysis><summary>clean result</summary>';
const dispatch = createProductionDispatch(fakeConfig());

await expect(dispatch('hello', { label: 'h1' })).resolves.toBe(
'clean result',
);
});

// FIX-C4 (TST-2-C2): the previous test only asserted no-crash. This one
// actually captures the signal in the mock and asserts identity, so a
// regression that drops the second arg of subagent.execute() would fail.
Expand Down Expand Up @@ -1741,9 +1759,8 @@ describe('WorkflowOrchestrator P3 — agentType / model / isolation / schema', (
// by one test does not bleed into the next (mockImplementation is
// persistent; the per-test overrides below rely on a clean baseline).
beforeEach(async () => {
const { GitWorktreeService } = await import(
'../../services/gitWorktreeService.js'
);
const { GitWorktreeService } =
await import('../../services/gitWorktreeService.js');
worktreeStubs.instances.length = 0;
vi.mocked(GitWorktreeService).mockImplementation(() => {
const stub = worktreeStubs.makeStub();
Expand Down Expand Up @@ -1921,6 +1938,27 @@ describe('WorkflowOrchestrator P3 — agentType / model / isolation / schema', (
);
});

it('strips internal tags from override-path final text', async () => {
const { config } = fakeConfigWithMgr({
findSubagentByName: async () => ({
name: 'Explore',
description: 'fast read-only',
systemPrompt: 'You are Explore.',
level: 'builtin',
}),
onCreate: async () => ({
finalText:
'<analysis>scratch</analysis><summary>clean result</summary>',
terminateMode: 'GOAL',
}),
});
const dispatch = createProductionDispatch(config);

await expect(dispatch('find foo', { agentType: 'Explore' })).resolves.toBe(
'clean result',
);
});

it('agentType not found throws upstream-aligned error', async () => {
const { config } = fakeConfigWithMgr({
findSubagentByName: async () => null,
Expand Down Expand Up @@ -2439,16 +2477,18 @@ describe('WorkflowOrchestrator P3 — agentType / model / isolation / schema', (
const dispatch = createProductionDispatch(config);
// newline + nul + del — all control codes < 0x20 or == 0x7f.
const evil = 'Explore\n\rEvil\x00\x7f';
await expect(dispatch('hi', { agentType: evil })).rejects.toThrow();
// The thrown message must NOT contain raw newlines / NULs.
let error: unknown;
try {
await dispatch('hi', { agentType: evil });
} catch (err) {
const msg = (err as Error).message;
// eslint-disable-next-line no-control-regex
expect(msg).not.toMatch(/[\n\r\u0000\u007f]/);
expect(msg).toContain('not found');
error = err;
}
expect(error).toBeInstanceOf(Error);
const msg = (error as Error).message;
// eslint-disable-next-line no-control-regex
expect(msg).not.toMatch(/[\n\r\u0000\u007f]/);
expect(msg).toContain('not found');
});

// R2 self-review (test-5): dispose() MUST still run even when
Expand Down Expand Up @@ -2496,9 +2536,8 @@ describe('WorkflowOrchestrator P3 — agentType / model / isolation / schema', (

it("isolation:'worktree' refuses when git is not available", async () => {
worktreeStubs.instances.length = 0; // reset
const { GitWorktreeService } = await import(
'../../services/gitWorktreeService.js'
);
const { GitWorktreeService } =
await import('../../services/gitWorktreeService.js');
vi.mocked(GitWorktreeService).mockImplementation(
() =>
({
Expand All @@ -2519,9 +2558,8 @@ describe('WorkflowOrchestrator P3 — agentType / model / isolation / schema', (
});

it("isolation:'worktree' refuses when cwd is not a git repository", async () => {
const { GitWorktreeService } = await import(
'../../services/gitWorktreeService.js'
);
const { GitWorktreeService } =
await import('../../services/gitWorktreeService.js');
vi.mocked(GitWorktreeService).mockImplementation(
() =>
({
Expand All @@ -2539,9 +2577,8 @@ describe('WorkflowOrchestrator P3 — agentType / model / isolation / schema', (
});

it("isolation:'worktree' refuses when parent working tree is dirty", async () => {
const { GitWorktreeService } = await import(
'../../services/gitWorktreeService.js'
);
const { GitWorktreeService } =
await import('../../services/gitWorktreeService.js');
vi.mocked(GitWorktreeService).mockImplementation(
() =>
({
Expand All @@ -2559,9 +2596,8 @@ describe('WorkflowOrchestrator P3 — agentType / model / isolation / schema', (
});

it("isolation:'worktree' surfaces createUserWorktree failure", async () => {
const { GitWorktreeService } = await import(
'../../services/gitWorktreeService.js'
);
const { GitWorktreeService } =
await import('../../services/gitWorktreeService.js');
vi.mocked(GitWorktreeService).mockImplementation(
() =>
({
Expand Down Expand Up @@ -2589,9 +2625,8 @@ describe('WorkflowOrchestrator P3 — agentType / model / isolation / schema', (
// suffix and was previously untested.

it("isolation:'worktree' cleanup: removeUserWorktree failure preserves path+branch", async () => {
const { GitWorktreeService } = await import(
'../../services/gitWorktreeService.js'
);
const { GitWorktreeService } =
await import('../../services/gitWorktreeService.js');
vi.mocked(GitWorktreeService).mockImplementation(
() =>
({
Expand Down Expand Up @@ -2621,9 +2656,8 @@ describe('WorkflowOrchestrator P3 — agentType / model / isolation / schema', (
});

it("isolation:'worktree' cleanup: branchPreserved race yields branch-only suffix", async () => {
const { GitWorktreeService } = await import(
'../../services/gitWorktreeService.js'
);
const { GitWorktreeService } =
await import('../../services/gitWorktreeService.js');
vi.mocked(GitWorktreeService).mockImplementation(
() =>
({
Expand All @@ -2646,9 +2680,8 @@ describe('WorkflowOrchestrator P3 — agentType / model / isolation / schema', (
});

it("isolation:'worktree' cleanup: thrown removeUserWorktree preserves path+branch", async () => {
const { GitWorktreeService } = await import(
'../../services/gitWorktreeService.js'
);
const { GitWorktreeService } =
await import('../../services/gitWorktreeService.js');
vi.mocked(GitWorktreeService).mockImplementation(
() =>
({
Expand Down Expand Up @@ -2740,9 +2773,8 @@ describe('WorkflowOrchestrator P3 — agentType / model / isolation / schema', (
// the worktree on disk.
it("isolation:'worktree' + schema setup throws → worktree is still cleaned up", async () => {
const removeCalls: string[] = [];
const { GitWorktreeService } = await import(
'../../services/gitWorktreeService.js'
);
const { GitWorktreeService } =
await import('../../services/gitWorktreeService.js');
vi.mocked(GitWorktreeService).mockImplementation(() => {
const stub = worktreeStubs.makeStub();
// Track removeUserWorktree calls — the fallback finally must call it.
Expand Down
Loading
Loading