Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 37 additions & 31 deletions apps/mobile/src/features/threads/PendingUserInputCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,16 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
}));
const overlayHeightStyle = useAnimatedStyle(() => ({ height: maxHeight.value }));

const stopButton = props.onStopThread ? (
<ControlPill
accessibilityLabel="Stop"
icon="stop.fill"
variant="danger"
className="h-9 w-9"
disabled={!props.canOperateThread}
onPress={props.onStopThread}
/>
) : null;
const bar = (
<View
onLayout={handleBarLayout}
Expand Down Expand Up @@ -200,16 +210,7 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
type="monochrome"
/>
</Pressable>
{props.onStopThread ? (
<ControlPill
accessibilityLabel="Stop"
icon="stop.fill"
variant="danger"
className="h-9 w-9"
disabled={!props.canOperateThread}
onPress={props.onStopThread}
/>
) : null}
{stopButton}
</View>
);
const card = (
Expand All @@ -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}
>
<Pressable
accessibilityRole="button"
accessibilityLabel="Collapse user input"
onPress={props.onToggleCollapsed}
className="flex-row items-start gap-2"
>
<View className="flex-1 gap-2.5">
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-foreground-secondary">
User input needed
</Text>
<Text className="font-t3-bold text-lg text-foreground">Fill in the pending answers</Text>
</View>
<View className="h-8 w-8 items-center justify-center rounded-full bg-subtle-strong">
<SymbolView
name="chevron.down"
size={13}
tintColorClassName={"accent-icon-subtle"}
type="monochrome"
/>
</View>
</Pressable>
<View className="flex-row items-start gap-2">
<Pressable
accessibilityRole="button"
accessibilityLabel="Collapse user input"
onPress={props.onToggleCollapsed}
className="flex-1 flex-row items-start gap-2"
>
<View className="flex-1 gap-2.5">
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-foreground-secondary">
User input needed
</Text>
<Text className="font-t3-bold text-lg text-foreground">
Fill in the pending answers
</Text>
</View>
<View className="h-8 w-8 items-center justify-center rounded-full bg-subtle-strong">
<SymbolView
name="chevron.down"
size={13}
tintColorClassName={"accent-icon-subtle"}
type="monochrome"
/>
</View>
</Pressable>
{stopButton}
</View>
<ScrollView
bounces={false}
className="min-h-0"
Expand Down
40 changes: 40 additions & 0 deletions apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -611,6 +611,7 @@ const makePromptInactivityHarness = Effect.fnUntraced(function* (input: {
prompt: AcpSessionRuntime.AcpSessionRuntime["Service"]["prompt"],
) => AcpSessionRuntime.AcpSessionRuntime["Service"]["prompt"];
readonly cancelled?: Deferred.Deferred<void>;
readonly followAgentWorkState?: boolean;
}) {
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const natives: Array<AcpSessionRuntime.AcpSessionRuntime["Service"]> = [];
Expand All @@ -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,
Expand All @@ -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({
Expand Down Expand Up @@ -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;
Expand Down
105 changes: 105 additions & 0 deletions apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string> = [];
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)),
);
17 changes: 16 additions & 1 deletion apps/server/src/orchestration-v2/Orchestrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
7 changes: 7 additions & 0 deletions apps/web/src/components/ChatView.logic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1321,6 +1321,7 @@ describe("planComposerTurn", () => {
sendEnvMode: "worktree" as const,
worktreePath: null,
activeThreadBranch: "main",
isScratchProject: false,
resumeCompactionTokens: null,
keepFullHistory: false,
phase: "ready" as const,
Expand All @@ -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", () => {
Expand Down
5 changes: 4 additions & 1 deletion apps/web/src/components/ChatView.logic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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:
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/components/ChatView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2959,6 +2959,7 @@ export default function ChatView(props: ChatViewProps) {
activeThreadKey,
activeThreadBranch,
activeProject,
activeProjectIsScratch,
activeProjectDefaultModelSelection,
activeMessageCount,
isServerThread,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>), runs: [] };
await using screen = await render(
<ThreadRelationshipsPanel
environmentId={environmentId}
threadId={threadId}
showLineage
showSideChats={false}
/>,
{ 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";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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" ? (
Expand Down
Loading
Loading