Skip to content

The open-source app everyone uses to manage agents at work

Fix unavailable workspace branches with an inline repair and retry (#15726)

Dottab6b3cb3761da
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index 77f9323226..1e93d8b970 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -1993,6 +1993,7 @@ export {
issueExecutionMonitorPolicySchema,
issueExecutionStateSchema,
resolveIssueRecoveryActionSchema,
+ isValidExistingBranchName,
retryWorkspaceExportSchema,
issueReviewRequestSchema,
issueExecutionWorkspaceSettingsSchema,
diff --git a/packages/shared/src/validators/index.ts b/packages/shared/src/validators/index.ts
index 448531ff66..47cf59aeb8 100644
--- a/packages/shared/src/validators/index.ts
+++ b/packages/shared/src/validators/index.ts
@@ -439,6 +439,7 @@ export {
issueExecutionStateSchema,
issueRecoveryActionReadModelSchema,
resolveIssueRecoveryActionSchema,
+ isValidExistingBranchName,
retryWorkspaceExportSchema,
issueReviewRequestSchema,
issueExecutionWorkspaceSettingsSchema,
diff --git a/packages/shared/src/validators/issue.ts b/packages/shared/src/validators/issue.ts
index f383d5bb92..8d56cc0c49 100644
--- a/packages/shared/src/validators/issue.ts
+++ b/packages/shared/src/validators/issue.ts
@@ -564,6 +564,10 @@ export const retryWorkspaceExportSchema = z.object({
export const resolveIssueRecoveryActionSchema = z
.object({
+ workspaceBaseRef: z.object({
+ requestedRef: z.string().trim().min(1).max(1024),
+ branch: z.string().trim().refine(isValidExistingBranchName, { message: "Choose a valid Git branch name" }),
+ }).strict().optional(),
executionReconciliation: z
.object({
runId: z.string().guid(),
@@ -581,6 +585,9 @@ export const resolveIssueRecoveryActionSchema = z
})
.strict()
.superRefine((value, ctx) => {
+ if (value.workspaceBaseRef && (!value.actionId || value.outcome !== "restored" || value.sourceIssueStatus !== "todo" || value.executionReconciliation)) {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["workspaceBaseRef"], message: "Branch repair must retry the exact recovery action" });
+ }
if (value.outcome === "restored") {
// A retained-source repair records evidence without changing task state.
// The route verifies the exact server-owned source and unchanged status.
diff --git a/server/src/__tests__/activity-service.test.ts b/server/src/__tests__/activity-service.test.ts
index f3c107910e..f146fc9ecc 100644
--- a/server/src/__tests__/activity-service.test.ts
+++ b/server/src/__tests__/activity-service.test.ts
@@ -254,6 +254,7 @@ describeEmbeddedPostgres("activity service", () => {
},
resultJson: {
conversationReset: true,
+ configurationIncomplete: { reason: "workspace_base_ref_unresolved", requestedRef: "main", fetchError: "private diagnostic" },
billing_type: "metered",
total_cost_usd: 0.42,
stopReason: "timeout",
@@ -295,6 +296,7 @@ describeEmbeddedPostgres("activity service", () => {
});
expect(runs[0]?.resultJson).toEqual({
conversationReset: true,
+ configurationIncomplete: { reason: "workspace_base_ref_unresolved" },
billingType: "metered",
billing_type: "metered",
costUsd: 0.42,
diff --git a/server/src/__tests__/heartbeat-process-recovery.test.ts b/server/src/__tests__/heartbeat-process-recovery.test.ts
index 541540efe0..5517583e66 100644
--- a/server/src/__tests__/heartbeat-process-recovery.test.ts
+++ b/server/src/__tests__/heartbeat-process-recovery.test.ts
@@ -1580,6 +1580,34 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
} finally { realize.mockRestore(); await fs.rm(repoRoot, { recursive: true, force: true }); }
});
+ it("keeps a repair notice on the latest run when an unresolved branch fails twice", async () => {
+ const { agentId, issueId, runId } = await seedQueuedIssueRunFixture();
+ const error = new workspaceRuntime.UnresolvedWorkspaceBaseRefError({
+ requestedRef: "main", recoveryIdentityRef: "origin/main", attemptedRefs: ["origin/main"], defaultBranch: "master",
+ });
+ const realize = vi.spyOn(workspaceRuntime, "realizeExecutionWorkspace").mockRejectedValue(error);
+ try {
+ const heartbeat = heartbeatService(db);
+ await heartbeat.resumeQueuedRuns();
+ await waitForRunToSettle(heartbeat, runId, 5_000);
+ await heartbeat.waitForRunExecutionDrain(runId);
+ const [firstAction] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, issueId));
+ const next = await heartbeat.wakeup(agentId, { source: "on_demand", triggerDetail: "manual",
+ reason: "retry_failed_run", failedRunId: runId, payload: { issueId }, contextSnapshot: { issueId },
+ requestedByActorType: "user", requestedByActorId: "responsible-user" });
+ expect(next).toHaveProperty("id");
+ await waitForRunToSettle(heartbeat, next!.id, 5_000);
+ await heartbeat.waitForRunExecutionDrain(next!.id);
+ const actions = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, issueId));
+ expect(actions).toHaveLength(1);
+ expect(actions[0]).toMatchObject({ id: firstAction.id, status: "active", evidence: { latestRunId: next!.id } });
+ const comments = await db.select().from(issueComments).where(eq(issueComments.issueId, issueId));
+ expect(comments.filter(c => c.authorType === "system" && c.metadata?.sourceRunId === next!.id)).toHaveLength(1);
+ expect(comments.filter(c => c.authorType === "system" && c.metadata?.sourceRunId === runId)).toHaveLength(1);
+ expect(mockAdapterExecute).not.toHaveBeenCalled();
+ } finally { realize.mockRestore(); }
+ });
+
it.each(["missing_default", "credential_not_shared", "database_error", "unmarked_http_error", "unmarked_forbidden", "provider_error"] as const)(
"preserves AI configuration recovery and reports only unexpected causes: %s", async (cause) => {
const { companyId, agentId, issueId, runId, wakeupRequestId } = await seedQueuedIssueRunFixture();
diff --git a/server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts b/server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts
index f6c0a9f610..5054ca63d4 100644
--- a/server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts
+++ b/server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts
@@ -2439,6 +2439,71 @@ describe("agent issue mutation checkout ownership", () => {
);
});
+ describe("repairing an unavailable starting branch", () => {
+ const repair = { actionId: recoveryActionId, outcome: "restored", sourceIssueStatus: "todo",
+ workspaceBaseRef: { requestedRef: "main", branch: "master" } };
+ function seedBranchRepair() {
+ mockAccessService.decide.mockResolvedValue({ allowed: true, reason: "allow_explicit_grant", explanation: "Allowed" });
+ const issue = makeIssue({ status: "blocked", assigneeAgentId: ownerAgentId,
+ executionWorkspaceSettings: { mode: "isolated_workspace", workspaceStrategy: { type: "git_worktree", baseRef: "main", branchTemplate: "task/{issueId}" } } });
+ mockIssueService.getById.mockResolvedValue(issue);
+ mockIssueService.update.mockImplementation(async (_id, patch) => ({ ...issue, ...patch }));
+ mockIssueRecoveryActionService.getActiveForIssue.mockResolvedValue({ id: recoveryActionId,
+ status: "active", cause: "configuration_incomplete", ownerType: "board", returnOwnerAgentId: ownerAgentId,
+ evidence: { latestRunId: ownerRunId } });
+ return createRunContextDb({}, [{ id: ownerRunId, companyId, agentId: ownerAgentId,
+ contextSnapshot: { issueId }, errorCode: "configuration_incomplete",
+ resultJson: { configurationIncomplete: { reason: "workspace_base_ref_unresolved", requestedRef: "main" } } }]);
+ }
+ it("saves the task-only branch in the recovery transaction and requests a retry", async () => {
+ const db = seedBranchRepair();
+ const res = await request(await createApp(boardActor(), db)).post(`/api/issues/${issueId}/recovery-actions/resolve`).send(repair);
+ expect(res.status, JSON.stringify(res.body)).toBe(200);
+ expect(mockIssueService.update).toHaveBeenCalledWith(issueId, expect.objectContaining({ status: "todo",
+ executionWorkspaceSettings: { mode: "isolated_workspace", workspaceStrategy: { type: "git_worktree", baseRef: "master", branchTemplate: "task/{issueId}" } },
+ }), expect.anything(), expect.anything());
+ expect(mockHeartbeatService.wakeup).toHaveBeenCalledTimes(1);
+ });
+ it("creates a valid task override when the failing branch was inherited", async () => {
+ const db = seedBranchRepair();
+ mockIssueService.getById.mockResolvedValue(makeIssue({ status: "blocked", assigneeAgentId: ownerAgentId, executionWorkspaceSettings: null }));
+ const res = await request(await createApp(boardActor(), db)).post(`/api/issues/${issueId}/recovery-actions/resolve`).send(repair);
+ expect(res.status, JSON.stringify(res.body)).toBe(200);
+ expect(mockIssueService.update).toHaveBeenCalledWith(issueId, expect.objectContaining({
+ executionWorkspaceSettings: { workspaceStrategy: { type: "git_worktree", baseRef: "master" } },
+ }), expect.anything(), expect.anything());
+ });
+ it("preserves inherited agent setup when repairing only the base branch", async () => {
+ const db = seedBranchRepair();
+ mockIssueService.getById.mockResolvedValue(makeIssue({ status: "blocked", assigneeAgentId: ownerAgentId, executionWorkspaceSettings: null }));
+ const strategy = { type: "git_worktree", baseRef: "main", provisionCommand: "npm run setup", branchTemplate: "task/{{issue.identifier}}", worktreeParentDir: ".worktrees" };
+ mockAgentService.getById.mockResolvedValue({ ...makeAgent(ownerAgentId), adapterConfig: { workspaceStrategy: strategy } });
+ const res = await request(await createApp(boardActor(), db)).post(`/api/issues/${issueId}/recovery-actions/resolve`).send(repair);
+ expect(res.status, JSON.stringify(res.body)).toBe(200);
+ expect(mockIssueService.update).toHaveBeenCalledWith(issueId, expect.objectContaining({
+ executionWorkspaceSettings: { workspaceStrategy: { ...strategy, baseRef: "master" } },
+ }), expect.anything(), expect.anything());
+ expect(strategy.baseRef).toBe("main");
+ });
+ it.each(["stale", "project", "strategy", "agent", "permission", "paused", "run", "approval", "budget", "blocker"])("rejects %s repairs without saving or waking", async gate => {
+ const db = seedBranchRepair();
+ if (gate === "project") mockIssueService.getById.mockResolvedValue(makeIssue({ status: "blocked", assigneeAgentId: ownerAgentId, projectId: "new-project" }));
+ if (gate === "strategy") mockIssueService.getById.mockResolvedValue(makeIssue({ status: "blocked", assigneeAgentId: ownerAgentId, executionWorkspaceSettings: { workspaceStrategy: { type: "adapter_managed" } } }));
+ if (gate === "permission") mockAccessService.decide.mockImplementation(async ({ action }) => ({ allowed: action !== "runtime:manage", reason: "deny_missing_grant", explanation: "No runtime permission" }));
+ if (gate === "stale") mockIssueService.getById.mockResolvedValue(makeIssue({ status: "blocked", assigneeAgentId: ownerAgentId,
+ executionWorkspaceSettings: { workspaceStrategy: { baseRef: "release" } } }));
+ if (gate === "paused") mockAgentService.getById.mockResolvedValue({ ...makeAgent(ownerAgentId), status: "paused" });
+ if (gate === "run") mockIssueService.getById.mockResolvedValue(makeIssue({ status: "blocked", assigneeAgentId: ownerAgentId, executionRunId: ownerRunId }));
+ if (gate === "approval") mockIssueApprovalService.listApprovalsForIssue.mockResolvedValue([{ status: "pending" }]);
+ if (gate === "budget") mockBudgetService.getInvocationBlock.mockResolvedValue({ scope: "agent", reason: "hard_limit_reached" });
+ if (gate === "blocker") mockIssueService.getDependencyReadiness.mockResolvedValue({ unresolvedBlockerCount: 1 });
+ const res = await request(await createApp(gate === "agent" ? ownerActor() : boardActor(), db)).post(`/api/issues/${issueId}/recovery-actions/resolve`).send(repair);
+ expect([403, 409], JSON.stringify(res.body)).toContain(res.status);
+ expect(mockIssueService.update).not.toHaveBeenCalled();
+ expect(mockHeartbeatService.wakeup).not.toHaveBeenCalled();
+ });
+ });
+
describe("retrying an escalated disposition repair", () => {
function seedRetry() {
mockIssueService.getById.mockResolvedValue(makeIssue({ status: "blocked", assigneeAgentId: ownerAgentId }));
diff --git a/server/src/__tests__/issue-recovery-actions.test.ts b/server/src/__tests__/issue-recovery-actions.test.ts
index f6f3e2149b..dd814866b5 100644
--- a/server/src/__tests__/issue-recovery-actions.test.ts
+++ b/server/src/__tests__/issue-recovery-actions.test.ts
@@ -660,17 +660,19 @@ describeEmbeddedPostgres("issue recovery actions", () => {
// The operator retries the same remote branch under two spellings. Both map
// to the canonical `origin/fix/foo` identity, so recovery must not reset the
- // attempt count or post a second notice.
+ // attempt count. Each failed run still needs its own actionable notice.
+ const firstRun = makeRun("fix/foo", "origin/fix/foo");
+ const secondRun = makeRun("origin/fix/foo", "origin/fix/foo");
await recovery.escalateStrandedAssignedIssue({
issue: sourceIssue,
previousStatus: "in_progress",
- latestRun: makeRun("fix/foo", "origin/fix/foo"),
+ latestRun: firstRun,
recoveryCause: "configuration_incomplete",
});
await recovery.escalateStrandedAssignedIssue({
issue: sourceIssue,
previousStatus: "in_progress",
- latestRun: makeRun("origin/fix/foo", "origin/fix/foo"),
+ latestRun: secondRun,
recoveryCause: "configuration_incomplete",
});
@@ -689,7 +691,12 @@ describeEmbeddedPostgres("issue recovery actions", () => {
`source_scoped_recovery:${sourceIssue.companyId}:${sourceIssue.id}:configuration_incomplete:workspace_base_ref:origin/fix/foo`,
);
- // The operator gets one notice, bound to the one action.
+ // Each run gets one notice bound to the same action; reconciling the
+ // latest run again must not duplicate its notice.
+ await recovery.escalateStrandedAssignedIssue({
+ issue: sourceIssue, previousStatus: "in_progress", latestRun: secondRun,
+ recoveryCause: "configuration_incomplete",
+ });
const notices = await db
.select({ metadata: issueComments.metadata })
.from(issueComments)
@@ -703,7 +710,8 @@ describeEmbeddedPostgres("issue recovery actions", () => {
notices.filter((row) =>
noticeMetadataReferencesRecoveryAction(row.metadata, actions[0]!.id),
),
- ).toHaveLength(1);
+ ).toHaveLength(2);
+ expect(notices.map((row) => row.metadata?.sourceRunId).sort()).toEqual([firstRun.id, secondRun.id].sort());
});
it("gives a distinct recovery identity and a new operator notice when the unresolved base ref changes", async () => {
diff --git a/server/src/__tests__/workspace-runtime.test.ts b/server/src/__tests__/workspace-runtime.test.ts
index 969635018c..021523b997 100644
--- a/server/src/__tests__/workspace-runtime.test.ts
+++ b/server/src/__tests__/workspace-runtime.test.ts
@@ -631,6 +631,21 @@ describe("resolveRuntimeProvisionCommand", () => {
});
describe("refreshRemoteTrackingBaseRef git auth", () => {
+ it("does not diagnose a missing remote branch as a rejected credential", async () => {
+ const { repoRoot } = await createClonedRepoWithRemote();
+ const warnings = await refreshRemoteTrackingBaseRef(repoRoot, "origin/main", async () => ({
+ configArgs: [],
+ env: { GIT_TERMINAL_PROMPT: "0" },
+ source: "server_environment",
+ secretName: null,
+ }));
+ expect(warnings).toHaveLength(1);
+ expect(warnings[0]).toContain("couldn't find remote ref refs/heads/main");
+ expect(warnings[0]).toContain("server-environment GitHub credential");
+ expect(warnings[0]).not.toContain("rejected");
+ expect(warnings[0]).not.toContain("authenticated with");
+ });
+
it("offers the remote URL to the provider and keeps ambient behavior when it returns null", async () => {
const { remotePath, repoRoot } = await createClonedRepoWithRemote();
const offeredUrls: string[] = [];
@@ -1256,6 +1271,27 @@ describe("realizeExecutionWorkspace", () => {
).rejects.toThrow();
});
+ it("rejects explicit main on a master-only remote and succeeds after correcting the base ref", async () => {
+ const { repoRoot } = await createClonedRepoWithRemote();
+ const error = await realizeWorktreeForTest(repoRoot, "main").catch((caught: unknown) => caught);
+ expect(error).toBeInstanceOf(UnresolvedWorkspaceBaseRefError);
+ const unresolved = error as UnresolvedWorkspaceBaseRefError;
+ expect(unresolved.requestedRef).toBe("main");
+ expect(unresolved.defaultBranch).toBe("master");
+ expect(unresolved.attemptedRefs).toEqual(["origin/main"]);
+ expect(unresolved.fetchError).toContain("couldn't find remote ref refs/heads/main");
+ expect(unresolved.message).toContain("Check that the ref exists");
+ expect(unresolved.message).not.toContain("authenticated fetch");
+ await expect(
+ fs.stat(path.join(repoRoot, ".paperclip", "worktrees", "PAP-447-add-worktree-support")),
+ ).rejects.toThrow();
+
+ const workspace = await realizeWorktreeForTest(repoRoot, "master");
+ expect(workspace.created).toBe(true);
+ expect(workspace.baseRefSha).toBe(await readGit(repoRoot, ["rev-parse", "origin/master"]));
+ expect(await readGit(workspace.cwd, ["rev-parse", "HEAD"])).toBe(workspace.baseRefSha);
+ });
+
it("gives equivalent spellings of one absent remote ref the same recovery identity", async () => {
const { repoRoot } = await createClonedRepoWithRemote();
@@ -1329,7 +1365,9 @@ describe("realizeExecutionWorkspace", () => {
} else {
// Git returns the remote name when its URL is empty, then the fetch fails.
expect(error.fetchError).toBeTruthy();
- expect(authCalls).toBe(1);
+ // Fetch and the bounded default-branch suggestion each use the credential resolver.
+ expect(authCalls).toBe(2);
+ expect(error.defaultBranch).toBeNull();
expect(readUnresolvedWorkspaceBaseRefDiagnostic(error)).toEqual({ schemaVersion: 1,
remoteLookup: "resolved", authLookup: "unavailable", fetch: "failed", fetchExitCode: 128,
fetchFailureKind: "unknown", refResolution: "failed", refExitCode: 128 });
@@ -1381,7 +1419,9 @@ process.stderr.write(${JSON.stringify(stderr)}, () => { process.exitCode = ${cod
expect(JSON.stringify(diagnostic)).not.toContain("example.invalid");
expect((await fs.readFile(calls, "utf8")).trim().split("\n").map(line => JSON.parse(line))).toEqual([
["fetch", "--prune", "origin", "+refs/heads/absent-fixture:refs/remotes/origin/absent-fixture"],
+ ["ls-remote", "--symref", "origin", "HEAD"],
]);
+ expect(error.defaultBranch).toBeNull();
});
it("rejects reusing an empty directory that only looks like a worktree because it sits inside the repo", async () => {
diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts
index 108ba69944..4ce53bce29 100644
--- a/server/src/routes/issues.ts
+++ b/server/src/routes/issues.ts
@@ -1,3 +1,4 @@
+import { parseObject } from "../adapters/utils.js";
import { hasRequiredWorkspaceRecovery, LEGACY_WORKSPACE_RECOVERY_SCHEMA } from "../services/workspace-restore-recovery-state.js";
import { monitorPoliciesEqual, applyActorMonitorScheduledBy, assertCanManageIssueMonitor, summarizeIssueMonitor } from "../services/issue-monitors.js";
import type { IssuePrivacyConstraints } from "@paperclipai/shared";
@@ -315,7 +316,7 @@ import {
redactIssueMonitorExternalRef,
setIssueExecutionPolicyMonitorScheduledBy,
} from "../services/issue-execution-policy.js";
-import { parseIssueExecutionWorkspaceSettings } from "../services/execution-workspace-policy.js";
+import { buildExecutionWorkspaceAdapterConfig, parseProjectExecutionWorkspacePolicy, parseIssueExecutionWorkspaceSettings } from "../services/execution-workspace-policy.js";
import type { PluginWorkerManager } from "../services/plugin-worker-manager.js";
import {
buildPromotedSourceTrust,
@@ -9440,11 +9441,17 @@ export function issueRoutes(
sourceIssueStatus,
resolutionNote,
executionReconciliation,
+ workspaceBaseRef,
} = req.body;
if (outcome === "false_positive" || outcome === "cancelled") {
assertBoard(req);
}
+ if (workspaceBaseRef) {
+ assertBoard(req);
+ const decision = await access.decide({ actor: req.actor, action: "runtime:manage", resource: { type: "company", companyId: existing.companyId } });
+ if (!decision.allowed) throw forbidden(decision.explanation, authorizationDeniedDetails(decision));
+ }
const actor = getActorInfo(req);
const actionStatus = outcome === "cancelled" ? "cancelled" : "resolved";
const postCommitActivityPublications: ActivityPublication[] = [];
@@ -9564,6 +9571,51 @@ export function issueRoutes(
{ source: "recovery_action_resolution" },
);
+ let repairedWorkspaceSettings: Record<string, unknown> | undefined;
+ if (workspaceBaseRef) {
+ const currentSettings = parseObject(lockedIssue.executionWorkspaceSettings);
+ const currentStrategy = parseObject(currentSettings.workspaceStrategy);
+ const sourceRunId = activeRecoveryAction.evidence.latestRunId;
+ if (typeof sourceRunId !== "string" || !isUuidLike(sourceRunId)) throw conflict("The failed run is unavailable. Refresh the task before repairing its branch.");
+ const [failedRun] = await tx.select({ contextSnapshot: heartbeatRuns.contextSnapshot, resultJson: heartbeatRuns.resultJson,
+ agentId: heartbeatRuns.agentId, errorCode: heartbeatRuns.errorCode }).from(heartbeatRuns).where(and(
+ eq(heartbeatRuns.companyId, lockedIssue.companyId),
+ eq(heartbeatRuns.id, sourceRunId),
+ ));
+ const failure = parseObject(parseObject(failedRun?.resultJson).configurationIncomplete);
+ if (lockedIssue.status !== "blocked" || activeRecoveryAction.status !== "active"
+ || activeRecoveryAction.cause !== "configuration_incomplete"
+ || activeRecoveryAction.returnOwnerAgentId !== lockedIssue.assigneeAgentId
+ || !lockedIssue.assigneeAgentId || failedRun?.agentId !== lockedIssue.assigneeAgentId
+ || parseObject(failedRun?.contextSnapshot).issueId !== lockedIssue.id
+ || (parseObject(failedRun?.contextSnapshot).projectId ?? null) !== (lockedIssue.projectId ?? null)
+ || (currentStrategy.type && currentStrategy.type !== "git_worktree")
+ || failedRun?.errorCode !== "configuration_incomplete" || failure.reason !== "workspace_base_ref_unresolved"
+ || failure.requestedRef !== workspaceBaseRef.requestedRef
+ || (typeof currentStrategy.baseRef === "string" && currentStrategy.baseRef.trim() && currentStrategy.baseRef !== workspaceBaseRef.requestedRef)
+ || workspaceBaseRef.branch === workspaceBaseRef.requestedRef) {
+ throw conflict("This branch repair no longer matches the task. Refresh before retrying.");
+ }
+ // Materialize the currently effective strategy before adding a task
+ // override, so agent defaults retain their setup and workspace layout.
+ const repairOwner = await agentsSvc.getById(lockedIssue.assigneeAgentId);
+ const repairProject = lockedIssue.projectId ? await projectsSvc.getById(lockedIssue.projectId) : null;
+ const effectiveStrategy = parseObject(buildExecutionWorkspaceAdapterConfig({
+ agentConfig: parseObject(repairOwner?.adapterConfig),
+ projectPolicy: parseProjectExecutionWorkspacePolicy(repairProject?.executionWorkspacePolicy),
+ issueSettings: parseIssueExecutionWorkspaceSettings(currentSettings),
+ mode: "isolated_workspace", legacyUseProjectWorkspace: null,
+ }).workspaceStrategy);
+ // This failure is emitted only by Git worktree preparation. With no
+ // strategy object, the runtime used its default Git worktree strategy.
+ if (!effectiveStrategy.type) effectiveStrategy.type = "git_worktree";
+ if (effectiveStrategy.type !== "git_worktree"
+ || (typeof effectiveStrategy.baseRef === "string" && effectiveStrategy.baseRef.trim() && effectiveStrategy.baseRef !== workspaceBaseRef.requestedRef)) {
+ throw conflict("The workspace configuration changed. Refresh before repairing its branch.");
+ }
+ repairedWorkspaceSettings = { ...currentSettings, workspaceStrategy: { ...effectiveStrategy, baseRef: workspaceBaseRef.branch } };
+ }
+
if (outcome === "restored" && activeRecoveryAction.cause === "native_workspace_sync_out_unsafe_archive") {
throw conflict("Unsafe workspace export recovers automatically without another provider turn.", { code: "workspace_export_automatic_recovery" });
}
@@ -9579,12 +9631,12 @@ export function issueRoutes(
if (
outcome === "restored" &&
sourceIssueStatus === "todo" &&
- activeRecoveryAction.kind === "deliberate_wait_without_target"
+ (activeRecoveryAction.kind === "deliberate_wait_without_target" || workspaceBaseRef)
) {
if (
lockedIssue.status !== "blocked" ||
activeRecoveryAction.ownerType !== "board" ||
- activeRecoveryAction.wakePolicy?.type !== "board_escalation" ||
+ (!workspaceBaseRef && activeRecoveryAction.wakePolicy?.type !== "board_escalation") ||
!activeRecoveryAction.returnOwnerAgentId ||
lockedIssue.assigneeAgentId !== activeRecoveryAction.returnOwnerAgentId
) {
@@ -9766,6 +9818,7 @@ export function issueRoutes(
const updateFields: Record<string, unknown> = {
status: sourceIssueStatus,
+ ...(repairedWorkspaceSettings ? { executionWorkspaceSettings: repairedWorkspaceSettings } : {}),
};
if (!safeHandBack) {
await assertInReviewReviewPath({
@@ -9927,6 +9980,7 @@ export function issueRoutes(
outcome: result.recoveryAction.outcome,
sourceIssueStatus: sourceIssueStatus ?? null,
resolutionNote: result.recoveryAction.resolutionNote,
+ ...(workspaceBaseRef ? { workspaceBaseRef } : {}),
},
});
diff --git a/server/src/services/activity.ts b/server/src/services/activity.ts
index d171d62966..4130ed2718 100644
--- a/server/src/services/activity.ts
+++ b/server/src/services/activity.ts
@@ -89,6 +89,8 @@ export function activityService(db: Db) {
when ${heartbeatRuns.resultJson} is null then null
else jsonb_strip_nulls(jsonb_build_object(
'conversationReset', ${heartbeatRuns.resultJson} -> 'conversationReset',
+ 'configurationIncomplete', case when ${heartbeatRuns.resultJson} -> 'configurationIncomplete' ->> 'reason' = 'workspace_base_ref_unresolved'
+ then jsonb_build_object('reason', 'workspace_base_ref_unresolved') end,
'workspaceRestoreFailure', case when ${heartbeatRuns.resultJson} ->> 'workspaceRestoreFailure'
in ('restore_permission_denied', 'restore_lock_timeout', 'restore_unsafe_archive', 'restore_failed')
then ${heartbeatRuns.resultJson} -> 'workspaceRestoreFailure' end,
diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts
index 39f6c0a7ce..b39ece2ebb 100644
--- a/server/src/services/heartbeat.ts
+++ b/server/src/services/heartbeat.ts
@@ -841,6 +841,7 @@ function buildUnresolvedWorkspaceBaseRefResultJson(
issueId: readNonEmptyString(context.issueId) ?? null,
projectId: readNonEmptyString(context.projectId) ?? null,
requestedRef: error.requestedRef,
+ defaultBranch: error.defaultBranch,
attemptedRefs: error.attemptedRefs,
fetchError: error.fetchError,
fingerprint: `workspace_base_ref:${error.recoveryIdentityRef}`,
diff --git a/server/src/services/recovery/service.ts b/server/src/services/recovery/service.ts
index 9b1a5c4439..8a90da0fe4 100644
--- a/server/src/services/recovery/service.ts
+++ b/server/src/services/recovery/service.ts
@@ -2553,7 +2553,9 @@ export function recoveryService(
? "Board operator: repair the project workspace repository URL or clone access, or configure a local checkout cwd, then explicitly retry or reassign."
: "Board operator: repair the source task workspace link, project workspace cwd, or git checkout, then explicitly retry or reassign."
: recoveryCause === "configuration_incomplete"
- ? readConfigurationIncompletePayload(input.latestRun)?.reason === "ai_connection_unavailable"
+ ? readConfigurationIncompletePayload(input.latestRun)?.reason === "workspace_base_ref_unresolved"
+ ? "Check the starting branch and repository access, then repair the task’s branch and retry the original assignee."
+ : readConfigurationIncompletePayload(input.latestRun)?.reason === "ai_connection_unavailable"
? "Reconnect the selected AI account or choose an available connection, then continue the task."
: readConfigurationIncompletePayload(input.latestRun)
?.reason === SANDBOX_PROVIDER_PLUGIN_NOT_READY_REASON
@@ -4074,10 +4076,14 @@ export function recoveryService(
.then((rows) =>
rows.some(
(row) =>
- noticeMetadataReferencesRecoveryAction(
+ (noticeMetadataReferencesRecoveryAction(
row.metadata,
recoveryAction.id,
- ) || (row.body ?? "").includes(escalationCommentMarker),
+ ) || (row.body ?? "").includes(escalationCommentMarker))
+ // Task threads attach notices to runs. A reused incident needs
+ // one notice for each failed run so its latest repair stays visible.
+ && (readConfigurationIncompletePayload(input.latestRun)?.reason !== "workspace_base_ref_unresolved"
+ || row.metadata?.sourceRunId === input.latestRun?.id),
),
);
diff --git a/server/src/services/recovery/stranded-notice.test.ts b/server/src/services/recovery/stranded-notice.test.ts
index a4b838a744..c824d684ad 100644
--- a/server/src/services/recovery/stranded-notice.test.ts
+++ b/server/src/services/recovery/stranded-notice.test.ts
@@ -67,6 +67,31 @@ describe("stranded recovery notice seeds", () => {
expect(buildConfigurationIncompleteRecoveryNoticeSeed(null).body).toContain("secret/env bindings");
});
+ it("explains an unresolved workspace base ref and carries its remedy into the recovery card", () => {
+ const seed = buildConfigurationIncompleteRecoveryNoticeSeed({
+ reason: "workspace_base_ref_unresolved",
+ requestedRef: "main",
+ attemptedRefs: ["origin/main"],
+ fetchError: "fatal: couldn't find remote ref refs/heads/main",
+ missingBindings: [],
+ });
+ const notice = buildStrandedRecoveryEscalationNotice({
+ seed,
+ recoveryActionId: "base-ref-recovery",
+ recoveryOwner: null,
+ sourceRun: { id: "failed-run", status: "failed", errorCode: "configuration_incomplete" },
+ });
+ expect(notice.presentation.title).toBe("Workspace base ref unavailable");
+ expect(notice.body).toContain("before the agent started");
+ expect(notice.body).toContain("base ref");
+ expect(notice.body).not.toContain("secret/env bindings");
+ expect(allRows(notice.metadata)).toContainEqual({
+ type: "key_value",
+ label: "Next action",
+ value: "Check that the configured base ref exists and the repository is accessible. Correct the task or project workspace settings, then retry the task.",
+ });
+ });
+
it("distinguishes todo dispatch from in_progress continuation copy", () => {
expect(buildImmediateExecutionPathRecoveryNoticeSeed({ status: "todo" }).body).toContain("retried dispatch");
expect(buildImmediateExecutionPathRecoveryNoticeSeed({ status: "in_progress" }).body).toContain(
diff --git a/server/src/services/recovery/stranded-notice.ts b/server/src/services/recovery/stranded-notice.ts
index 8d98ad3d8a..41ec1a08d9 100644
--- a/server/src/services/recovery/stranded-notice.ts
+++ b/server/src/services/recovery/stranded-notice.ts
@@ -113,6 +113,14 @@ export function sandboxProviderPluginRemedy(pluginStatus: string): string {
export function buildConfigurationIncompleteRecoveryNoticeSeed(
configurationIncomplete?: Record<string, unknown> | null,
): StrandedRecoveryNoticeSeed {
+ if (readNonEmptyStringField(configurationIncomplete, "reason") === "workspace_base_ref_unresolved") {
+ return {
+ title: "Workspace base ref unavailable",
+ body: "Paperclip stopped before the agent started because the configured workspace base ref could not be resolved to a Git commit. The task is blocked until its workspace configuration or repository access is repaired.",
+ nextAction: "Check that the configured base ref exists and the repository is accessible. Correct the task or project workspace settings, then retry the task.",
+ tone: "danger",
+ };
+ }
if (readNonEmptyStringField(configurationIncomplete, "reason") === "ai_connection_unavailable") {
return {
title: "AI connection needs attention",
diff --git a/server/src/services/workspace-runtime.ts b/server/src/services/workspace-runtime.ts
index 3adc9581e2..5c16153669 100644
--- a/server/src/services/workspace-runtime.ts
+++ b/server/src/services/workspace-runtime.ts
@@ -1,4 +1,4 @@
-import { spawn, type ChildProcess } from "node:child_process";
+import { execFile, spawn, type ChildProcess } from "node:child_process";
import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync } from "node:fs";
import fs from "node:fs/promises";
import net from "node:net";
@@ -1040,7 +1040,7 @@ async function refreshRemoteTrackingBaseRefWithDiagnostic(
.replace(/([a-z][a-z0-9+.-]*:\/\/)[^/@\s]+@/gi, "$1***@")
.replace(/([a-z][a-z0-9+.-]*:\/\/[^\s"'?]*)\?[^\s"']*/gi, "$1?***");
const authNote = auth
- ? ` The fetch authenticated with ${auth.secretName ? `the ${auth.secretName} company-secret GitHub credential` : "the server-environment GitHub credential"}, which may have been rejected.`
+ ? ` The fetch used ${auth.secretName ? `the ${auth.secretName} company-secret GitHub credential` : "the server-environment GitHub credential"}.`
: "";
return { warnings: [`Could not refresh base ref ${baseRef} before preparing the execution workspace: ${message}${authNote}`], diagnostic };
}
@@ -2434,7 +2434,7 @@ export async function ensureGitWorktreeBranchCoherent(input: {
}
// A configured base ref that does not resolve to a commit, even after an
-// authenticated fetch of its `origin/<branch>` counterpart. The caller must
+// attempted fetch of its remote-tracking counterpart. The caller must
// stop before `git worktree add` and raise a pre-dispatch configuration
// failure. `requestedRef` keeps the operator spelling for the human notice.
// `recoveryIdentityRef` is the canonical remote ref the resolver probed, so two
@@ -2446,21 +2446,25 @@ export class UnresolvedWorkspaceBaseRefError extends Error {
recoveryIdentityRef: string;
attemptedRefs: string[];
fetchError: string | null;
+ defaultBranch: string | null;
constructor(input: {
requestedRef: string;
recoveryIdentityRef: string;
attemptedRefs: string[];
fetchError?: string | null;
+ defaultBranch?: string | null;
}) {
super(
- `Configured workspace base ref "${input.requestedRef}" did not resolve to a commit on origin after an authenticated fetch.`,
+ `Configured workspace base ref "${input.requestedRef}" could not be resolved to a commit ` +
+ `(tried: ${input.attemptedRefs.join(", ")}). Check that the ref exists and the repository is accessible before retrying.`,
);
this.name = "UnresolvedWorkspaceBaseRefError";
this.requestedRef = input.requestedRef;
this.recoveryIdentityRef = input.recoveryIdentityRef;
this.attemptedRefs = input.attemptedRefs;
this.fetchError = input.fetchError ?? null;
+ this.defaultBranch = input.defaultBranch ?? null;
}
}
@@ -2749,6 +2753,24 @@ async function isGitCheckout(cwd: string): Promise<boolean> {
return Boolean(await runGit(["rev-parse", "--git-dir"], cwd).catch(() => null));
}
+// A repair suggestion must come from the remote's advertised HEAD, never the
+// runtime's main/master fallback heuristic. Failure to inspect is not a guess.
+async function readAdvertisedDefaultBranch(repoRoot: string, resolveGitAuth?: GitRemoteAuthProvider | null): Promise<string | null> {
+ try {
+ const remoteUrl = await runGit(["remote", "get-url", "origin"], repoRoot);
+ const auth = resolveGitAuth ? await resolveGitAuth(remoteUrl) : null;
+ const output = await new Promise<string>((resolve, reject) => {
+ execFile("git", [...(auth?.configArgs ?? []), "ls-remote", "--symref", "origin", "HEAD"], {
+ cwd: repoRoot, timeout: 10_000, maxBuffer: 64 * 1024,
+ env: { ...process.env, ...auth?.env, GIT_TERMINAL_PROMPT: "0" },
+ }, (error, stdout) => error ? reject(error) : resolve(stdout));
+ });
+ return /^ref: refs\/heads\/(.+)\tHEAD$/m.exec(output)?.[1] ?? null;
+ } catch {
+ return null;
+ }
+}
+
async function detectDefaultBranch(
repoRoot: string,
resolveGitAuth?: GitRemoteAuthProvider | null,
@@ -3640,6 +3662,7 @@ export async function realizeExecutionWorkspace(input: {
recoveryIdentityRef: baseRefResolution.recoveryIdentityRef,
attemptedRefs: baseRefResolution.attemptedRefs,
fetchError: baseRefResolution.fetchError,
+ defaultBranch: await readAdvertisedDefaultBranch(repoRoot, input.resolveGitAuth),
});
unresolvedBaseRefDiagnostics.set(error, readWorkspaceBaseRefDiagnostic(baseRefResolution.diagnostic)!);
throw error;
diff --git a/tests/e2e/workspace-base-ref/README.md b/tests/e2e/workspace-base-ref/README.md
new file mode 100644
index 0000000000..54f85177e8
--- /dev/null
+++ b/tests/e2e/workspace-base-ref/README.md
@@ -0,0 +1,36 @@
+# Workspace starting-branch repair acceptance
+
+This fixture uses a real Git repository with a `master` branch and no `main`
+branch. It runs a deterministic process adapter, with no external model calls.
+Use a disposable local-trusted instance. The seed changes that instance's
+experimental workspace and task-interface flags and creates a test company.
+
+1. Start a disposable Paperclip instance from this checkout. Set a separate
+ `PAPERCLIP_HOME` and port. Keep it bound to loopback in `local_trusted` mode.
+2. Run `node tests/e2e/workspace-base-ref/seed.mjs http://127.0.0.1:PORT`.
+3. Open the returned issue in the browser. Wait for it to become blocked.
+4. Confirm the thread says the starting branch is unavailable and shows the
+ branch repair card. It must not claim that secrets are missing or offer a
+ generic retry of the same broken setting.
+5. Click **Use master & retry**. The task must reach **Done**. Its agent comment
+ must report that it ran in an isolated worktree at the `origin/master` commit.
+6. Reload. Confirm the task remains Done, its task-specific base ref is `master`,
+ and its recovery action is resolved. There should be exactly two runs: the
+ initial configuration failure and a successful process run.
+
+To test custom input, seed another company and task. Choose **Choose another
+branch**. Enter `bad..branch` and submit: the inline error must keep the task
+blocked. Change it to `master` and submit. Verify the same durable result.
+
+The worker uses its authenticated run API to obtain its actual workspace and
+mark its own task complete. It checks both the fixture file and the Git commit
+before doing so. A saved setting or simulated Storybook success alone does not
+satisfy this acceptance check.
+
+The component stories are under **Workspace branch recovery**. Their save and
+retry callbacks are simulated; use this fixture for the real server journey.
+
+Pass `--agent-defaults` to the seed command to put the missing base branch,
+setup command, branch template, and worktree directory in agent defaults.
+The task has no strategy override. On repair, the worker also verifies that
+inherited setup ran and the branch template and worktree directory survived.
diff --git a/tests/e2e/workspace-base-ref/seed.mjs b/tests/e2e/workspace-base-ref/seed.mjs
new file mode 100644
index 0000000000..17ab49ad40
--- /dev/null
+++ b/tests/e2e/workspace-base-ref/seed.mjs
@@ -0,0 +1,41 @@
+import assert from "node:assert/strict";
+import { mkdtemp, writeFile } from "node:fs/promises";
+import { execFileSync } from "node:child_process";
+import os from "node:os";
+import path from "node:path";
+import { pathToFileURL } from "node:url";
+
+export async function seedBranchRepair(base, { inheritAgentStrategy = false } = {}) {
+ assert.equal(new URL(base).hostname, "127.0.0.1", "Use a disposable loopback instance");
+ const api = async (route, method = "GET", body) => {
+ const response = await fetch(`${base}/api${route}`, { method, headers: { "Content-Type": "application/json" }, body: body ? JSON.stringify(body) : undefined });
+ assert(response.ok, `${response.status}: ${await response.clone().text()}`);
+ return response.json();
+ };
+ assert.equal((await api("/health")).deploymentMode, "local_trusted");
+ await api("/instance/settings/experimental", "PATCH", { enableIsolatedWorkspaces: true, enableClassicTaskInterface: false });
+ const company = await api("/companies", "POST", { name: "Branch Repair Acceptance" });
+ const root = await mkdtemp(path.join(os.tmpdir(), "branch-repair-"));
+ const source = path.join(root, "source"), remote = path.join(root, "origin.git"), checkout = path.join(root, "checkout");
+ const git = (...args) => execFileSync("git", args, { cwd: root, stdio: "ignore" });
+ git("init", "-b", "master", source);
+ await writeFile(path.join(source, "README.md"), "Branch repair acceptance fixture\n");
+ git("-C", source, "add", ".");
+ git("-C", source, "-c", "user.name=Acceptance", "-c", "[email protected]", "commit", "-m", "fixture");
+ git("clone", "--bare", source, remote);
+ git("clone", remote, checkout);
+ const project = await api(`/companies/${company.id}/projects`, "POST", { name: "Master-only repository", status: "in_progress",
+ workspace: { name: "Repository", cwd: checkout, repoUrl: pathToFileURL(remote).href, isPrimary: true },
+ executionWorkspacePolicy: { enabled: true, defaultMode: "isolated_workspace", allowIssueOverride: true, ...(inheritAgentStrategy ? {} : { workspaceStrategy: { type: "git_worktree" } }) },
+ });
+ const agent = await api(`/companies/${company.id}/agents`, "POST", { name: "Branch verification worker", role: "engineer", adapterType: "process",
+ adapterConfig: { command: process.execPath, args: [path.resolve(import.meta.dirname, "worker.mjs"), ...(inheritAgentStrategy ? ["--expect-setup"] : [])],
+ ...(inheritAgentStrategy ? { workspaceStrategy: { type: "git_worktree", baseRef: "main", branchTemplate: "agent/{{issue.identifier}}", worktreeParentDir: ".agent-worktrees", provisionCommand: `node -e "require('node:fs').writeFileSync('setup-proof.txt', 'ready')"` } } : {}) },
+ runtimeConfig: { heartbeat: { enabled: false, wakeOnDemand: true } },
+ });
+ const issue = await api(`/companies/${company.id}/issues`, "POST", { title: "Repair the missing starting branch", status: "todo", projectId: project.id, assigneeAgentId: agent.id,
+ executionWorkspacePreference: "isolated_workspace", executionWorkspaceSettings: { mode: "isolated_workspace", ...(inheritAgentStrategy ? {} : { workspaceStrategy: { type: "git_worktree", baseRef: "main" } }) },
+ });
+ return { base, companyId: company.id, issueId: issue.id, identifier: issue.identifier, prefix: company.issuePrefix, agentId: agent.id, projectId: project.id, root, checkout };
+}
+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) console.log(JSON.stringify(await seedBranchRepair(process.argv[2], { inheritAgentStrategy: process.argv.includes("--agent-defaults") })));
diff --git a/tests/e2e/workspace-base-ref/worker.mjs b/tests/e2e/workspace-base-ref/worker.mjs
new file mode 100644
index 0000000000..90252e59e5
--- /dev/null
+++ b/tests/e2e/workspace-base-ref/worker.mjs
@@ -0,0 +1,23 @@
+// Real process adapter: verify Git and complete through the run-scoped API.
+import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
+import { readFile } from "node:fs/promises";
+const git = (...args) => execFileSync("git", args, { encoding: "utf8" }).trim();
+const headers = { Authorization: `Bearer ${process.env.PAPERCLIP_API_KEY}`, "X-Paperclip-Run-Id": process.env.PAPERCLIP_RUN_ID, "Content-Type": "application/json" };
+const api = async (route, method = "GET", body) => {
+ const response = await fetch(`${process.env.PAPERCLIP_API_URL}/api${route}`, { method, headers, body: body ? JSON.stringify(body) : undefined });
+ assert(response.ok, `${response.status}: ${await response.clone().text()}`);
+ return response.json();
+};
+const run = await api(`/heartbeat-runs/${process.env.PAPERCLIP_RUN_ID}`);
+assert.equal(run.contextSnapshot.paperclipWorkspace.mode, "isolated_workspace");
+process.chdir(run.contextSnapshot.paperclipWorkspace.cwd);
+assert.equal(await readFile("README.md", "utf8"), "Branch repair acceptance fixture\n");
+if (process.argv.includes("--expect-setup")) {
+ assert.equal(await readFile("setup-proof.txt", "utf8"), "ready");
+ assert.match(git("branch", "--show-current"), /^agent\//);
+ assert.match(process.cwd(), /\.agent-worktrees/);
+}
+assert.equal(git("rev-parse", "HEAD"), git("rev-parse", "origin/master"));
+await api(`/issues/${run.contextSnapshot.issueId}`, "PATCH", { status: "done", comment: `Branch repair verified: the agent started in an isolated worktree at master (${git("rev-parse", "HEAD")}).` });
+console.log("Branch repair verified in the real Git worktree.");
diff --git a/ui/src/api/issues.ts b/ui/src/api/issues.ts
index 4b057f5e77..540a8d1b6d 100644
--- a/ui/src/api/issues.ts
+++ b/ui/src/api/issues.ts
@@ -284,6 +284,7 @@ export const issuesApi = {
id: string,
data: {
executionReconciliation?: ExecutionReconciliation;
+ workspaceBaseRef?: { requestedRef: string; branch: string };
actionId?: string;
outcome: "restored" | "false_positive" | "blocked" | "cancelled";
sourceIssueStatus: "todo" | "done" | "in_review" | "blocked";
diff --git a/ui/src/components/IssueChatThread.tsx b/ui/src/components/IssueChatThread.tsx
index 4a9aef03b1..22d611d962 100644
--- a/ui/src/components/IssueChatThread.tsx
+++ b/ui/src/components/IssueChatThread.tsx
@@ -1,3 +1,5 @@
+import { useWorkspaceBaseRefRecovery } from "./WorkspaceBaseRefRecovery";
+import { WorkspaceBaseRefRecoveryNotice } from "./WorkspaceBaseRefRecoveryNotice";
import { DispositionRecoveryNotice, useDispositionRecoverySnapshot } from "./DispositionRecoveryNotice";
import { AgentAvatar } from "@/components/AgentAvatar";
import type { ComposerRunSettings } from "./task-chat/composer-run-settings";
@@ -3518,6 +3520,7 @@ function SystemNoticeCommentContent({
? custom.commentMetadata
: null;
const recoverySnapshot = useDispositionRecoverySnapshot(commentMetadata);
+ const branchRecovery = useWorkspaceBaseRefRecovery(commentMetadata);
const runAgentId =
typeof custom.runAgentId === "string" ? custom.runAgentId : null;
const runId = typeof custom.runId === "string" ? custom.runId : null;
@@ -3614,6 +3617,8 @@ function SystemNoticeCommentContent({
});
};
+ if (authorType === "system" && branchRecovery) return <div id={anchorId}><WorkspaceBaseRefRecoveryNotice key={`${branchRecovery.actionId}:${branchRecovery.runId}`} {...branchRecovery.props} /></div>;
+
if (authorType === "system" && recoverySnapshot) {
return <div id={anchorId}><DispositionRecoveryNotice snapshot={recoverySnapshot} createdAt={toValidIsoString(message.createdAt)} defaultExpanded={presentation?.detailsDefaultOpen} /></div>;
}
diff --git a/ui/src/components/TaskChatThread.test.tsx b/ui/src/components/TaskChatThread.test.tsx
index 6cbf89c6d9..7da26219cf 100644
--- a/ui/src/components/TaskChatThread.test.tsx
+++ b/ui/src/components/TaskChatThread.test.tsx
@@ -1011,6 +1011,18 @@ describe("TaskChatThread runtime transcript selection", () => {
expect(container.textContent).not.toContain("Workspace restore failed");
});
+ it("directs a missing starting branch to repair instead of offering an unchanged retry", () => {
+ render(<TaskChatThread comments={[]} onAdd={async () => {}} issueStatus="blocked" onRetryFailedRun={vi.fn()} linkedRuns={[{
+ runId: "missing-branch-run", runtimeMode: "legacy", status: "failed", errorCode: "configuration_incomplete",
+ agentId: "agent-1", agentName: "Worker", adapterType: "claude_local",
+ createdAt: "2026-08-25T18:00:00.000Z", startedAt: null, finishedAt: "2026-08-25T18:00:02.000Z",
+ resultJson: { configurationIncomplete: { reason: "workspace_base_ref_unresolved", requestedRef: "main" } },
+ }]} />);
+ expect(container.textContent).toContain("Starting branch unavailable");
+ expect(container.textContent).toContain("Repair the starting branch below before retrying.");
+ expect(container.querySelector('[data-testid="task-chat-run-failed-try-again"]')).toBeNull();
+ });
+
it("directs a missing personal AI credential to its card without offering a premature retry", () => {
render(<TaskChatThread comments={[]} onAdd={async () => {}} issueStatus="blocked"
onRetryFailedRun={vi.fn()} interactions={[{
diff --git a/ui/src/components/TaskChatThread.tsx b/ui/src/components/TaskChatThread.tsx
index 9902a3e035..f0873c93ac 100644
--- a/ui/src/components/TaskChatThread.tsx
+++ b/ui/src/components/TaskChatThread.tsx
@@ -1716,11 +1716,14 @@ export function TaskChatThread(props: TaskChatThreadProps) {
? "You can retry this message now."
: "Your message is preserved.";
const restoreFailed = hasWorkspaceRestoreFailure(meta?.resultJson);
+ const branchUnavailable = (meta?.resultJson?.configurationIncomplete as Record<string, unknown> | undefined)?.reason === "workspace_base_ref_unresolved";
const savedPlan = Boolean(planDocument && (meta?.resultJson?.savedPlanRevisionId === planDocument.latestRevisionId || interactions?.some((interaction) =>
interaction.sourceRunId === source.id && interactionTargetsPlanRevision(interaction, planDocument),
)));
const aiRequest = interactions?.find((interaction) => interaction.kind === "connection_intent" && interaction.payload.purpose === "ai" && interaction.sourceRunId === source.id);
- const detail = restoreFailed
+ const detail = branchUnavailable
+ ? "Repair the starting branch below before retrying."
+ : restoreFailed
? workspaceRestoreMarkerDetail({ result: meta?.resultJson, savedPlan, hasResponse: sourceHasPresentationComment || Boolean(acceptedSummary) })
: aiRequest
? aiRequest.status === "pending"
@@ -1744,9 +1747,9 @@ export function TaskChatThread(props: TaskChatThreadProps) {
id,
kind: "marker",
variant: "interrupted",
- label: restoreFailed ? "Workspace restore failed" : aiRequest?.status === "pending" ? "AI connection needed" : source.status === "cancelled" ? (meta?.startedAt ? "Stopped" : "Couldn't start") : "Run failed",
+ label: branchUnavailable ? "Starting branch unavailable" : restoreFailed ? "Workspace restore failed" : aiRequest?.status === "pending" ? "AI connection needed" : source.status === "cancelled" ? (meta?.startedAt ? "Stopped" : "Couldn't start") : "Run failed",
runId: source.status === "cancelled" ? undefined : source.id,
- ...(aiRequest?.status === "pending" ? { retryable: false } : {}),
+ ...(branchUnavailable || aiRequest?.status === "pending" ? { retryable: false } : {}),
...(restoreFailed ? {
retryable: meta?.resultJson?.workspaceRestoreFailure !== "restore_unsafe_archive",
collapsible: true,
diff --git a/ui/src/components/WorkspaceBaseRefRecovery.test.tsx b/ui/src/components/WorkspaceBaseRefRecovery.test.tsx
new file mode 100644
index 0000000000..221b52dc41
--- /dev/null
+++ b/ui/src/components/WorkspaceBaseRefRecovery.test.tsx
@@ -0,0 +1,66 @@
+// @vitest-environment jsdom
+import { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import type { Issue, IssueCommentMetadata } from "@paperclipai/shared";
+import { WorkspaceBaseRefRecoveryProvider, useWorkspaceBaseRefRecovery } from "./WorkspaceBaseRefRecovery";
+import { WorkspaceBaseRefRecoveryNotice } from "./WorkspaceBaseRefRecoveryNotice";
+
+const mocks = vi.hoisted(() => ({ get: vi.fn(), resolve: vi.fn() }));
+vi.mock("../api/heartbeats", () => ({ heartbeatsApi: { get: mocks.get } }));
+vi.mock("../api/issues", () => ({ issuesApi: { resolveRecoveryAction: mocks.resolve } }));
+const issue = { id: "issue", companyId: "company", status: "blocked", assigneeAgentId: "agent",
+ executionWorkspaceSettings: { workspaceStrategy: { baseRef: "main" } },
+ activeRecoveryAction: { id: "action", status: "active", cause: "configuration_incomplete", returnOwnerAgentId: "agent", evidence: { latestRunId: "run" } },
+} as unknown as Issue;
+const metadata: IssueCommentMetadata = { version: 1, sourceRunId: "run", sections: [{ rows: [{ type: "key_value", label: "Recovery action", value: "action" }] }] };
+function Consumer({ data = metadata }: { data?: IssueCommentMetadata }) {
+ const value = useWorkspaceBaseRefRecovery(data);
+ return value ? <WorkspaceBaseRefRecoveryNotice {...value.props} /> : <p>No repair</p>;
+}
+let container: HTMLDivElement, root: Root, client: QueryClient;
+beforeEach(() => {
+ container = document.createElement("div"); document.body.append(container); root = createRoot(container);
+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ mocks.resolve.mockReset();
+ mocks.get.mockResolvedValue({ companyId: "company", agentId: "agent", contextSnapshot: { issueId: "issue" },
+ resultJson: { configurationIncomplete: { reason: "workspace_base_ref_unresolved", requestedRef: "main", defaultBranch: "master" } } });
+});
+afterEach(async () => { await act(async () => root.unmount()); client.clear(); container.remove(); });
+async function render(data = metadata, unavailableReason: string | null = null) {
+ await act(async () => {
+ root.render(<QueryClientProvider client={client}><WorkspaceBaseRefRecoveryProvider issue={issue}
+ agentMap={new Map([["agent", { name: "Worker", status: "idle" }]])} unavailableReason={unavailableReason} onRepaired={() => {}}>
+ <Consumer data={data} /></WorkspaceBaseRefRecoveryProvider></QueryClientProvider>);
+ await new Promise(resolve => setTimeout(resolve, 0));
+ });
+ await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); });
+}
+it("binds the repair to the exact notice and sends an atomic recovery request", async () => {
+ mocks.resolve.mockResolvedValue({ issue: { ...issue, status: "todo", executionWorkspaceSettings: { workspaceStrategy: { baseRef: "master" } } } });
+ await render();
+ const button = [...container.querySelectorAll("button")].find(b => b.textContent === "Use master & retry")!;
+ await act(async () => button.click());
+ expect(mocks.resolve).toHaveBeenCalledExactlyOnceWith("issue", { actionId: "action", outcome: "restored", sourceIssueStatus: "todo", workspaceBaseRef: { requestedRef: "main", branch: "master" } });
+ expect(container.textContent).toContain("Branch updated · retry requested");
+});
+it("does not turn an unrelated notice into a repair", async () => {
+ await render({ ...metadata, sections: [{ rows: [{ type: "key_value", label: "Recovery action", value: "other-action" }] }] });
+ expect(container.textContent).toBe("No repair");
+});
+it("does not report success from an incomplete receipt", async () => {
+ mocks.resolve.mockResolvedValue({ issue });
+ await render();
+ await act(async () => [...container.querySelectorAll("button")].find(b => b.textContent === "Use master & retry")!.click());
+ expect(container.querySelector('[role="alert"]')?.textContent).toContain("The task changed while saving");
+ expect(container.textContent).not.toContain("Branch updated · retry requested");
+});
+
+it("renders only the latest run notice when a repeated failure reuses the incident", async () => {
+ await render({ ...metadata, sourceRunId: "first-failed-run" });
+ expect(container.textContent).toBe("No repair");
+ await render(metadata);
+ expect(mocks.get).toHaveBeenCalledWith("run");
+ expect(container.textContent).toContain("Use master & retry");
+});
diff --git a/ui/src/components/WorkspaceBaseRefRecovery.tsx b/ui/src/components/WorkspaceBaseRefRecovery.tsx
new file mode 100644
index 0000000000..7c3e11935e
--- /dev/null
+++ b/ui/src/components/WorkspaceBaseRefRecovery.tsx
@@ -0,0 +1,77 @@
+import { createContext, useContext, type ReactNode } from "react";
+import { useQuery } from "@tanstack/react-query";
+import type { Agent, Issue, IssueCommentMetadata } from "@paperclipai/shared";
+import { heartbeatsApi } from "../api/heartbeats";
+import { issuesApi } from "../api/issues";
+import type { WorkspaceBaseRefRecoveryNoticeProps } from "./WorkspaceBaseRefRecoveryNotice";
+
+function record(value: unknown): Record<string, unknown> {
+ return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
+}
+
+type RecoveryValue = { actionId: string; runId: string; props: WorkspaceBaseRefRecoveryNoticeProps };
+const Context = createContext<RecoveryValue | null>(null);
+
+/** Bind the repair to the server-owned action and its latest failed run. */
+export function useWorkspaceBaseRefRecovery(metadata: IssueCommentMetadata | null | undefined) {
+ const value = useContext(Context);
+ return value && metadata?.sourceRunId === value.runId
+ && metadata.sections.some(section => section.rows.some(row => row.type === "key_value" && row.value === value.actionId))
+ ? value : null;
+}
+
+export function WorkspaceBaseRefRecoveryProvider({ issue, agentMap, unavailableReason, onRepaired, children }: {
+ issue: Issue;
+ agentMap: ReadonlyMap<string, Pick<Agent, "name" | "status">>;
+ unavailableReason: string | null;
+ onRepaired: () => void;
+ children: ReactNode;
+}) {
+ const action = issue.activeRecoveryAction;
+ const runId = action?.cause === "configuration_incomplete" && typeof action.evidence.latestRunId === "string"
+ ? action.evidence.latestRunId : null;
+ const { data: run } = useQuery({
+ queryKey: ["workspace-base-ref-recovery", issue.companyId, issue.id, runId],
+ queryFn: () => heartbeatsApi.get(runId!), enabled: Boolean(runId), staleTime: Infinity, retry: false,
+ });
+ const failure = record(record(run?.resultJson).configurationIncomplete);
+ let value: RecoveryValue | null = null;
+ if (action && runId && run?.companyId === issue.companyId && record(run.contextSnapshot).issueId === issue.id
+ && failure.reason === "workspace_base_ref_unresolved" && typeof failure.requestedRef === "string") {
+ const agent = issue.assigneeAgentId ? agentMap.get(issue.assigneeAgentId) : undefined;
+ const requestedRef = failure.requestedRef;
+ const workspace = issue.project?.workspaces?.find(w => w.id === issue.projectWorkspaceId)
+ ?? issue.project?.primaryWorkspace;
+ let repository = "The task’s repository";
+ if (workspace?.repoUrl) {
+ try { const url = new URL(workspace.repoUrl); if (url.protocol === "https:" || url.protocol === "http:") repository = `${url.hostname}${url.pathname.replace(/\.git$/, "")}`; } catch { /* Keep local paths and credentials out of the card. */ }
+ }
+ const settings = record(issue.executionWorkspaceSettings);
+ const currentRef = record(settings.workspaceStrategy).baseRef;
+ const stale = action.status !== "active" || issue.status !== "blocked" || issue.assigneeAgentId !== action.returnOwnerAgentId
+ || run.agentId !== issue.assigneeAgentId || (typeof currentRef === "string" && Boolean(currentRef.trim()) && currentRef !== requestedRef);
+ const reason = stale ? "This repair no longer matches the task. Refresh to review its current state."
+ : unavailableReason
+ ?? (issue.executionRunId || issue.checkoutRunId ? "Wait for the current run to finish." : null)
+ ?? (agent?.status === "paused" || agent?.status === "terminated" ? "The assigned agent is unavailable." : null)
+ ?? (issue.executionState?.status === "pending" ? "Complete the pending review or approval before retrying." : null)
+ ?? (issue.blockedBy?.some(b => b.status !== "done" && b.status !== "cancelled") ? "Resolve the task’s blockers before retrying." : null);
+ value = { actionId: action.id, runId, props: {
+ requestedRef, repository, taskOverride: currentRef === requestedRef, defaultBranch: typeof failure.defaultBranch === "string" ? failure.defaultBranch : null,
+ agentName: agent?.name ?? "The assigned agent", unavailableReason: reason,
+ failureKind: typeof failure.fetchError === "string" && failure.fetchError.includes(`couldn't find remote ref refs/heads/${requestedRef}`) ? "missing_branch" : "unresolved_ref",
+ onRepair: async branch => {
+ try {
+ const receipt = await issuesApi.resolveRecoveryAction(issue.id, {
+ actionId: action.id, outcome: "restored", sourceIssueStatus: "todo", workspaceBaseRef: { requestedRef, branch },
+ });
+ if (receipt.issue.status !== "todo" || receipt.issue.assigneeAgentId !== issue.assigneeAgentId
+ || record(record(receipt.issue.executionWorkspaceSettings).workspaceStrategy).baseRef !== branch) {
+ throw new Error("The task changed while saving. Refresh to check its current state.");
+ }
+ } finally { onRepaired(); }
+ },
+ } };
+ }
+ return <Context.Provider value={value}>{children}</Context.Provider>;
+}
diff --git a/ui/src/components/WorkspaceBaseRefRecoveryNotice.test.tsx b/ui/src/components/WorkspaceBaseRefRecoveryNotice.test.tsx
new file mode 100644
index 0000000000..103d247315
--- /dev/null
+++ b/ui/src/components/WorkspaceBaseRefRecoveryNotice.test.tsx
@@ -0,0 +1,73 @@
+// @vitest-environment jsdom
+import { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { WorkspaceBaseRefRecoveryNotice, type WorkspaceBaseRefRecoveryNoticeProps } from "./WorkspaceBaseRefRecoveryNotice";
+
+const evidence = { requestedRef: "main", repository: "paperclipai/paperclip", defaultBranch: "master", agentName: "Felix", failureKind: "missing_branch" as const };
+describe("workspace branch repair", () => {
+ let container: HTMLDivElement;
+ let root: Root;
+ beforeEach(() => { container = document.createElement("div"); document.body.append(container); root = createRoot(container); });
+ afterEach(async () => { await act(async () => root.unmount()); container.remove(); });
+ const button = (name: string) => Array.from(container.querySelectorAll("button")).find(b => b.textContent === name)!;
+ const render = async (props: Partial<WorkspaceBaseRefRecoveryNoticeProps> = {}) => act(async () => { root.render(<WorkspaceBaseRefRecoveryNotice {...evidence} onRepair={async () => {}} {...props} />); });
+
+ it("shows the missing branch and verified default without a secrets diagnosis", async () => {
+ await render();
+ expect(container.textContent).toContain("Branch main was not found");
+ expect(container.textContent).toContain("Felix hasn’t started");
+ expect(container.textContent).not.toContain("secret");
+ expect(button("Use master & retry").disabled).toBe(false);
+ expect(container.textContent).toContain("Changes only this task");
+ });
+ it("waits for a repair receipt and prevents duplicate submissions", async () => {
+ let finish!: () => void;
+ const repair = vi.fn(() => new Promise<void>(resolve => { finish = resolve; }));
+ await render({ onRepair: repair });
+ await act(async () => { button("Use master & retry").click(); button("Use master & retry")?.click(); });
+ expect(repair).toHaveBeenCalledExactlyOnceWith("master");
+ expect(button("Saving & requesting retry…").disabled).toBe(true);
+ expect(container.textContent).not.toContain("Branch updated");
+ await act(async () => finish());
+ expect(container.textContent).toContain("Branch updated · retry requested");
+ expect(button("Use master & retry")).toBeUndefined();
+ });
+ it("keeps a custom branch after failure and permits correction", async () => {
+ const repair = vi.fn().mockRejectedValue(new Error("Branch was not found."));
+ await render({ onRepair: repair });
+ await act(async () => button("Choose another branch").click());
+ const input = container.querySelector("input")!;
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, "release/next");
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ await act(async () => container.querySelector("form")!.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true })));
+ expect(repair).toHaveBeenCalledExactlyOnceWith("release/next");
+ expect(input.value).toBe("release/next");
+ expect(container.querySelector('[role="alert"]')?.textContent).toContain("Branch was not found");
+ expect(button("Save branch & retry").disabled).toBe(false);
+ expect(container.textContent).not.toContain("Branch updated");
+ });
+ it("rejects invalid branch syntax before sending a repair", async () => {
+ const repair = vi.fn();
+ await render({ onRepair: repair, defaultBranch: "bad..branch" });
+ await act(async () => button("Use bad..branch & retry").click());
+ expect(repair).not.toHaveBeenCalled();
+ expect(container.querySelector('[role="alert"]')?.textContent).toContain("Enter a valid branch name");
+ });
+ it("does not guess a default branch or call an unresolved ref missing", async () => {
+ await render({ defaultBranch: null, failureKind: "unresolved_ref" });
+ expect(button("Use master & retry")).toBeUndefined();
+ expect(container.textContent).not.toContain("has no branch");
+ expect(container.querySelector("input")?.value).toBe("");
+ expect(button("Save branch & retry").disabled).toBe(true);
+ });
+ it("does not submit a disabled repair", async () => {
+ const repair = vi.fn();
+ await render({ onRepair: repair, unavailableReason: "The task is paused." });
+ expect(button("Use master & retry").disabled).toBe(true);
+ await act(async () => button("Use master & retry").click());
+ expect(repair).not.toHaveBeenCalled();
+ });
+});
diff --git a/ui/src/components/WorkspaceBaseRefRecoveryNotice.tsx b/ui/src/components/WorkspaceBaseRefRecoveryNotice.tsx
new file mode 100644
index 0000000000..d8082b6804
--- /dev/null
+++ b/ui/src/components/WorkspaceBaseRefRecoveryNotice.tsx
@@ -0,0 +1,122 @@
+import { useId, useRef, useState } from "react";
+import { isValidExistingBranchName } from "@paperclipai/shared";
+import { Check, ChevronDown, GitBranch, Loader2, TriangleAlert } from "lucide-react";
+import { Button } from "./ui/button";
+import { Input } from "./ui/input";
+import { Label } from "./ui/label";
+import { SystemNoticeMetadataSections } from "./SystemNotice";
+import { cn } from "../lib/utils";
+
+export interface WorkspaceBaseRefRecoveryNoticeProps {
+ requestedRef: string;
+ repository: string;
+ /** Only supply a default confirmed by the repository, never a guessed main/master. */
+ defaultBranch?: string | null;
+ agentName: string;
+ /** Verified provenance, when available. */
+ configuredBy?: string | null;
+ taskOverride?: boolean;
+ failureKind?: "missing_branch" | "unresolved_ref";
+ unavailableReason?: string | null;
+ /** Resolve only after both the task setting and retry have server receipts. */
+ onRepair: (branch: string) => Promise<void>;
+}
+
+/** Inline task repair, also used by the interactive Storybook preview. */
+export function WorkspaceBaseRefRecoveryNotice({
+ requestedRef, repository, defaultBranch, agentName, configuredBy,
+ taskOverride = true, failureKind = "unresolved_ref", unavailableReason, onRepair,
+}: WorkspaceBaseRefRecoveryNoticeProps) {
+ const id = useId();
+ const [editing, setEditing] = useState(!defaultBranch);
+ const [branch, setBranch] = useState(defaultBranch ?? "");
+ const [details, setDetails] = useState(false);
+ const [pending, setPending] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [repairedBranch, setRepairedBranch] = useState<string | null>(null);
+ const inFlight = useRef(false);
+ const changed = branch.trim().length > 0 && branch.trim() !== requestedRef;
+
+ async function repair(nextBranch: string) {
+ const value = nextBranch.trim();
+ if (!value || value === requestedRef || unavailableReason || inFlight.current || repairedBranch) return;
+ if (!isValidExistingBranchName(value)) {
+ setError("Enter a valid branch name, such as master or release/next.");
+ return;
+ }
+ inFlight.current = true;
+ setPending(true);
+ setError(null);
+ try {
+ await onRepair(value);
+ setRepairedBranch(value);
+ } catch (cause) {
+ setError(cause instanceof Error ? cause.message : "Refresh the task to check its current state, then try again.");
+ } finally {
+ inFlight.current = false;
+ setPending(false);
+ }
+ }
+
+ return (
+ <section aria-labelledby={`${id}-title`} className="flex min-w-0 gap-3 rounded-lg border border-border bg-muted/20 p-4" data-testid="workspace-base-ref-recovery">
+ {repairedBranch
+ ? <Check aria-hidden className="mt-0.5 size-4 shrink-0 text-(--status-task-icon-done)" />
+ : <TriangleAlert aria-hidden className="mt-0.5 size-4 shrink-0 text-(--status-task-icon-blocked)" />}
+ <div className="flex min-w-0 flex-1 flex-col gap-3">
+ <div className="flex flex-col gap-1" role="status" aria-live="polite">
+ <h2 id={`${id}-title`} className="break-words text-sm font-semibold">
+ {repairedBranch ? "Branch updated · retry requested" : failureKind === "missing_branch" ? <>Branch <code className="font-mono">{requestedRef}</code> was not found</> : <>Couldn’t use branch <code className="font-mono">{requestedRef}</code></>}
+ </h2>
+ <p className="text-sm leading-relaxed text-muted-foreground">
+ {repairedBranch
+ ? <>This task now starts from <code className="font-mono text-foreground">{repairedBranch}</code>. A retry has been requested for {agentName}.</>
+ : <><span className="break-all text-foreground">{repository}</span>{failureKind === "missing_branch" ? <> has no branch named <code className="font-mono text-foreground">{requestedRef}</code>.</> : " could not resolve the starting branch. Check the branch name and repository access."} {agentName} hasn’t started.</>}
+ </p>
+ </div>
+ {!repairedBranch && (
+ <>
+ {defaultBranch && !editing && <p className="flex flex-wrap items-center gap-1.5 text-sm"><GitBranch aria-hidden className="size-4 text-muted-foreground" /><code className="font-mono">{defaultBranch}</code><span className="text-muted-foreground">is the repository’s default branch.</span></p>}
+ <p className="text-xs text-muted-foreground">Changes only this task’s starting branch.</p>
+ {unavailableReason && <p id={`${id}-unavailable`} className="text-sm text-muted-foreground">{unavailableReason}</p>}
+ {error && <p role="alert" id={`${id}-error`} className="text-sm text-destructive">Couldn’t confirm the repair. {error}</p>}
+ {editing ? (
+ <form className="flex flex-col gap-3" onSubmit={event => { event.preventDefault(); void repair(branch); }}>
+ <div className="flex flex-col gap-1.5">
+ <Label htmlFor={`${id}-branch`}>Starting branch</Label>
+ <Input id={`${id}-branch`} autoFocus value={branch} disabled={pending || Boolean(unavailableReason)} onChange={event => setBranch(event.target.value)} placeholder="Branch name" className="font-mono" aria-describedby={error ? `${id}-error` : undefined} autoComplete="off" spellCheck={false} />
+ </div>
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ {defaultBranch ? <Button type="button" variant="ghost" size="sm" disabled={pending} onClick={() => { setEditing(false); setError(null); }}>Cancel</Button> : <span />}
+ <Button type="submit" size="sm" disabled={pending || !changed || Boolean(unavailableReason)} aria-describedby={unavailableReason ? `${id}-unavailable` : undefined}>
+ {pending && <Loader2 aria-hidden className="size-3.5 animate-spin motion-reduce:animate-none" />}{pending ? "Saving & requesting retry…" : "Save branch & retry"}
+ </Button>
+ </div>
+ </form>
+ ) : (
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <Button type="button" variant="ghost" size="sm" disabled={pending || Boolean(unavailableReason)} onClick={() => setEditing(true)}>Choose another branch</Button>
+ <Button type="button" size="sm" disabled={pending || Boolean(unavailableReason) || defaultBranch === requestedRef} aria-describedby={unavailableReason ? `${id}-unavailable` : undefined} onClick={() => void repair(defaultBranch!)}>
+ {pending && <Loader2 aria-hidden className="size-3.5 animate-spin motion-reduce:animate-none" />}{pending ? "Saving & requesting retry…" : `Use ${defaultBranch} & retry`}
+ </Button>
+ </div>
+ )}
+ </>
+ )}
+ <div>
+ <Button type="button" variant="ghost" size="xs" className="text-muted-foreground" aria-expanded={details} aria-controls={`${id}-details`} onClick={() => setDetails(value => !value)}>
+ {details ? "Hide details" : "Why did this happen?"}<ChevronDown aria-hidden className={cn("size-3", details && "rotate-180")} />
+ </Button>
+ {details && <div id={`${id}-details`} className="mt-2 rounded-md border border-border bg-background">
+ <SystemNoticeMetadataSections tone="neutral" sections={[{ rows: [
+ { kind: "text", label: "Setting", value: taskOverride ? "Task-specific starting branch" : "Workspace starting branch" },
+ { kind: "code", label: "Requested branch", value: requestedRef },
+ ...(configuredBy ? [{ kind: "text" as const, label: "Set by", value: configuredBy }] : []),
+ { kind: "text", label: "Why it stopped", value: taskOverride ? "An explicit task branch overrides the repository default. Paperclip does not silently switch branches." : "The configured starting branch must resolve before the agent can start. This repair overrides it for this task." },
+ ] }]} />
+ </div>}
+ </div>
+ </div>
+ </section>
+ );
+}
diff --git a/ui/src/components/task-chat/TaskChatSystemNotice.tsx b/ui/src/components/task-chat/TaskChatSystemNotice.tsx
index 2c1d9fafed..151ee60400 100644
--- a/ui/src/components/task-chat/TaskChatSystemNotice.tsx
+++ b/ui/src/components/task-chat/TaskChatSystemNotice.tsx
@@ -1,3 +1,5 @@
+import { useWorkspaceBaseRefRecovery } from "@/components/WorkspaceBaseRefRecovery";
+import { WorkspaceBaseRefRecoveryNotice } from "@/components/WorkspaceBaseRefRecoveryNotice";
import { DispositionRecoveryNotice, useDispositionRecoverySnapshot } from "@/components/DispositionRecoveryNotice";
import { useId, useState } from "react";
import {
@@ -56,6 +58,7 @@ export function TaskChatSystemNotice({
tryAgainNoLiveExecutionPathPending?: boolean;
}) {
const recoverySnapshot = useDispositionRecoverySnapshot(item.metadata);
+ const branchRecovery = useWorkspaceBaseRefRecovery(item.metadata);
const streamlined = useStreamlinedTaskChatPresentation();
const [open, setOpen] = useState(Boolean(item.presentation?.detailsDefaultOpen));
const detailsId = useId();
@@ -84,6 +87,8 @@ export function TaskChatSystemNotice({
.catch(() => undefined);
};
+ if (item.author === "system" && branchRecovery) return <WorkspaceBaseRefRecoveryNotice key={`${branchRecovery.actionId}:${branchRecovery.runId}`} {...branchRecovery.props} />;
+
if (item.author === "system" && recoverySnapshot) {
return <DispositionRecoveryNotice snapshot={recoverySnapshot} createdAt={item.createdAtIso} defaultExpanded={item.presentation?.detailsDefaultOpen} />;
}
diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsx
index ee00bb2c46..e42768c867 100644
--- a/ui/src/pages/IssueDetail.tsx
+++ b/ui/src/pages/IssueDetail.tsx
@@ -1,3 +1,4 @@
+import { WorkspaceBaseRefRecoveryProvider } from "../components/WorkspaceBaseRefRecovery";
import { isLockedIssueStub, LockedIssueChip } from "@/components/LockedIssueChip";
import { canManageIssuePrivacy } from "../lib/issuePrivacy";
import { TextAttachmentContext } from "../context/TextAttachmentContext";
@@ -7913,6 +7914,12 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
<ExecutionBlockerNotice companyId={issue.companyId} issueId={issue.id} blocker={issue.executionBlocker} onRetried={invalidateIssueDetail} />
)}
{resolvedDetailTab === "chat" ? (
+ <WorkspaceBaseRefRecoveryProvider issue={issue} agentMap={agentMap} onRepaired={() => { invalidateIssueDetail(); invalidateIssueCollections(); }}
+ unavailableReason={!canManageBoardRuntime || !canResolveBoardRecoveryAction ? "You don’t have permission to repair this task’s workspace."
+ : treeControlStateError ? "Couldn’t check whether this task is paused. Refresh to try again."
+ : activePauseHold ? "Resume the task before retrying."
+ : issue.project?.pausedAt ? "Resume the project before retrying."
+ : interactions.some(i => i.status === "pending") ? "Respond to the pending question or confirmation before retrying." : null}>
<DispositionRecoveryProvider value={{
issue,
agentMap,
@@ -8184,6 +8191,7 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
linkCaseReferences={casesChipsEnabled}
/>
</DispositionRecoveryProvider>
+ </WorkspaceBaseRefRecoveryProvider>
) : null}
</TabsContent>
diff --git a/ui/storybook/stories/workspace-branch-recovery/01-component.stories.tsx b/ui/storybook/stories/workspace-branch-recovery/01-component.stories.tsx
new file mode 100644
index 0000000000..8e2fdd6d57
--- /dev/null
+++ b/ui/storybook/stories/workspace-branch-recovery/01-component.stories.tsx
@@ -0,0 +1,22 @@
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { expect, userEvent, within } from "storybook/test";
+import { WorkspaceBaseRefRecoveryNotice } from "@/components/WorkspaceBaseRefRecoveryNotice";
+import { evidence, simulateRepair } from "./fixtures";
+
+const meta = {
+ title: "Workspace branch recovery/01 Repair card",
+ component: WorkspaceBaseRefRecoveryNotice,
+ args: { ...evidence, onRepair: simulateRepair },
+ parameters: { layout: "fullscreen", docs: { description: { component: "Proposed inline repair using the reusable component. Repository data and save/retry responses are simulated here; this story does not change a live task. The default-branch action appears only with a verified repository default." } } },
+ render: (args, context) => <div className="mx-auto max-w-2xl p-4 sm:p-8"><WorkspaceBaseRefRecoveryNotice key={context.id} {...args} /></div>,
+} satisfies Meta<typeof WorkspaceBaseRefRecoveryNotice>;
+export default meta;
+type Story = StoryObj<typeof meta>;
+export const MissingBranch: Story = {};
+export const CustomBranch: Story = { play: async ({ canvasElement }) => { await userEvent.click(within(canvasElement).getByRole("button", { name: "Choose another branch" })); } };
+export const Saving: Story = { args: { onRepair: () => new Promise<void>(() => {}) }, play: async ({ canvasElement }) => { await userEvent.click(within(canvasElement).getByRole("button", { name: "Use master & retry" })); } };
+export const RepairFailed: Story = { args: { onRepair: async () => { throw new Error("Repository access could not be confirmed. Check its GitHub connection, then try again."); } }, play: async ({ canvasElement }) => { await userEvent.click(within(canvasElement).getByRole("button", { name: "Use master & retry" })); } };
+export const RetryRequested: Story = { play: async ({ canvasElement }) => { const c = within(canvasElement); await userEvent.click(c.getByRole("button", { name: "Use master & retry" })); await expect(await c.findByText("Branch updated · retry requested")).toBeVisible(); } };
+export const UnknownDefault: Story = { args: { defaultBranch: null, failureKind: "unresolved_ref", configuredBy: null } };
+export const NoPermission: Story = { args: { unavailableReason: "Only a workspace operator can change this task’s starting branch." } };
+export const Mobile: Story = { globals: { viewport: { value: "mobile", isRotated: false } } };
diff --git a/ui/storybook/stories/workspace-branch-recovery/02-task-journey.stories.tsx b/ui/storybook/stories/workspace-branch-recovery/02-task-journey.stories.tsx
new file mode 100644
index 0000000000..48f827ca78
--- /dev/null
+++ b/ui/storybook/stories/workspace-branch-recovery/02-task-journey.stories.tsx
@@ -0,0 +1,42 @@
+import { useEffect, useState } from "react";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { Route, Routes } from "@/lib/router";
+import { Layout } from "@/components/Layout";
+import { TaskChatBubble } from "@/components/task-chat/TaskChatBubble";
+import { TaskChatComposer } from "@/components/task-chat/TaskChatComposer";
+import { WorkspaceBaseRefRecoveryNotice } from "@/components/WorkspaceBaseRefRecoveryNotice";
+import { StatusBadge } from "@/components/StatusBadge";
+import { PluginLauncherProvider } from "@/plugins/launchers";
+import { useBreadcrumbs } from "@/context/BreadcrumbContext";
+import { evidence, simulateRepair } from "./fixtures";
+
+function TaskConversation() {
+ const [retried, setRetried] = useState(false);
+ const [messages, setMessages] = useState<string[]>([]);
+ const { setBreadcrumbs } = useBreadcrumbs();
+ useEffect(() => { setBreadcrumbs([{ label: "Tasks", href: "/PAP/issues" }, { label: "Rewrite agent policy", identifier: "PAP-24" }]); }, [setBreadcrumbs]);
+ return <div className="mx-auto flex min-h-full w-full max-w-3xl flex-col gap-6 px-4 py-6 sm:px-8">
+ <header className="flex flex-col gap-2">
+ <div className="flex flex-wrap items-center gap-2"><StatusBadge status={retried ? "todo" : "blocked"} /><span className="font-mono text-xs text-muted-foreground">PAP-24</span><span className="text-xs text-muted-foreground">Documentation</span></div>
+ <h1 className="text-xl font-semibold">Let agents install missing dev tools</h1>
+ <p className="text-sm text-muted-foreground">Assigned to Jordan Lee</p>
+ </header>
+ <TaskChatBubble item={{ id: "request", kind: "message", author: "human", text: "Update the agent policy so agents can install missing dev tools in user space and keep working." }} />
+ <TaskChatBubble item={{ id: "delegation", kind: "message", author: "agent", authorName: "Casey Morgan", text: "I’ve assigned the policy update to Jordan in a separate workspace." }} />
+ <WorkspaceBaseRefRecoveryNotice {...evidence} onRepair={async branch => { await simulateRepair(branch); setRetried(true); }} />
+ {messages.map((text, index) => <TaskChatBubble key={index} item={{ id: `message-${index}`, kind: "message", author: "human", text }} />)}
+ <div className="flex-1" />
+ <TaskChatComposer workMode="standard" onAdd={async body => setMessages(current => [...current, body])} placeholder="Message Jordan Lee…" />
+ </div>;
+}
+function Journey() {
+ return <PluginLauncherProvider><Routes><Route path="/:companyPrefix" element={<Layout />}><Route path="issues/:issueId" element={<TaskConversation />} /></Route></Routes></PluginLauncherProvider>;
+}
+const meta = {
+ title: "Workspace branch recovery/02 Task journey", component: Journey,
+ parameters: { layout: "fullscreen", initialEntries: ["/PAP/issues/PAP-24"], docs: { description: { component: "Interactive proposal in the production app shell, using the shared task bubbles, composer and repair component. Save/retry and branch lookup are simulated. Use master or choose release/next; a missing branch shows an inline error. No live task is modified." }, story: { inline: false } } },
+} satisfies Meta<typeof Journey>;
+export default meta;
+type Story = StoryObj<typeof meta>;
+export const FixAndRetry: Story = {};
+export const Mobile: Story = { globals: { viewport: { value: "mobile", isRotated: false } } };
diff --git a/ui/storybook/stories/workspace-branch-recovery/fixtures.ts b/ui/storybook/stories/workspace-branch-recovery/fixtures.ts
new file mode 100644
index 0000000000..162e816651
--- /dev/null
+++ b/ui/storybook/stories/workspace-branch-recovery/fixtures.ts
@@ -0,0 +1,15 @@
+import type { WorkspaceBaseRefRecoveryNoticeProps } from "@/components/WorkspaceBaseRefRecoveryNotice";
+
+export const evidence = {
+ requestedRef: "main",
+ repository: "example/docs-site",
+ defaultBranch: "master",
+ agentName: "Jordan Lee",
+ configuredBy: "Casey Morgan, when creating this task",
+ failureKind: "missing_branch",
+} satisfies Omit<WorkspaceBaseRefRecoveryNoticeProps, "onRepair">;
+
+export async function simulateRepair(branch: string) {
+ await new Promise(resolve => window.setTimeout(resolve, 700));
+ if (branch !== "master" && branch !== "release/next") throw new Error(`Branch “${branch}” was not found. Choose an existing branch.`);
+}