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
129 changes: 124 additions & 5 deletions apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5246,13 +5246,18 @@ describe("ClaudeAdapterV2 background wake turns", () => {
);

it.effect.each([
{ runtimeMode: "auto", modelHasAuto: true, changes: ["auto", "plan"] },
{ runtimeMode: "full-access", modelHasAuto: true, changes: ["bypassPermissions", "plan"] },
// Like the CLI at launch, a model without Auto runs in default.
{ runtimeMode: "auto", modelHasAuto: false, changes: ["auto", "default", "plan"] },
{ runtimeMode: "auto", modelHasAuto: true, changes: ["auto", "plan"], asks: false },
{
runtimeMode: "full-access",
modelHasAuto: true,
changes: ["bypassPermissions", "plan"],
asks: true,
},
// Like the CLI at launch, a model without Auto runs in default, which asks.
{ runtimeMode: "auto", modelHasAuto: false, changes: ["auto", "default", "plan"], asks: true },
] as const)(
"switches $runtimeMode Plan in and out on a process running a background shell (Auto: $modelHasAuto)",
({ runtimeMode, modelHasAuto, changes }) =>
({ runtimeMode, modelHasAuto, changes, asks }) =>
Effect.scoped(
Effect.gen(function* () {
const harness = yield* makeWakeHarnessWithOptions({
Expand Down Expand Up @@ -5291,11 +5296,41 @@ describe("ClaudeAdapterV2 background wake turns", () => {
yield* harness.runtime.startTurn(turn(1, "plan"));
const originalOptions = harness.getOpenedOptions();
assert.equal(originalOptions?.permissionMode, "plan");
// Leaving Plan for Full access needs the bypass allowance from launch.
assert.equal(
originalOptions?.allowDangerouslySkipPermissions,
runtimeMode === "full-access" ? true : undefined,
);
yield* harness.offerAndWait(wakeTaskStarted);
yield* settle;
assert.isTrue(yield* harness.hasPendingBackgroundWork);

yield* harness.runtime.startTurn(turn(2, "default"));
const decision = yield* Effect.promise(() =>
originalOptions!.canUseTool!(
"Bash",
{ command: "git status" },
{
signal: new AbortController().signal,
toolUseID: "tool-after-plan",
requestId: "request-after-plan",
},
),
).pipe(Effect.forkScoped);
const first = yield* Effect.raceFirst(
Queue.take(harness.runtimeRequestReceipts).pipe(
Effect.map((event) => ({ type: "request", event }) as const),
),
Fiber.join(decision).pipe(Effect.map(() => ({ type: "decision" }) as const)),
);
assert.equal(first.type, asks ? "request" : "decision");
if (first.type === "request") {
yield* harness.runtime.respondToRuntimeRequest({
requestId: first.event.runtimeRequest.id,
decision: "decline",
});
yield* Fiber.join(decision);
}
yield* settle;
yield* harness.runtime.startTurn(turn(3, "plan"));
yield* settle;
Expand All @@ -5317,6 +5352,90 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);

it.effect("asks for approvals after restoring Claude's own Plan falls back to default", () =>
Effect.scoped(
Effect.gen(function* () {
const harness = yield* makeWakeHarnessWithOptions({
setPermissionMode: (mode) =>
mode === "auto"
? Effect.fail(
new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({
method: "setPermissionMode",
cause: new Error("auto mode is not available for this model"),
}),
)
: Effect.void,
});
const now = yield* DateTime.now;
const turn = (ordinal: number) =>
makeClaudeTestTurnInput({
threadId: harness.threadId,
providerThread: harness.providerThread,
now,
attemptId: RunAttemptId.make(`attempt-restore-plan:${ordinal}`),
text: `Request ${ordinal}`,
attachments: [],
providerTurnOrdinal: ordinal,
runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
runtimeMode: "auto",
interactionMode: "default",
cwd: "/workspace",
}),
});
yield* harness.runtime.startTurn(turn(1));
// Claude enters Plan on its own, and the model no longer offers Auto to return to.
yield* harness.offerAndWait(
claudeSdkFrame({
type: "system",
subtype: "status",
status: null,
permissionMode: "plan",
uuid: "restore-enter-plan",
session_id: WAKE_NATIVE_SESSION,
}),
);
yield* harness.offerAndWait(turnOneResult);
yield* Queue.take(harness.terminalReceipts);

yield* harness.runtime.startTurn(turn(2));
assert.deepEqual(harness.permissionModeChanges, ["auto", "default"]);
const decision = yield* Effect.promise(() =>
harness.getOpenedOptions()!.canUseTool!(
"Bash",
{ command: "git status" },
{
signal: new AbortController().signal,
toolUseID: "tool-after-restore",
requestId: "request-after-restore",
},
),
).pipe(Effect.forkScoped);
const first = yield* Effect.raceFirst(
Queue.take(harness.runtimeRequestReceipts).pipe(
Effect.map((event) => ({ type: "request", event }) as const),
),
Fiber.join(decision).pipe(Effect.map(() => ({ type: "decision" }) as const)),
);
assert.equal(first.type, "request");
if (first.type !== "request") return;
yield* harness.runtime.respondToRuntimeRequest({
requestId: first.event.runtimeRequest.id,
decision: "decline",
});
yield* Fiber.join(decision);
}).pipe(
Effect.provide(
Layer.mergeAll(
IdAllocator.layer,
McpProviderSessions.layer,
NodeServices.layer,
NodeCrypto.layer,
),
),
),
),
);

it.effect("re-sends the model on the turn after a live selection change fails", () =>
Effect.scoped(
Effect.gen(function* () {
Expand Down
15 changes: 14 additions & 1 deletion apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1466,6 +1466,18 @@ function setClaudeLivePermissionMode(live: ClaudeLiveQueryContext, mode: Permiss
);
}

// Turns follow the mode Claude accepted. A fallback to default forwards its approvals, so the
// callback must ask for them even when the requested mode would not.
function claudeEffectiveLiveQueryPolicy(live: ClaudeLiveQueryContext): ClaudeRuntimeQueryPolicy {
return live.openedPermissionMode === live.queryPolicy.permissionMode
? live.queryPolicy
: {
...live.queryPolicy,
permissionMode: live.openedPermissionMode,
installPermissionCallback: true,
};
}

// A delegated child is its own SDK session, so Claude Code gives it the main-conversation cache
// TTL. When the user sets Claude's subagentPromptCacheTtl, the child follows it like a native
// subagent would. An explicit CLAUDE_CODE_PROMPT_CACHE_TTL on the instance still wins.
Expand Down Expand Up @@ -10474,6 +10486,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
existing,
existing.openedPermissionMode,
);
existing.openedPermissionMode = existing.permissionMode;
}
return existing;
}
Expand Down Expand Up @@ -10785,7 +10798,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
const querySession = yield* openQuery(turnInput, nativeThreadId);
const context: ActiveClaudeTurnContext = {
input: turnInput,
queryPolicy: querySession.queryPolicy,
queryPolicy: claudeEffectiveLiveQueryPolicy(querySession),
nativeThreadId,
nativeTurnId,
nativeMessageCursor: null,
Expand Down
64 changes: 64 additions & 0 deletions apps/web/src/components/ChatView.logic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
snapshotComposerSend,
withMessageContext,
deriveAvailableRevertTurnCounts,
hasPendingProviderBackgroundWork,
} from "./ChatView.logic";
import { recallCheckoutIsRepo, rememberCheckoutIsRepo } from "./ChatView.logic";
import { ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
Expand Down Expand Up @@ -1258,3 +1259,66 @@ describe("deriveAvailableRevertTurnCounts", () => {
expect(deriveAvailableRevertTurnCounts(null).size).toBe(0);
});
});

describe("hasPendingProviderBackgroundWork", () => {
const providerThreadId = ProviderThreadId.make("provider-thread");

function projection(input: {
readonly laterRun?: "queued" | "rolled_back";
readonly agent?: boolean;
readonly command?: boolean;
readonly pullRequestWatch?: boolean;
}) {
const base = makeThreadProjectionFixture();
const run = (ordinal: number, status: string) => ({
id: RunId.make(`run-${ordinal}`),
ordinal,
status,
startedAt: status === "queued" ? null : "2026-10-30T14:20:00.000Z",
});
return {
...base,
thread: {
...base.thread,
activeProviderThreadId: providerThreadId,
pullRequests:
input.pullRequestWatch === true
? [{ host: "github.com", repository: "o/r", number: 1, watch: {} }]
: [],
},
providerThreads: [
{
id: providerThreadId,
providerInstanceId: base.thread.modelSelection.instanceId,
pendingBackgroundTasks:
input.command === true ? [{ taskId: "gate", kind: "command" }] : [],
},
],
runs: [
run(1, "completed"),
...(input.laterRun === undefined ? [] : [run(2, input.laterRun)]),
],
turnItems:
input.agent === true
? [{ id: "item-agent", type: "subagent", status: "running", runId: RunId.make("run-1") }]
: [],
} as unknown as ReturnType<typeof makeThreadProjectionFixture>;
}

it.each([
{ name: "a running background agent", input: { agent: true }, expected: true },
{
name: "a background agent behind a queued message",
input: { agent: true, laterRun: "queued" },
expected: true,
},
{
name: "a listed command after a rollback",
input: { command: true, laterRun: "rolled_back" },
expected: false,
},
{ name: "only a watched pull request", input: { pullRequestWatch: true }, expected: false },
] as const)("$name: $expected", ({ input, expected }) => {
expect(hasPendingProviderBackgroundWork(projection(input))).toBe(expected);
});
});
34 changes: 26 additions & 8 deletions apps/web/src/components/ChatView.logic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1555,11 +1555,8 @@ export function presentThreadShellFromProjection(
};
}

/** Background work the provider still runs after the latest run ended, plus watched pull requests. */
export function deriveThreadPendingBackgroundTasks(
projection: ThreadStructure | null,
options?: { readonly includePullRequestWatches?: boolean },
) {
/** Background work the provider still runs after the latest run ended. */
export function deriveThreadPendingBackgroundTasks(projection: ThreadStructure | null) {
if (projection === null) return [];
const sessionError =
projection.providerSessions.findLast(
Expand All @@ -1575,13 +1572,34 @@ export function deriveThreadPendingBackgroundTasks(
turnItems: projection.turnItems,
activeProviderThreadId: projection.thread.activeProviderThreadId,
runs: projection.runs,
...(options?.includePullRequestWatches === false
? {}
: { pullRequests: projection.thread.pullRequests }),
pullRequests: projection.thread.pullRequests,
}),
];
}

/**
* Whether the provider still runs background agents or commands for the thread's latest run.
* Pull request watches do not count, and a queued run has not taken over the session yet.
*/
export function hasPendingProviderBackgroundWork(
projection: Pick<ThreadStructure, "thread" | "providerThreads" | "runs" | "turnItems">,
): boolean {
const latestRun = projection.runs.reduce<ThreadStructure["runs"][number] | null>(
(latest, run) =>
run.status === "queued" || (latest !== null && latest.ordinal > run.ordinal) ? latest : run,
null,
);
return (
derivePendingBackgroundWork({
latestRun,
providerThreads: projection.providerThreads,
turnItems: projection.turnItems,
activeProviderThreadId: projection.thread.activeProviderThreadId,
runs: projection.runs,
}).length > 0
);
}

/**
* Run ordinals the conversation can be reverted to: those whose provider turn belongs to the
* active provider thread, plus 0 for the thread start. Empty without a live provider session
Expand Down
4 changes: 2 additions & 2 deletions apps/web/src/components/ChatView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { announcedRun, isDetailBehindShell } from "./chat/threadActivityAnnounce
import {
deriveAvailableRevertTurnCounts,
deriveThreadPendingBackgroundTasks,
hasPendingProviderBackgroundWork,
presentThreadShellFromProjection,
} from "./ChatView.logic";
import { usePullRequestDraftThread } from "./chat/usePullRequestDraftThread";
Expand Down Expand Up @@ -2494,8 +2495,7 @@ export default function ChatView(props: ChatViewProps) {
!hasHeldQueuedRuns &&
multipleModelSelections === null &&
// Background agents keep the session live and report into its next turn.
deriveThreadPendingBackgroundTasks(serverProjection, { includePullRequestWatches: false })
.length === 0 &&
(serverProjection === null || !hasPendingProviderBackgroundWork(serverProjection)) &&
shouldOfferResumeCompaction({
provider: selectedProvider,
usedTokens: activeContextWindow.usedTokens,
Expand Down
Loading