@@ -3213,119 +3213,128 @@ describe("ClaudeAdapterV2 background wake turns", () => {
32133213 ),
32143214 );
32153215
3216- // Moves are forked, so a test proves one was not asked for by draining the
3217- // requests up to a later control move instead of polling an empty queue.
3218- const makeSteerBackgroundHarness = (options: {
3219- readonly attempt: string;
3220- readonly registered?: (toolUseId: string) => boolean;
3221- readonly offer?: (
3222- message: SDKUserMessage,
3223- ) => Effect.Effect<void, ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError>;
3224- }) =>
3225- Effect.gen(function* () {
3226- const moves: Array<{ readonly toolUseId: string; readonly offeredBefore: number }> = [];
3227- const moved = yield* Queue.unbounded<string>();
3228- let offered: ReadonlyArray<SDKUserMessage> = [];
3229- const harness = yield* makeWakeHarnessWithOptions({
3230- backgroundTasks: (toolUseId) =>
3231- Effect.sync(() => moves.push({ toolUseId, offeredBefore: offered.length })).pipe(
3232- Effect.andThen(Queue.offer(moved, toolUseId)),
3233- Effect.as(options.registered?.(toolUseId) ?? false),
3234- ),
3235- ...(options.offer === undefined ? {} : { offer: options.offer }),
3236- });
3237- offered = harness.offeredMessages;
3238- const idAllocator = yield* IdAllocator.IdAllocatorV2;
3239- const attemptId = RunAttemptId.make(options.attempt);
3240- const input = makeClaudeTestTurnInput({
3241- threadId: harness.threadId,
3242- providerThread: harness.providerThread,
3243- now: yield* DateTime.now,
3244- attemptId,
3245- text: "Run the slow suite.",
3246- attachments: [],
3247- });
3248- yield* harness.runtime.startTurn(input);
3249- let frame = 0;
3250- const uuid = () =>
3251- `00000000-0000-4000-8000-${(0x900 + frame++).toString(16).padStart(12, "0")}`;
3252- const toolUse = (id: string) =>
3253- claudeSdkFrame({
3254- type: "assistant",
3255- uuid: uuid(),
3256- session_id: WAKE_NATIVE_SESSION,
3257- parent_tool_use_id: null,
3258- message: {
3259- id: `message-${id}`,
3260- model: "claude-sonnet-5-5",
3261- content: [{ type: "tool_use", id, name: "Bash", input: { command: "vp test" } }],
3262- },
3263- });
3264- const taskStarted = (toolUseId: string) =>
3265- claudeSdkFrame({
3266- type: "system",
3267- subtype: "task_started",
3268- task_id: `task-${toolUseId}`,
3269- tool_use_id: toolUseId,
3270- description: "Run the suite",
3271- is_backgrounded: false,
3272- task_type: "local_bash",
3273- uuid: uuid(),
3274- session_id: WAKE_NATIVE_SESSION,
3275- });
3276- const steer = (text: string) =>
3277- harness.runtime.steerTurn({
3278- threadId: harness.threadId,
3279- runId: input.runId,
3280- providerThread: harness.providerThread,
3281- providerTurnId: idAllocator.derive.providerTurn({
3282- driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
3283- nativeTurnId: `turn:${attemptId}`,
3284- }),
3285- message: {
3286- createdBy: "user",
3287- creationSource: "web",
3288- messageId: MessageId.make(`message-${options.attempt}-${frame++}`),
3289- text,
3290- attachments: [],
3291- },
3292- });
3293- const movesUntil = Effect.fnUntraced(function* (control: string) {
3294- const taken: Array<string> = [];
3295- while (taken.at(-1) !== control) taken.push(yield* Queue.take(moved));
3296- return taken;
3297- });
3298- return { harness, moves, toolUse, taskStarted, steer, movesUntil, uuid };
3299- });
3300-
3301- it.effect.each([true, false])(
3302- "a steer moves running root commands to the background, registered at steer %s",
3303- (registered) =>
3216+ it.effect.each([false, true])(
3217+ "steer backgrounds only eligible root commands across overlapping offers (older abort: %s)",
3218+ (olderAbort) =>
33043219 Effect.scoped(
33053220 Effect.gen(function* () {
3306- // The CLI registers a foreground command's task about three seconds
3307- // in; before that, backgroundTasks matches nothing.
3308- const registeredTasks = new Set<string>(registered ? ["toolu-running"] : []);
3309- const { harness, moves, toolUse, taskStarted, steer, movesUntil, uuid } =
3310- yield* makeSteerBackgroundHarness({
3311- attempt: "attempt-steer-background",
3312- registered: (toolUseId) => registeredTasks.has(toolUseId),
3221+ const moved = yield* Queue.unbounded<string>();
3222+ const moves: Array<{ id: string; offered: number; registered: boolean }> = [];
3223+ const registered = new Set(["registered"]);
3224+ const stopped: Array<string> = [];
3225+ let interrupts = 0;
3226+ let rejectOffer = false;
3227+ const harness = yield* makeWakeHarnessWithOptions({
3228+ backgroundTasks: (id) =>
3229+ Effect.gen(function* () {
3230+ moves.push({
3231+ id,
3232+ offered: harness.offeredMessages.length,
3233+ registered: registered.has(id),
3234+ });
3235+ yield* Queue.offer(moved, id);
3236+ if (id === "unsupported") {
3237+ return yield* new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({
3238+ method: "backgroundTasks",
3239+ cause: new Error("Backgrounding unavailable."),
3240+ });
3241+ }
3242+ return registered.has(id);
3243+ }),
3244+ offer: () =>
3245+ rejectOffer
3246+ ? Effect.fail(
3247+ new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({
3248+ method: "offer",
3249+ cause: new Error("Input rejected."),
3250+ }),
3251+ )
3252+ : Effect.void,
3253+ stopTask: (id) =>
3254+ Effect.sync(() => {
3255+ stopped.push(id);
3256+ }),
3257+ interrupt: Effect.sync(() => {
3258+ interrupts++;
3259+ }),
3260+ });
3261+ const idAllocator = yield* IdAllocator.IdAllocatorV2;
3262+ const attemptId = RunAttemptId.make("steer-command-cohorts");
3263+ const input = makeClaudeTestTurnInput({
3264+ threadId: harness.threadId,
3265+ providerThread: harness.providerThread,
3266+ now: yield* DateTime.now,
3267+ attemptId,
3268+ text: "Run the slow suites.",
3269+ attachments: [],
3270+ });
3271+ yield* harness.runtime.startTurn(input);
3272+ let sequence = 0;
3273+ const uuid = () =>
3274+ `00000000-0000-4000-8000-${(++sequence).toString(16).padStart(12, "0")}`;
3275+ const command = (id: string) =>
3276+ harness.offerAndWait(
3277+ claudeSdkFrame({
3278+ type: "assistant",
3279+ uuid: uuid(),
3280+ session_id: WAKE_NATIVE_SESSION,
3281+ parent_tool_use_id: null,
3282+ message: {
3283+ id: `message-${id}`,
3284+ model: "claude-sonnet-5-5",
3285+ content: [{ type: "tool_use", id, name: "Bash", input: { command: "vp test" } }],
3286+ },
3287+ }),
3288+ );
3289+ const taskStarted = (id: string) =>
3290+ harness.offerAndWait(
3291+ claudeSdkFrame({
3292+ type: "system",
3293+ subtype: "task_started",
3294+ task_id: `task-${id}`,
3295+ tool_use_id: id,
3296+ description: "Run the suite",
3297+ is_backgrounded: false,
3298+ task_type: "local_bash",
3299+ uuid: uuid(),
3300+ session_id: WAKE_NATIVE_SESSION,
3301+ }),
3302+ );
3303+ const steer = (text: string) =>
3304+ harness.runtime.steerTurn({
3305+ threadId: harness.threadId,
3306+ runId: input.runId,
3307+ providerThread: harness.providerThread,
3308+ providerTurnId: idAllocator.derive.providerTurn({
3309+ driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
3310+ nativeTurnId: `turn:${attemptId}`,
3311+ }),
3312+ message: {
3313+ createdBy: "user",
3314+ creationSource: "web",
3315+ messageId: MessageId.make(`steer-${sequence++}`),
3316+ text,
3317+ attachments: [],
3318+ },
33133319 });
3314- yield* harness.offerAndWait(toolUse("toolu-running"));
3315-
3320+ // Background requests are forked; a later control request drains earlier
3321+ // requests without sleeps or assertions against an unobserved empty queue.
3322+ const through = Effect.fnUntraced(function* (id: string) {
3323+ for (;;) {
3324+ if ((yield* Queue.take(moved)) === id) return;
3325+ }
3326+ });
3327+ yield* command("registered");
3328+ yield* taskStarted("registered");
3329+ yield* command("late");
33163330 yield* steer("Skip the e2e tests.");
3331+ yield* through("late");
33173332 assert.equal(harness.offeredMessages[1]?.priority, "now");
3318- assert.deepEqual(yield* movesUntil("toolu-running"), ["toolu-running"]);
3319- if (!registered) {
3320- registeredTasks.add("toolu-running");
3321- yield* harness.offerAndWait(taskStarted("toolu-running"));
3322- assert.deepEqual(yield* movesUntil("toolu-running"), ["toolu-running"]);
3323- }
3324- // Offered first, so the steer is queued when the tool call returns.
3325- assert.isTrue(moves.every((move) => move.offeredBefore === 2));
3326-
3327- yield* Queue.offer(
3328- harness.sdkMessages,
3333+ assert.deepEqual(moves, [
3334+ { id: "registered", offered: 2, registered: true },
3335+ { id: "late", offered: 2, registered: false },
3336+ ]);
3337+ yield* harness.offerAndWait(
33293338 claudeSdkFrame({
33303339 type: "user",
33313340 uuid: uuid(),
@@ -3336,36 +3345,52 @@ describe("ClaudeAdapterV2 background wake turns", () => {
33363345 content: [
33373346 {
33383347 type: "tool_result",
3339- tool_use_id: "toolu-running",
3340- content:
3341- "Command was manually backgrounded by user with ID: task-toolu-running.",
3348+ tool_use_id: "registered",
3349+ content: "Command was manually backgrounded by user with ID: task-registered.",
33423350 },
33433351 ],
33443352 },
33453353 }),
33463354 );
3347- yield* Queue.offer(
3348- harness.sdkMessages,
3349- makeResultFrame({ uuid: uuid(), result: "", terminalReason: "aborted_tools" }),
3350- );
3351- // Claude has read the steer: its own later commands keep running.
3352- yield* harness.offerAndWait(toolUse("toolu-later"));
3353- yield* harness.offerAndWait(taskStarted("toolu-later"));
3354- // A second steer moves toolu-later once, and toolu-control after it.
3355- yield* harness.offerAndWait(toolUse("toolu-control"));
3355+ yield* command("unsupported");
33563356 yield* steer("Also skip lint.");
3357- const taken = yield* movesUntil("toolu-control");
3358- assert.lengthOf(
3359- taken.filter((id) => id === "toolu-later"),
3360- 1,
3357+ yield* through("unsupported");
3358+ yield* command("new");
3359+ rejectOffer = true;
3360+ assert.isTrue(Exit.isFailure(yield* steer("Undeliverable steer").pipe(Effect.exit)));
3361+ rejectOffer = false;
3362+ registered.add("new");
3363+ yield* taskStarted("new");
3364+ if (olderAbort) {
3365+ yield* harness.offerAndWait(
3366+ makeResultFrame({
3367+ uuid: uuid(),
3368+ result: "",
3369+ terminalReason: "aborted_tools",
3370+ }),
3371+ );
3372+ }
3373+ registered.add("late");
3374+ yield* taskStarted("late");
3375+ yield* command("control");
3376+ yield* steer("Now stop waiting for the new suite, too.");
3377+ yield* through("control");
3378+ assert.isTrue(
3379+ moves.some((move) => move.id === "late" && move.registered && move.offered === 4),
3380+ "late registration retains eligibility from successful steers, even after an older abort",
33613381 );
3362-
3382+ assert.deepEqual(
3383+ moves.filter((move) => move.id === "new"),
3384+ [{ id: "new", offered: 5, registered: true }],
3385+ "a later command waits for its own successful steer, even if another offer fails",
3386+ );
3387+ assert.deepEqual(stopped, []);
3388+ assert.equal(interrupts, 0);
33633389 yield* Queue.offer(
33643390 harness.sdkMessages,
3365- makeResultFrame({ uuid: uuid(), result: "Skipped the e2e tests ." }),
3391+ makeResultFrame({ uuid: uuid(), result: "Done ." }),
33663392 );
3367- const terminal = yield* Queue.take(harness.terminalReceipts);
3368- assert.equal(terminal.status, "completed");
3393+ assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "completed");
33693394 assert.lengthOf(harness.terminalEvents(), 1);
33703395 }).pipe(
33713396 Effect.provide(
@@ -3375,82 +3400,6 @@ describe("ClaudeAdapterV2 background wake turns", () => {
33753400 ),
33763401 );
33773402
3378- it.effect("a command Claude starts while the steer is still being offered stays put", () =>
3379- Effect.scoped(
3380- Effect.gen(function* () {
3381- // Steering while Claude streams aborts the stream at once, so the
3382- // steer's abort result and Claude's next command can reach the adapter
3383- // before the offer returns.
3384- let duringOffer: Effect.Effect<void> = Effect.void;
3385- const { harness, toolUse, taskStarted, steer, movesUntil, uuid } =
3386- yield* makeSteerBackgroundHarness({
3387- attempt: "attempt-steer-during-offer",
3388- offer: (message) => (message.priority === "now" ? duringOffer : Effect.void),
3389- });
3390- duringOffer = Effect.suspend(() => {
3391- duringOffer = Effect.void;
3392- return Queue.offerAll(harness.sdkMessages, [
3393- makeResultFrame({ uuid: uuid(), result: "", terminalReason: "aborted_streaming" }),
3394- toolUse("toolu-after-steer"),
3395- taskStarted("toolu-after-steer"),
3396- ]).pipe(Effect.asVoid);
3397- });
3398- yield* steer("Skip the e2e tests.");
3399-
3400- yield* harness.offerAndWait(toolUse("toolu-control"));
3401- yield* steer("Also skip lint.");
3402- const taken = yield* movesUntil("toolu-control");
3403- assert.lengthOf(
3404- taken.filter((id) => id === "toolu-after-steer"),
3405- 1,
3406- );
3407- }).pipe(
3408- Effect.provide(
3409- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
3410- ),
3411- ),
3412- ),
3413- );
3414-
3415- it.effect("a steer Claude never received leaves later commands in the foreground", () =>
3416- Effect.scoped(
3417- Effect.gen(function* () {
3418- let delivered = false;
3419- const { harness, toolUse, taskStarted, steer, movesUntil } =
3420- yield* makeSteerBackgroundHarness({
3421- attempt: "attempt-steer-undelivered",
3422- offer: (message) =>
3423- message.priority === "now" && !delivered
3424- ? Effect.fail(
3425- new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({
3426- method: "offer",
3427- cause: new Error("The CLI closed its input."),
3428- }),
3429- )
3430- : Effect.void,
3431- });
3432- yield* harness.offerAndWait(toolUse("toolu-undelivered"));
3433-
3434- assert.isTrue(Exit.isFailure(yield* steer("Skip the e2e tests.").pipe(Effect.exit)));
3435- yield* harness.offerAndWait(taskStarted("toolu-undelivered"));
3436-
3437- // A delivered steer moves toolu-undelivered once, and toolu-control after it.
3438- delivered = true;
3439- yield* harness.offerAndWait(toolUse("toolu-control"));
3440- yield* steer("Skip the e2e tests.");
3441- const taken = yield* movesUntil("toolu-control");
3442- assert.lengthOf(
3443- taken.filter((id) => id === "toolu-undelivered"),
3444- 1,
3445- );
3446- }).pipe(
3447- Effect.provide(
3448- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
3449- ),
3450- ),
3451- ),
3452- );
3453-
34543403 it.effect("announces usage-limit pauses once per window and again on a new turn", () =>
34553404 Effect.gen(function* () {
34563405 const harness = yield* makeWakeHarness;
0 commit comments