diff --git a/apps/mobile/src/features/threads/PendingUserInputCard.tsx b/apps/mobile/src/features/threads/PendingUserInputCard.tsx
index 12640fdb6e7e8..a486948e18f8b 100644
--- a/apps/mobile/src/features/threads/PendingUserInputCard.tsx
+++ b/apps/mobile/src/features/threads/PendingUserInputCard.tsx
@@ -170,6 +170,16 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
}));
const overlayHeightStyle = useAnimatedStyle(() => ({ height: maxHeight.value }));
+ const stopButton = props.onStopThread ? (
+
+ ) : null;
const bar = (
- {props.onStopThread ? (
-
- ) : null}
+ {stopButton}
);
const card = (
@@ -221,27 +222,32 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
className="overflow-hidden gap-2.5 rounded-[20px] border border-border bg-card-alt p-4"
style={cardAnimatedStyle}
>
-
-
-
- User input needed
-
- Fill in the pending answers
-
-
-
-
-
+
+
+
+
+ User input needed
+
+
+ Fill in the pending answers
+
+
+
+
+
+
+ {stopButton}
+
AcpSessionRuntime.AcpSessionRuntime["Service"]["prompt"];
readonly cancelled?: Deferred.Deferred;
+ readonly followAgentWorkState?: boolean;
}) {
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const natives: Array = [];
@@ -621,6 +622,7 @@ const makePromptInactivityHarness = Effect.fnUntraced(function* (input: {
driver: ACP_TEST_DRIVER,
capabilities: AcpProviderCapabilitiesV2,
promptInactivityTimeout: "15 minutes",
+ ...(input.followAgentWorkState === true ? { followAgentWorkState: true } : {}),
makeRuntime: makeMockRuntime({
childProcessSpawner,
mockAgentPath: yield* bundledMockAgentPath,
@@ -639,6 +641,9 @@ const makePromptInactivityHarness = Effect.fnUntraced(function* (input: {
}),
},
selfInvocation: yield* resolveSelfInvocation(),
+ ...(input.followAgentWorkState === true
+ ? { continuationRequests: { offer: () => Effect.void } }
+ : {}),
});
const threadId = ThreadId.make("thread-acp-prompt-inactivity");
const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
@@ -5191,6 +5196,41 @@ describe("AcpAdapterV2", () => {
}).pipe(Effect.provide(layerTest)),
);
+ it.effect.each([false, true])(
+ "ends a running tool call when its agent process exits mid-prompt (followAgentWorkState: %s)",
+ (followAgentWorkState) =>
+ Effect.gen(function* () {
+ const harness = yield* makePromptInactivityHarness({
+ followAgentWorkState,
+ environment: (runtimeOrdinal) =>
+ runtimeOrdinal === 1 ? { T3_ACP_EMIT_TRACKED_TOOL_CALL_KIND_THEN_HANG: "execute" } : {},
+ });
+ yield* harness.startTurn(1);
+ let exited = false;
+ const statuses = yield* harness.runtime.events.pipe(
+ Stream.takeUntil((event) => event.type === "turn.terminal"),
+ Stream.flatMap((event) =>
+ event.type === "turn_item.updated" &&
+ event.turnItem.nativeItemRef?.nativeId === "tracked-tool-call"
+ ? Stream.make(event.turnItem.status)
+ : Stream.empty,
+ ),
+ // The agent dies while its tool call is open.
+ Stream.tap(() =>
+ exited
+ ? Effect.void
+ : Effect.sync(() => (exited = true)).pipe(
+ Effect.andThen(harness.natives[0]!.notify("_test/exit", {})),
+ ),
+ ),
+ Stream.runCollect,
+ Effect.map((collected) => Array.from(collected)),
+ );
+ // regression: #37368 the dead agent's tool call stayed open in the failed turn.
+ assert.include(["failed", "interrupted", "cancelled"], statuses.at(-1));
+ }).pipe(Effect.provide(layerTest)),
+ );
+
it.live("does not poll the process ledger while a cgroup lease owns teardown", () =>
Effect.gen(function* () {
if ((yield* HostProcess.Platform) !== "linux") return;
diff --git a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts
index 6ff5137556242..214f6cf360e20 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts
@@ -2855,3 +2855,108 @@ it.effect("a running provider-turn update reads only the thread's queued and run
);
}),
);
+
+it.effect(
+ "a delegated child's run end reads the parent's runs no matter how many deliveries it has open",
+ () =>
+ Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
+ const parentThreadId = ThreadId.make("thread:busy-coordinator");
+ const now = yield* DateTime.now;
+ yield* orchestrator.dispatch({
+ type: "thread.create",
+ commandId: CommandId.make("create-busy-coordinator"),
+ threadId: parentThreadId,
+ projectId: ProjectId.make("project:busy-coordinator"),
+ title: "Coordinator",
+ modelSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ createdBy: "user",
+ creationSource: "web",
+ });
+ yield* orchestrator.dispatch({
+ type: "message.dispatch",
+ commandId: CommandId.make("start-busy-coordinator"),
+ threadId: parentThreadId,
+ messageId: MessageId.make("message:busy-coordinator"),
+ text: "Delegate the work",
+ attachments: [],
+ dispatchMode: { type: "start_immediately" },
+ createdBy: "user",
+ creationSource: "web",
+ });
+ const parentRun = (yield* projections.getThreadRecords(parentThreadId, ["runs"])).runs[0]!;
+ yield* orchestrator.dispatch({
+ type: "delegated_task.request",
+ commandId: CommandId.make("delegate-busy-coordinator"),
+ parentThreadId,
+ parentRunId: parentRun.id,
+ parentNodeId: parentRun.rootNodeId!,
+ task: "Do the work",
+ completionWake: "always",
+ modelSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ createdBy: "agent",
+ creationSource: "mcp",
+ });
+ const task = (yield* projections.getThreadRecords(parentThreadId, ["subagents"]))
+ .subagents[0]!;
+ const childThreadId = task.childThreadId!;
+ const childRun = (yield* projections.getThreadRecords(childThreadId, ["runs"])).runs[0]!;
+
+ const runReads: Array = [];
+ const recordRunReads = Effect.provideService(
+ Statement.CurrentTransformer,
+ (statement, _make, _fiber, _span) => {
+ const [query, params] = statement.compile();
+ if (
+ query.includes("FROM orchestration_v2_projection_runs") &&
+ params.includes(parentThreadId)
+ )
+ runReads.push(query);
+ return Effect.succeed(statement);
+ },
+ );
+ const captureReads = Effect.gen(function* () {
+ runReads.length = 0;
+ yield* orchestrator
+ .recoverDelegatedTask(childThreadId, { completedRunId: childRun.id })
+ .pipe(recordRunReads);
+ return runReads.length;
+ });
+ const quietParent = yield* captureReads;
+
+ // Completion wakes queued behind the coordinator's own work, each with a delivery still open.
+ for (let index = 0; index < 40; index++) {
+ const runId = RunId.make(`run:busy-coordinator:wake:${index}`);
+ yield* projections.apply({
+ id: EventId.make(`event:busy-coordinator:wake:${index}`),
+ type: "run.updated",
+ threadId: parentThreadId,
+ runId,
+ occurredAt: now,
+ payload: {
+ ...parentRun,
+ id: runId,
+ ordinal: parentRun.ordinal + index + 1,
+ status: "queued",
+ delegatedCompletion: {
+ disposition: "open",
+ nextGeneration: 2,
+ delivery: {
+ generation: 1,
+ messageId: MessageId.make(`message:busy-coordinator:wake:${index}`),
+ taskIds: [NodeId.make(`task:busy-coordinator:other:${index}`)],
+ },
+ },
+ },
+ });
+ }
+ assert.equal(yield* captureReads, quietParent);
+ }).pipe(Effect.provide(layerTest)),
+);
diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts
index 0160ae21423e4..97940a14d60ea 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.ts
@@ -16075,7 +16075,22 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
return;
yield* threadDispatch.withLock(
parentThreadId,
- offerDelegatedCompletionDeliveries(parentThreadId).pipe(
+ Effect.gen(function* () {
+ // A task's wake lives on the run that requested it; the parent's other wakes are not this child's.
+ const { subagents } = yield* projectionStore.getThreadRecords(
+ parentThreadId,
+ ["subagents"],
+ { subagentChildThreadIds: [threadId] },
+ );
+ const parentRunIds = new Set(
+ subagents.flatMap((task) =>
+ task.childThreadId === threadId && task.runId !== null ? [task.runId] : [],
+ ),
+ );
+ for (const parentRunId of parentRunIds) {
+ yield* offerDelegatedCompletionDelivery(parentThreadId, parentRunId);
+ }
+ }).pipe(
Effect.andThen(
finalizeAppOwnedSubagent(
threadId,
diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts
index d1ff164f16a90..dbbb445a5ec95 100644
--- a/apps/web/src/components/ChatView.logic.test.ts
+++ b/apps/web/src/components/ChatView.logic.test.ts
@@ -1321,6 +1321,7 @@ describe("planComposerTurn", () => {
sendEnvMode: "worktree" as const,
worktreePath: null,
activeThreadBranch: "main",
+ isScratchProject: false,
resumeCompactionTokens: null,
keepFullHistory: false,
phase: "ready" as const,
@@ -1341,6 +1342,12 @@ describe("planComposerTurn", () => {
missingWorktreeBaseBranch: true,
baseBranchForWorktree: null,
});
+ expect(
+ planComposerTurn({ ...base, activeThreadBranch: null, isScratchProject: true }),
+ ).toMatchObject({
+ missingWorktreeBaseBranch: false,
+ baseBranchForWorktree: null,
+ });
});
it("queues behind a compaction of a stale session, except for /compact itself", () => {
diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts
index 057bd52d282fe..e528246e7aea1 100644
--- a/apps/web/src/components/ChatView.logic.ts
+++ b/apps/web/src/components/ChatView.logic.ts
@@ -1343,6 +1343,8 @@ export function planComposerTurn(input: {
readonly sendEnvMode: DraftThreadEnvMode;
readonly worktreePath: string | null;
readonly activeThreadBranch: string | null;
+ /** The server launches a No project worktree request at its root, so it needs no base. */
+ readonly isScratchProject: boolean;
readonly resumeCompactionTokens: number | null;
readonly keepFullHistory: boolean;
readonly phase: SessionPhase;
@@ -1369,7 +1371,8 @@ export function planComposerTurn(input: {
return {
// In worktree mode, require an explicit base branch so we don't silently
// fall back to local execution when branch selection is missing.
- missingWorktreeBaseBranch: shouldCreateWorktree && !input.activeThreadBranch,
+ missingWorktreeBaseBranch:
+ shouldCreateWorktree && !input.activeThreadBranch && !input.isScratchProject,
baseBranchForWorktree: shouldCreateWorktree ? input.activeThreadBranch : null,
compactBeforeSend,
turnDispatchMode:
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index bc4676f8306ea..4676ed343450c 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -2959,6 +2959,7 @@ export default function ChatView(props: ChatViewProps) {
activeThreadKey,
activeThreadBranch,
activeProject,
+ activeProjectIsScratch,
activeProjectDefaultModelSelection,
activeMessageCount,
isServerThread,
diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx
index 1fc292f7ff1ae..1a0fb5bd406f8 100644
--- a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx
+++ b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx
@@ -338,6 +338,32 @@ it("shows a remote subagent's full title in its tooltip even when its environmen
expect(screen.router?.state.location.pathname).toBe("/environment/fork");
});
+it("explains why Merge back is unavailable before the fork completes a run", async () => {
+ setup();
+ state.projection = { ...(state.projection as Record), runs: [] };
+ await using screen = await render(
+ ,
+ { router: "/environment/fork" },
+ );
+
+ const mergeBack = screen.getByRole("button", { name: "Merge back to source conversation" });
+ await userEvent.hover(mergeBack);
+ await vi.waitFor(() =>
+ expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toBe(
+ "Complete a run in this fork before merging it back",
+ ),
+ );
+
+ state.commandSucceeds = true;
+ await mergeBack.click({ force: true });
+ expect(screen.router?.state.location.pathname).toBe("/environment/fork");
+});
+
it("shows a delegated-from thread's full title in its tooltip even when its environment is unavailable", async () => {
setup();
const longTitle = "Parent task delegated from another machine that has a long description";
diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx
index 0dd481edf776e..16882da3f2a17 100644
--- a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx
+++ b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx
@@ -923,7 +923,7 @@ export function ThreadRelationshipsPanel(props: {
? `Merge back to ${parentTitle}`
: "Merge back to source conversation"
}
- disabled={!canMerge || busyAction !== null}
+ aria-disabled={!canMerge || busyAction !== null || undefined}
onClick={() => void merge()}
>
{busyAction === "merge" ? (
diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts
index da3e2eaf20f8f..72e6f3bf792c0 100644
--- a/apps/web/src/components/chat/useComposerSend.ts
+++ b/apps/web/src/components/chat/useComposerSend.ts
@@ -176,6 +176,7 @@ interface ComposerSendInput {
readonly activeThreadKey: string | null;
readonly activeThreadBranch: string | null;
readonly activeProject: EnvironmentProject | null;
+ readonly activeProjectIsScratch: boolean;
readonly activeProjectDefaultModelSelection: ModelSelection | null;
readonly activeMessageCount: number;
readonly isServerThread: boolean;
@@ -276,6 +277,7 @@ export function useComposerSend(input: ComposerSendInput) {
activeThreadKey,
activeThreadBranch,
activeProject,
+ activeProjectIsScratch,
activeProjectDefaultModelSelection,
activeMessageCount,
isServerThread,
@@ -814,6 +816,7 @@ export function useComposerSend(input: ComposerSendInput) {
sendEnvMode,
worktreePath: activeThread.worktreePath,
activeThreadBranch,
+ isScratchProject: activeProjectIsScratch,
resumeCompactionTokens,
keepFullHistory,
phase,
diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts
index d642cfe200cbd..01bfafd68b11d 100644
--- a/packages/provider-acp/src/server/adapter.ts
+++ b/packages/provider-acp/src/server/adapter.ts
@@ -2550,12 +2550,16 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
yield* Ref.set(continuationRequested, false);
yield* cancelPendingRuntimeRequests();
const context = yield* Ref.get(activeTurn);
- if (context !== null)
+ if (context !== null) {
+ if (!context.finalized && !context.interrupted) {
+ yield* terminalizeOpenForegroundTools(context, "failed");
+ }
yield* finalizeTurn(
context,
"failed",
makeProviderFailure({ class: "transport_error" }),
);
+ }
}),
).pipe(Effect.asVoid);
const makeRuntimeInput = (
@@ -8973,6 +8977,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
if (!interrupted && flavor.restartRuntimeAfterPromptError?.(failure) === true) {
yield* Ref.set(runtimeRestartRequired, true);
}
+ // An agent that answered with an error is still alive and may finish its
+ // tools; any other failure means its process or pipe is gone.
+ const agentAnswered =
+ Result.isSuccess(error) && error.success._tag === "AcpRequestError";
+ if (!interrupted && !agentAnswered) {
+ yield* terminalizeOpenForegroundTools(context, "failed");
+ }
yield* finalizeTurn(
context,
interrupted ? "interrupted" : "failed",