Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(tasks): wait for pending sub-agents before completing turns (#129013)

posthog[bot]1b63d1f22bc1
diff --git a/packages/agent/packages/agent/src/adapters/claude/claude-agent.task-notification.test.ts b/packages/agent/packages/agent/src/adapters/claude/claude-agent.task-notification.test.ts
index 5a34e9211766..907f570aba84 100644
--- a/packages/agent/packages/agent/src/adapters/claude/claude-agent.task-notification.test.ts
+++ b/packages/agent/packages/agent/src/adapters/claude/claude-agent.task-notification.test.ts
@@ -42,6 +42,7 @@ function makeAgent(): { agent: Agent; client: ClientMocks } {
function installFakeSession(
agent: Agent,
sessionId: string,
+ waitForSubagents = false,
): { query: MockQuery; input: Pushable<SDKUserMessage> } {
const query = createMockQuery();
const input = new Pushable<SDKUserMessage>();
@@ -49,6 +50,7 @@ function installFakeSession(
const session = {
query,
+ waitForSubagents,
queryOptions: { sessionId, cwd: "/tmp/repo", abortController },
buildInProcessMcpServers: () => ({}),
localToolsServerNames: [] as string[],
@@ -140,7 +142,7 @@ function taskNotificationUserMessage(sessionId: string, event: string) {
uuid: `task-notification-${event}`,
message: {
role: "user",
- content: `<task-notification>\n<event>${event}</event>\n</task-notification>`,
+ content: `<task-notification>\n<task-id>${event}</task-id>\n</task-notification>`,
},
origin: { kind: "task-notification" },
};
@@ -208,6 +210,296 @@ describe("ClaudeAcpAgent — task-notification results", () => {
).toHaveLength(0);
});
+ it.each(["completed", "failed", "stopped"])(
+ "waits for every sub-agent and the parent's reply when a worker %s",
+ async (status) => {
+ const { agent, client } = makeAgent();
+ const sessionId = "s-pending-subagents";
+ const { query, input } = installFakeSession(agent, sessionId, true);
+ const settled = vi.fn();
+ const prompt = agent
+ .prompt({
+ sessionId,
+ prompt: [{ type: "text", text: "Choose a repository." }],
+ })
+ .then((result) => {
+ settled(result);
+ return result;
+ });
+ await tick();
+ await echoUserMessage(query, input);
+ for (const taskId of ["worker-a", "worker-b"]) {
+ await send(query, {
+ type: "system",
+ subtype: "task_started",
+ task_id: taskId,
+ task_type: "local_agent",
+ is_backgrounded: true,
+ });
+ }
+ await send(
+ query,
+ assistantMessage(sessionId, "waiting", "Research is pending."),
+ );
+ await send(query, {
+ ...resultSuccess(sessionId, "initial"),
+ usage: { output_tokens: 3 },
+ });
+ expect(settled).not.toHaveBeenCalled();
+
+ for (const taskId of ["worker-a", "worker-b"]) {
+ await send(query, {
+ type: "system",
+ subtype: "task_notification",
+ task_id: taskId,
+ status,
+ summary: "Worker ended.",
+ output_file: "/tmp/worker-output",
+ });
+ expect(settled).not.toHaveBeenCalled();
+ await send(query, taskNotificationUserMessage(sessionId, taskId));
+ await send(
+ query,
+ assistantMessage(
+ sessionId,
+ taskId,
+ taskId === "worker-b"
+ ? '{"repository":"example/app"}'
+ : "Another worker remains.",
+ ),
+ );
+ await send(query, {
+ ...taskNotificationResult(sessionId, taskId),
+ usage: { output_tokens: 5 },
+ });
+ if (taskId === "worker-a") expect(settled).not.toHaveBeenCalled();
+ }
+ await expect(prompt).resolves.toMatchObject({
+ stopReason: "end_turn",
+ usage: { outputTokens: 13 },
+ });
+ expect(
+ extNotificationCalls(
+ client.extNotification.mock.calls,
+ "_posthog/background_turn_complete",
+ ),
+ ).toHaveLength(0);
+ expect(client.sessionUpdate).toHaveBeenCalledWith(
+ expect.objectContaining({
+ update: expect.objectContaining({
+ content: { type: "text", text: '{"repository":"example/app"}' },
+ }),
+ }),
+ );
+ },
+ );
+
+ it.each(["overlapping", "batched", "late_snapshot", "late_start", "resumed"])(
+ "handles %s notifications without accepting an unrelated wakeup",
+ async (delivery) => {
+ const { agent } = makeAgent();
+ const sessionId = "s-subagent-notification-order";
+ const { query, input } = installFakeSession(agent, sessionId, true);
+ const settled = vi.fn();
+ const prompt = agent
+ .prompt({ sessionId, prompt: [{ type: "text", text: "Research." }] })
+ .then(settled);
+ await tick();
+ await echoUserMessage(query, input);
+ await send(query, {
+ type: "system",
+ subtype: "background_tasks_changed",
+ tasks: ["worker-a", "worker-b"].map((id) => ({
+ task_id: id,
+ task_type: "local_agent",
+ run_id: id,
+ })),
+ });
+ await send(query, {
+ type: "system",
+ subtype: "task_notification",
+ task_id: "worker-a",
+ run_id: "worker-a",
+ status: "completed",
+ summary: "Worker ended.",
+ });
+ await send(
+ query,
+ assistantMessage(sessionId, "waiting", "Research is pending."),
+ );
+ await send(query, resultSuccess(sessionId, "initial"));
+ await send(
+ query,
+ taskNotificationUserMessage(sessionId, "unrelated-wakeup"),
+ );
+ await send(query, taskNotificationResult(sessionId, "unrelated-result"));
+ expect(settled).not.toHaveBeenCalled();
+
+ const workerNotification = (id: string) => ({
+ ...taskNotificationUserMessage(sessionId, id),
+ origin: { kind: "task-notification", runId: id },
+ });
+ if (delivery === "overlapping") {
+ await send(query, workerNotification("worker-a"));
+ }
+ await send(query, {
+ type: "system",
+ subtype: "task_notification",
+ task_id: "worker-b",
+ run_id: "old-run",
+ status: "stopped",
+ summary: "Old worker ended.",
+ });
+ await send(query, {
+ type: "system",
+ subtype: "task_notification",
+ task_id: "worker-b",
+ run_id: "worker-b",
+ status: "completed",
+ summary: "Worker ended.",
+ });
+ if (delivery === "overlapping") {
+ await send(query, workerNotification("worker-b"));
+ await send(query, taskNotificationResult(sessionId, "worker-a"));
+ expect(settled).not.toHaveBeenCalled();
+ } else {
+ await send(query, {
+ ...taskNotificationUserMessage(sessionId, "batch"),
+ message: {
+ role: "user",
+ content: "<task-id>worker-a</task-id>\n<task-id>worker-b</task-id>",
+ },
+ });
+ }
+ await send(
+ query,
+ assistantMessage(sessionId, "final", "Research complete."),
+ );
+ if (delivery === "late_snapshot") {
+ await send(query, {
+ type: "system",
+ subtype: "background_tasks_changed",
+ tasks: [
+ {
+ task_id: "worker-b",
+ task_type: "local_agent",
+ run_id: "worker-b",
+ },
+ ],
+ });
+ await send(query, {
+ type: "system",
+ subtype: "background_tasks_changed",
+ tasks: [],
+ });
+ }
+ if (delivery === "late_start" || delivery === "resumed") {
+ await send(query, {
+ type: "system",
+ subtype: "task_started",
+ task_id: "worker-b",
+ task_type: "local_agent",
+ is_backgrounded: true,
+ run_id: delivery === "resumed" ? "worker-b-2" : "worker-b",
+ });
+ }
+ await send(query, taskNotificationResult(sessionId, "final"));
+ if (delivery === "resumed") {
+ expect(settled).not.toHaveBeenCalled();
+ await send(query, {
+ type: "system",
+ subtype: "task_notification",
+ task_id: "worker-b",
+ run_id: "worker-b-2",
+ status: "completed",
+ summary: "Worker ended.",
+ });
+ await send(query, {
+ ...taskNotificationUserMessage(sessionId, "worker-b"),
+ origin: { kind: "task-notification", runId: "worker-b-2" },
+ });
+ await send(
+ query,
+ assistantMessage(sessionId, "resumed", "Research complete."),
+ );
+ await send(query, taskNotificationResult(sessionId, "resumed"));
+ }
+ expect(settled).toHaveBeenCalledOnce();
+ await prompt;
+ },
+ );
+
+ it.each([
+ ["interactive", false, "local_agent", true, false],
+ ["shell", true, "local_bash", true, false],
+ ["monitor", true, "local_monitor", true, false],
+ ["foreground", true, "local_agent", false, false],
+ ["ambient", true, "local_agent", true, true],
+ ] as const)(
+ "does not wait for %s tasks",
+ async (_name, wait, taskType, backgrounded, ambient) => {
+ const { agent } = makeAgent();
+ const sessionId = "s-independent-task";
+ const { query, input } = installFakeSession(agent, sessionId, wait);
+ const prompt = agent.prompt({
+ sessionId,
+ prompt: [{ type: "text", text: "Proceed." }],
+ });
+ await tick();
+ await echoUserMessage(query, input);
+ await send(query, {
+ type: "system",
+ subtype: "task_started",
+ task_id: "worker",
+ task_type: taskType,
+ is_backgrounded: backgrounded,
+ ambient,
+ });
+ await send(query, assistantMessage(sessionId, "done", "Complete."));
+ await send(query, resultSuccess(sessionId, "result"));
+ await expect(prompt).resolves.toMatchObject({ stopReason: "end_turn" });
+ },
+ );
+
+ it.each(["cancel", "stream_end"])(
+ "ends a held turn on %s",
+ async (ending) => {
+ const { agent } = makeAgent();
+ const sessionId = "s-subagent-interrupted";
+ const { query, input } = installFakeSession(agent, sessionId, true);
+ const prompt = agent.prompt({
+ sessionId,
+ prompt: [{ type: "text", text: "Research." }],
+ });
+ await tick();
+ await echoUserMessage(query, input);
+ await send(query, {
+ type: "system",
+ subtype: "task_started",
+ task_id: "worker",
+ task_type: "local_agent",
+ is_backgrounded: true,
+ });
+ await send(
+ query,
+ assistantMessage(sessionId, "waiting", "Research is pending."),
+ );
+ await send(query, resultSuccess(sessionId, "initial"));
+ if (ending === "cancel") {
+ await agent.cancel({ sessionId });
+ await expect(prompt).resolves.toMatchObject({
+ stopReason: "cancelled",
+ });
+ } else {
+ const rejected = expect(prompt).rejects.toThrow(
+ "Session ended before sub-agents returned",
+ );
+ query._mockHelpers.complete();
+ await rejected;
+ }
+ },
+ );
+
it("acks a steer sent during a background turn only once the model acts on it", async () => {
const { agent } = makeAgent();
const sessionId = "s-task-notification-steer";
diff --git a/packages/agent/packages/agent/src/adapters/claude/claude-agent.ts b/packages/agent/packages/agent/src/adapters/claude/claude-agent.ts
index 9fe7b021c286..00fd413c6511 100644
--- a/packages/agent/packages/agent/src/adapters/claude/claude-agent.ts
+++ b/packages/agent/packages/agent/src/adapters/claude/claude-agent.ts
@@ -1106,6 +1106,38 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
cache_creation_input_tokens: 0,
};
let stopReason: PromptResponse["stopReason"] = "end_turn";
+ const pendingSubagents = new Map<string, string | undefined>();
+ const completedSubagents = new Map<string, string | undefined>();
+ const endedSubagentRuns = new Map<string, string | undefined>();
+ const trackPendingSubagent = (
+ taskId: string,
+ runId: string | undefined,
+ ): void => {
+ // Snapshot and lifecycle events can overlap; a completed run must not become pending again.
+ if (endedSubagentRuns.has(taskId)) {
+ const endedRun = endedSubagentRuns.get(taskId);
+ if (
+ runId === undefined ||
+ endedRun === undefined ||
+ runId <= endedRun
+ ) {
+ return;
+ }
+ }
+ const pendingRun = pendingSubagents.get(taskId);
+ if (
+ pendingRun !== undefined &&
+ (runId === undefined || runId < pendingRun)
+ ) {
+ return;
+ }
+ pendingSubagents.set(taskId, runId);
+ };
+ const subagentReplyBatches: Set<string>[] = [];
+ const hasPendingSubagents = () =>
+ pendingSubagents.size > 0 ||
+ completedSubagents.size > 0 ||
+ subagentReplyBatches.some((batch) => batch.size > 0);
// Read live: model switches reset session.lastContextWindowSize.
const windowSize = () =>
@@ -1166,6 +1198,10 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
};
const resetTurnScratch = () => {
+ pendingSubagents.clear();
+ completedSubagents.clear();
+ endedSubagentRuns.clear();
+ subagentReplyBatches.length = 0;
lastAssistantTotalUsage = null;
lastRefusalExplanation = null;
lastRefusalCategory = null;
@@ -1336,11 +1372,20 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
if (refreshed()) {
return;
}
- settleActive(
- session.cancelled
- ? this.cancelledResponse()
- : { stopReason, usage: sessionUsage() },
- );
+ if (!session.cancelled && session.activeTurn?.waitingForSubagents) {
+ failActive(
+ RequestError.internalError(
+ undefined,
+ "Session ended before sub-agents returned",
+ ),
+ );
+ } else {
+ settleActive(
+ session.cancelled
+ ? this.cancelledResponse()
+ : { stopReason, usage: sessionUsage() },
+ );
+ }
// Queued turns the SDK never started produced no output; reject
// them rather than report a success.
for (const queued of [...session.turnQueue]) {
@@ -1374,6 +1419,31 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
switch (message.type) {
case "system":
+ if (session.waitForSubagents && session.activeTurn) {
+ if (
+ message.subtype === "task_started" &&
+ message.is_backgrounded !== false &&
+ !message.ambient &&
+ (message.task_type === "local_agent" || message.subagent_type)
+ ) {
+ trackPendingSubagent(message.task_id, message.run_id);
+ } else if (message.subtype === "background_tasks_changed") {
+ for (const task of message.tasks) {
+ if (task.task_type === "local_agent" && !task.ambient) {
+ trackPendingSubagent(task.task_id, task.run_id);
+ }
+ }
+ } else if (
+ message.subtype === "task_notification" &&
+ pendingSubagents.has(message.task_id) &&
+ pendingSubagents.get(message.task_id) === message.run_id
+ ) {
+ // A completed worker still needs the parent to consume its result.
+ pendingSubagents.delete(message.task_id);
+ endedSubagentRuns.set(message.task_id, message.run_id);
+ completedSubagents.set(message.task_id, message.run_id);
+ }
+ }
if (message.subtype === "init") {
await this.syncFastModeState(message.fast_mode_state);
}
@@ -1533,11 +1603,16 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
break;
case "result": {
- // Task-notification followups are background work: they must not
- // touch the user-turn lifecycle, but their cost is still reported.
const isTaskNotification =
(message as { origin?: { kind?: string } }).origin?.kind ===
"task-notification";
+ const subagentReply = isTaskNotification
+ ? subagentReplyBatches.shift()
+ : undefined;
+ const isSubagentContinuation =
+ session.activeTurn != null && (subagentReply?.size ?? 0) > 0;
+ const isBackgroundResult =
+ isTaskNotification && !isSubagentContinuation;
if (isTaskNotification) {
session.backgroundTurnActive = false;
if (hasUnconsumedBackgroundSteers(session)) {
@@ -1563,7 +1638,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
);
}
- if (!isTaskNotification) {
+ if (!isBackgroundResult) {
await this.syncFastModeState(
(message as { fast_mode_state?: FastModeState })
.fast_mode_state,
@@ -1572,7 +1647,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
// Promote before accumulating usage: activation resets the
// accumulator.
- if (!isTaskNotification) {
+ if (!isBackgroundResult) {
await ensureActiveTurn();
}
@@ -1581,7 +1656,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
break;
}
- if (!isTaskNotification) {
+ if (!isBackgroundResult) {
// Accumulate usage from this result (guard against null from SDK)
session.accumulatedUsage.inputTokens +=
message.usage.input_tokens ?? 0;
@@ -1605,7 +1680,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
}
}
- if (!isTaskNotification && lastAssistantTotalUsage === null) {
+ if (!isBackgroundResult && lastAssistantTotalUsage === null) {
const usedTokens = await withAbort(
fetchContextUsedTokens(query, this.logger),
cancelController.signal,
@@ -1673,7 +1748,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
}),
...(lastRefusalCategory && { category: lastRefusalCategory }),
});
- if (isTaskNotification) {
+ if (isBackgroundResult) {
// Background work never activates a turn, so there is no
// settle path to broadcast completion — send it directly so
// the UI still closes this reply out as its own turn.
@@ -1693,7 +1768,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
session.activeTurn?.madeProgress === true,
);
if (result.error) {
- if (!isTaskNotification) {
+ if (!isBackgroundResult) {
failActive(result.error);
}
break;
@@ -1713,7 +1788,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
// For local-only commands, forward the result text to the client
if (
session.activeTurn?.isLocalOnlyCommand &&
- !isTaskNotification &&
+ !isBackgroundResult &&
message.subtype === "success" &&
message.result
) {
@@ -1726,9 +1801,21 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
});
}
- // Settle at the terminal result rather than the trailing idle,
- // which can lag behind background work.
- if (isTaskNotification) {
+ if (!isBackgroundResult && session.activeTurn) {
+ if (hasPendingSubagents()) {
+ session.activeTurn.waitingForSubagents = true;
+ break;
+ }
+ if (
+ isSubagentContinuation &&
+ !session.activeTurn.waitingForSubagents
+ ) {
+ break;
+ }
+ }
+
+ // Unrelated notifications keep their independent background lifecycle.
+ if (isBackgroundResult) {
// Background work never activates a turn, so there is no
// settle path to broadcast completion — send it directly so
// the UI still closes this reply out as its own turn instead
@@ -1825,6 +1912,29 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
"task-notification"
) {
session.backgroundTurnActive = true;
+ if (session.waitForSubagents && session.activeTurn) {
+ const origin = message.origin as { runId?: string } | undefined;
+ const content = message.message.content;
+ const text =
+ typeof content === "string"
+ ? content
+ : content
+ .filter((block) => block.type === "text")
+ .map((block) => block.text)
+ .join("\n");
+ const batch = new Set<string>();
+ for (const [taskId, runId] of completedSubagents) {
+ if (
+ origin?.runId
+ ? runId === origin.runId
+ : text.includes(`<task-id>${taskId}</task-id>`)
+ ) {
+ batch.add(taskId);
+ completedSubagents.delete(taskId);
+ }
+ }
+ subagentReplyBatches.push(batch);
+ }
}
// The SDK can echo a task notification before the previous
// background result, so that result clears the flag first. Model
@@ -3352,6 +3462,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
settingsManager,
permissionMode,
cloudMode: cloudRun,
+ waitForSubagents: meta?.mode === "background",
posthogExecPermissionRegex,
abortController,
budgetGuard: budgetGuard ?? undefined,
diff --git a/packages/agent/packages/agent/src/adapters/claude/types.ts b/packages/agent/packages/agent/src/adapters/claude/types.ts
index eebc707bba89..53524a915671 100644
--- a/packages/agent/packages/agent/src/adapters/claude/types.ts
+++ b/packages/agent/packages/agent/src/adapters/claude/types.ts
@@ -58,6 +58,7 @@ export type Turn = {
/** Result withheld while a steer has yet to reach the model. */
deferredResult?: PromptResponse;
steerTimer?: ReturnType<typeof setTimeout>;
+ waitingForSubagents?: boolean;
isLocalOnlyCommand: boolean;
commandName?: string;
/** Invoked once at activation, matching the pre-consumer broadcast timing. */
@@ -124,6 +125,8 @@ export type Session = BaseSession & {
configOptions: SessionConfigOption[];
accumulatedUsage: AccumulatedUsage;
budgetGuard?: RunBudgetGuard;
+ /** Unattended callers need the parent reply after its sub-agents finish. */
+ waitForSubagents?: boolean;
backgroundTurnActive?: boolean;
backgroundSteers?: Map<string, PendingSteer>;
backgroundSteerTimer?: ReturnType<typeof setTimeout>;
diff --git a/products/signals/backend/report_generation/select_repo.py b/products/signals/backend/report_generation/select_repo.py
index d2f0b4b14b06..6d3599e9116d 100644
--- a/products/signals/backend/report_generation/select_repo.py
+++ b/products/signals/backend/report_generation/select_repo.py
@@ -3,6 +3,7 @@
Thin wrapper around `products.tasks.backend.logic.repo_selection.select_repository`.
Renders `SignalData` to text and collapses both `RepoSelectionRejectedError`
(LLM hallucination) and `RepoSelectionUnavailableError` (no eligible repos)
+along with invalid agent output and failed sandbox runs
into `RepoSelectionResult(repository=None, ...)` — Signals has no picker
fallback, so the shared module's operational-vs-semantic distinction has
nowhere to land; `summary.py` treats `repository=None` as
@@ -27,6 +28,7 @@ from products.signals.backend.report_monitoring_provenance import (
monitoring_repository_sources,
)
from products.tasks.backend.facade import api as tasks_facade
+from products.tasks.backend.facade.agents import SandboxRunFailed
from products.tasks.backend.facade.repo_selection import (
REPO_SELECTION_DUMMY_REPOSITORY,
RepoSelectionRejectedError,
@@ -91,8 +93,8 @@ async def select_repository_for_team(
"""Select the most relevant repository for a free-form request against the team's repos.
``request_section`` is the caller-rendered string describing the request (e.g. rendered
- signals or a custom agent's initial prompt). Both rejection (LLM hallucination) and
- unavailability (no eligible repos) collapse into ``RepoSelectionResult(repository=None, ...)``
+ signals or a custom agent's initial prompt). Rejection, unavailability, invalid output,
+ and failed sandbox runs collapse into ``RepoSelectionResult(repository=None, ...)``
— Signals/custom agents have no picker fallback, so callers treat ``repository=None`` as
"no match / requires human input".
@@ -149,6 +151,13 @@ async def select_repository_for_team(
# No picker fallback — collapse operational failure into a null result.
logger.warning("repo selection unavailable: %s", exc.reason)
return RepoSelectionResult(repository=None, reason=exc.reason)
+ except (ValueError, SandboxRunFailed):
+ logger.exception("repo selection agent failed", extra={"team_id": team_id, "report_id": signal_report_id})
+ return RepoSelectionResult(
+ repository=None,
+ reason="Repository selection failed. Choose a repository to continue.",
+ autostart_eligible=False,
+ )
async def select_repository_for_report(
diff --git a/products/signals/backend/test/test_repo_corrections.py b/products/signals/backend/test/test_repo_corrections.py
index efabbeeff616..83b0640eb0d3 100644
--- a/products/signals/backend/test/test_repo_corrections.py
+++ b/products/signals/backend/test/test_repo_corrections.py
@@ -1,3 +1,4 @@
+import asyncio
from datetime import timedelta
from posthog.test.base import BaseTest
@@ -6,12 +7,15 @@ from unittest.mock import AsyncMock, patch
from django.utils import timezone
from asgiref.sync import async_to_sync
+from parameterized import parameterized
from products.signals.backend.agent_runtime import DEFAULT_RUNTIME
from products.signals.backend.artefact_schemas import Dismissal
from products.signals.backend.models import ArtefactAttribution, SignalReport, SignalReportArtefact
from products.signals.backend.repo_corrections import wrong_repo_corrections_block
from products.signals.backend.report_generation import select_repo
+from products.tasks.backend.facade.agents import SandboxRunFailed
+from products.tasks.backend.facade.repo_selection import RepoSelectionUsageLimitError
from products.tasks.backend.facade.repo_selection_types import RepoSelectionResult
@@ -108,6 +112,34 @@ class TestRepoCorrections(BaseTest):
class TestSelectRepositoryPassesCorrections(BaseTest):
+ @parameterized.expand(
+ [
+ ("invalid_output", ValueError("Invalid selection output")),
+ ("sandbox_failed", SandboxRunFailed("Selection run failed", error_type=None)),
+ ]
+ )
+ def test_agent_failure_returns_no_repository(self, _name: str, error: Exception) -> None:
+ with patch.object(select_repo, "select_repository", new=AsyncMock(side_effect=error)):
+ result = async_to_sync(select_repo.select_repository_for_team)(self.team.id, self.user.id, "context")
+
+ assert result.repository is None
+ assert result.autostart_eligible is False
+ assert "Choose a repository" in result.reason
+
+ @parameterized.expand(
+ [
+ ("canceled", asyncio.CancelledError()),
+ ("usage_limit", RepoSelectionUsageLimitError("Credits exhausted")),
+ ("unexpected", RuntimeError("Unexpected failure")),
+ ]
+ )
+ def test_other_failures_propagate(self, _name: str, error: BaseException) -> None:
+ with (
+ patch.object(select_repo, "select_repository", new=AsyncMock(side_effect=error)),
+ self.assertRaises(type(error)),
+ ):
+ async_to_sync(select_repo.select_repository_for_team)(self.team.id, self.user.id, "context")
+
def test_chokepoint_threads_corrections_into_selection(self):
select = AsyncMock(return_value=RepoSelectionResult(repository="acme/checkout", reason="ok"))
runtime = DEFAULT_RUNTIME