Skip to content

Commit 470c9b9

Browse files
committed
feat(antigravity): queue follow-up turns sequentially instead of cancelling active prompt
1 parent 77bca8b commit 470c9b9

2 files changed

Lines changed: 156 additions & 151 deletions

File tree

‎apps/server/src/provider/Layers/AntigravityAdapter.test.ts‎

Lines changed: 23 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -589,9 +589,9 @@ it.layer(layer)("AntigravityAdapter", (it) => {
589589
}),
590590
);
591591

592-
it.effect("waits for native cancellation before a steer changes the model", () =>
592+
it.effect("queues a follow-up turn until the in-flight prompt completes", () =>
593593
Effect.gen(function* () {
594-
const h = yield* makeHarness({ holdCancel: true });
594+
const h = yield* makeHarness();
595595
yield* h.adapter.startSession({
596596
threadId,
597597
cwd: process.cwd(),
@@ -609,38 +609,34 @@ it.layer(layer)("AntigravityAdapter", (it) => {
609609
const second = yield* h.adapter
610610
.sendTurn({
611611
threadId,
612-
input: "Steer the turn",
612+
input: "Follow-up prompt",
613613
modelSelection: { instanceId, model: nativeAlternative },
614614
})
615615
.pipe(Effect.forkChild);
616-
expect(yield* h.nextCancellation).toBe(1);
617-
expect(h.calls.slice(marker)).toEqual(["cancel:1"]);
618-
yield* h.emitNative({
619-
_tag: "ContentDelta",
620-
text: "The first prompt stopped.",
621-
rawPayload: {},
622-
});
623-
yield* Deferred.succeed(h.cancelRelease, undefined);
616+
617+
expect(h.hasActivePrompt()).toBe(true);
618+
expect(h.calls.slice(marker)).toEqual([]);
619+
620+
yield* Deferred.succeed(initialPrompt.result, { stopReason: "end_turn" });
621+
const firstResult = yield* Fiber.join(first);
622+
624623
const replacement = yield* h.nextPrompt;
625624
expect(replacement.content).toEqual([
626-
{ type: "text", text: "Steer the turn" },
625+
{ type: "text", text: "Follow-up prompt" },
627626
{
628627
type: "text",
629628
text: expect.stringContaining(`Antigravity harness, as ${nativeAlternative}`),
630629
},
631630
]);
632631
expect(h.calls.slice(marker)).toEqual([
633-
"cancel:1",
634-
"drained:1",
635632
`model:${nativeAlternative}`,
636633
"mode:default",
637634
"prompt:2",
638635
]);
639636
yield* Deferred.succeed(replacement.result, { stopReason: "end_turn" });
640-
const [oldResult, newResult] = yield* Effect.all([Fiber.join(first), Fiber.join(second)]);
641-
expect(oldResult.turnId).toBe(newResult.turnId);
642-
yield* h.waitForEvent((event) => event.type === "turn.completed");
643-
expect(h.seen.filter((event) => event.type === "turn.completed")).toHaveLength(1);
637+
const secondResult = yield* Fiber.join(second);
638+
expect(firstResult.turnId).not.toBe(secondResult.turnId);
639+
expect(h.seen.filter((event) => event.type === "turn.completed")).toHaveLength(2);
644640
expect((yield* h.adapter.listSessions())[0]).toMatchObject({
645641
status: "ready",
646642
activeTurnId: undefined,
@@ -685,17 +681,20 @@ it.layer(layer)("AntigravityAdapter", (it) => {
685681
runtimeMode: "approval-required",
686682
});
687683
const first = yield* h.adapter.sendTurn({ threadId, input: "First" }).pipe(Effect.forkChild);
688-
yield* h.nextPrompt;
684+
const prompt1 = yield* h.nextPrompt;
689685
h.controls.failModel = true;
690686
const failed = yield* h.adapter
691687
.sendTurn({
692688
threadId,
693689
input: "Replacement",
694690
modelSelection: { instanceId, model: nativeAlternative },
695691
})
696-
.pipe(Effect.exit);
697-
expect(Exit.isFailure(failed)).toBe(true);
692+
.pipe(Effect.forkChild);
693+
yield* Deferred.succeed(prompt1.result, { stopReason: "end_turn" });
698694
yield* Fiber.join(first);
695+
yield* h.waitForEvent((event) => event.type === "turn.completed");
696+
const failedExit = yield* Fiber.join(failed).pipe(Effect.exit);
697+
expect(Exit.isFailure(failedExit)).toBe(true);
699698
const ended = yield* h.waitForEvent((event) => event.type === "turn.completed");
700699
expect(ended.payload.state).toBe("failed");
701700
expect((yield* h.adapter.listSessions())[0]).toMatchObject({
@@ -1090,6 +1089,8 @@ it.layer(layer)("AntigravityAdapter", (it) => {
10901089
const steering = yield* h.adapter
10911090
.sendTurn({ threadId, input: "Change direction" })
10921091
.pipe(Effect.forkChild);
1092+
yield* Deferred.succeed(prompt.result, { stopReason: "end_turn" });
1093+
yield* Fiber.join(sending);
10931094
const replacement = yield* h.nextPrompt;
10941095
yield* Deferred.succeed(replacement.result, { stopReason: "end_turn" });
10951096
yield* Fiber.join(steering);
@@ -1101,12 +1102,7 @@ it.layer(layer)("AntigravityAdapter", (it) => {
11011102
taskId: "trajectory:4",
11021103
title: "Antigravity subagent batch",
11031104
taskType: "subagent_batch",
1104-
status:
1105-
stop === "disconnect"
1106-
? "failed"
1107-
: stop === "cancel" || stop === "steer"
1108-
? "cancelled"
1109-
: "idle",
1105+
status: stop === "disconnect" ? "failed" : stop === "cancel" ? "cancelled" : "idle",
11101106
});
11111107
if (stop === "disconnect")
11121108
yield* h.waitForEvent((event) => event.type === "session.exited");

‎apps/server/src/provider/Layers/AntigravityAdapter.ts‎

Lines changed: 133 additions & 124 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,7 @@ interface SessionContext {
198198
readonly promptLock: Semaphore.Semaphore;
199199
readonly stopLock: Semaphore.Semaphore;
200200
readonly commandLock: Semaphore.Semaphore;
201+
readonly turnQueue: Semaphore.Semaphore;
201202
readonly approvals: Map<ApprovalRequestId, PendingApproval>;
202203
readonly questions: Map<ApprovalRequestId, PendingQuestion>;
203204
readonly commands: Map<string, OpenCommand>;
@@ -871,6 +872,7 @@ export const makeAntigravityAdapter = Effect.fn("makeAntigravityAdapter")(functi
871872
promptLock: yield* Semaphore.make(1),
872873
stopLock: yield* Semaphore.make(1),
873874
commandLock: yield* Semaphore.make(1),
875+
turnQueue: yield* Semaphore.make(1),
874876
approvals: new Map(),
875877
questions: new Map(),
876878
commands: new Map(),
@@ -1026,140 +1028,147 @@ export const makeAntigravityAdapter = Effect.fn("makeAntigravityAdapter")(functi
10261028
});
10271029
}).pipe(Effect.uninterruptible);
10281030

1029-
return yield* Effect.gen(function* () {
1030-
const launch = yield* context.promptLock.withPermit(
1031+
const requestedModel = input.modelSelection?.model ?? context.session.model;
1032+
const configOptions = yield* context.runtime.getConfigOptions;
1033+
const model = resolveAntigravityModel({
1034+
configOptions,
1035+
model: requestedModel,
1036+
defaultModel: yield* options.defaultModel ?? Effect.succeed(undefined),
1037+
});
1038+
const availableModels = antigravityModelOptions(configOptions);
1039+
if (model && !availableModels.some((option) => option.value === model)) {
1040+
return yield* mapAntigravityError(
1041+
input.threadId,
1042+
"session/prompt",
1043+
EffectAcpErrors.AcpRequestError.invalidParams(
1044+
`Antigravity model '${model}' is unavailable for this Google account. Select an available model.`,
1045+
),
1046+
);
1047+
}
1048+
1049+
return yield* context.turnQueue
1050+
.withPermit(
10311051
Effect.gen(function* () {
1032-
yield* requireSession(input.threadId);
1033-
const requestedModel = input.modelSelection?.model ?? context.session.model;
1034-
const configOptions = yield* context.runtime.getConfigOptions;
1035-
const model = resolveAntigravityModel({
1036-
configOptions,
1037-
model: requestedModel,
1038-
defaultModel: yield* options.defaultModel ?? Effect.succeed(undefined),
1039-
});
1040-
const availableModels = antigravityModelOptions(configOptions);
1041-
if (model && !availableModels.some((option) => option.value === model)) {
1042-
return yield* EffectAcpErrors.AcpRequestError.invalidParams(
1043-
`Antigravity model '${model}' is unavailable for this Google account. Select an available model.`,
1044-
);
1045-
}
1046-
const turnId = context.activeTurnId ?? TurnId.make(yield* randomId);
1047-
const steering = context.activeTurnId !== undefined;
1048-
const turn: TurnIntent = { turnId, generation: ++context.generation, settled: false };
1049-
intent = turn;
1050-
context.activeTurnId = turnId;
1051-
if (!steering) {
1052-
yield* emit({
1053-
type: "turn.started",
1054-
...(yield* stamp),
1052+
const launch = yield* context.promptLock.withPermit(
1053+
Effect.gen(function* () {
1054+
yield* requireSession(input.threadId);
1055+
const turnId = TurnId.make(yield* randomId);
1056+
const turn: TurnIntent = { turnId, generation: ++context.generation, settled: false };
1057+
intent = turn;
1058+
context.activeTurnId = turnId;
1059+
yield* emit({
1060+
type: "turn.started",
1061+
...(yield* stamp),
1062+
provider: PROVIDER,
1063+
threadId: input.threadId,
1064+
turnId,
1065+
payload: model ? { model } : {},
1066+
});
1067+
yield* applyAntigravityAcpModelSelection({
1068+
runtime: context.runtime,
1069+
model,
1070+
mapError: (cause) => cause,
1071+
});
1072+
yield* context.runtime.setMode(
1073+
antigravityPermissionMode(context.session.runtimeMode),
1074+
);
1075+
context.session = {
1076+
...context.session,
1077+
status: "running",
1078+
activeTurnId: turnId,
1079+
...(model ? { model } : {}),
1080+
updatedAt: yield* nowIso,
1081+
};
1082+
const dispatched = yield* Deferred.make<void>();
1083+
const fiber = yield* context.runtime
1084+
.prompt(
1085+
{
1086+
prompt: [
1087+
...prompt,
1088+
{
1089+
type: "text",
1090+
text: buildRuntimeInstructions({ harness: "Antigravity", model }),
1091+
},
1092+
],
1093+
},
1094+
{ dispatched },
1095+
)
1096+
.pipe(Effect.forkIn(context.scope));
1097+
context.promptFiber = fiber;
1098+
// Fiber.join can skip a scope-close waiter when the child is interrupted.
1099+
// Unwrap the Exit after Fiber.await returns.
1100+
yield* Effect.raceFirst(
1101+
Deferred.await(dispatched),
1102+
Fiber.await(fiber).pipe(
1103+
Effect.flatMap((exit) => exit),
1104+
Effect.asVoid,
1105+
),
1106+
);
1107+
return { turn, fiber };
1108+
}),
1109+
);
1110+
const result = yield* Fiber.await(launch.fiber).pipe(Effect.flatMap((exit) => exit));
1111+
yield* context.runtime.drainEvents;
1112+
if (context.stopped) {
1113+
return yield* new ProviderAdapterSessionClosedError({
10551114
provider: PROVIDER,
10561115
threadId: input.threadId,
1057-
turnId,
1058-
payload: model ? { model } : {},
10591116
});
10601117
}
1061-
if (context.promptFiber) {
1062-
yield* cancelRequests(context);
1063-
yield* context.runtime.cancel;
1064-
yield* Fiber.await(context.promptFiber);
1065-
yield* finishSubagents(context, "cancelled");
1066-
}
1067-
yield* applyAntigravityAcpModelSelection({
1068-
runtime: context.runtime,
1069-
model,
1070-
mapError: (cause) => cause,
1071-
});
1072-
yield* context.runtime.setMode(antigravityPermissionMode(context.session.runtimeMode));
1073-
context.session = {
1074-
...context.session,
1075-
status: "running",
1076-
activeTurnId: turnId,
1077-
...(model ? { model } : {}),
1078-
updatedAt: yield* nowIso,
1079-
};
1080-
const dispatched = yield* Deferred.make<void>();
1081-
const fiber = yield* context.runtime
1082-
.prompt(
1083-
{
1084-
prompt: [
1085-
...prompt,
1086-
{
1087-
type: "text",
1088-
text: buildRuntimeInstructions({ harness: "Antigravity", model }),
1089-
},
1090-
],
1091-
},
1092-
{ dispatched },
1093-
)
1094-
.pipe(Effect.forkIn(context.scope));
1095-
context.promptFiber = fiber;
1096-
// Fiber.join can skip a scope-close waiter when the child is interrupted.
1097-
// Unwrap the Exit after Fiber.await returns.
1098-
yield* Effect.raceFirst(
1099-
Deferred.await(dispatched),
1100-
Fiber.await(fiber).pipe(
1101-
Effect.flatMap((exit) => exit),
1102-
Effect.asVoid,
1103-
),
1118+
const record = context.turns.find((turn) => turn.id === launch.turn.turnId);
1119+
if (record) record.items.push(result);
1120+
else context.turns.push({ id: launch.turn.turnId, items: [result] });
1121+
yield* context.promptLock.withPermit(
1122+
finishTurn(launch.turn, {
1123+
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
1124+
stopReason: result.stopReason,
1125+
}),
11041126
);
1105-
return { turn, fiber };
1106-
}),
1107-
);
1108-
const result = yield* Fiber.await(launch.fiber).pipe(Effect.flatMap((exit) => exit));
1109-
yield* context.runtime.drainEvents;
1110-
if (context.stopped) {
1111-
return yield* new ProviderAdapterSessionClosedError({
1112-
provider: PROVIDER,
1113-
threadId: input.threadId,
1114-
});
1115-
}
1116-
const record = context.turns.find((turn) => turn.id === launch.turn.turnId);
1117-
if (record) record.items.push(result);
1118-
else context.turns.push({ id: launch.turn.turnId, items: [result] });
1119-
yield* context.promptLock.withPermit(
1120-
finishTurn(launch.turn, {
1121-
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
1122-
stopReason: result.stopReason,
1127+
return {
1128+
threadId: input.threadId,
1129+
turnId: launch.turn.turnId,
1130+
resumeCursor: context.session.resumeCursor,
1131+
};
11231132
}),
1124-
);
1125-
return {
1126-
threadId: input.threadId,
1127-
turnId: launch.turn.turnId,
1128-
resumeCursor: context.session.resumeCursor,
1129-
};
1130-
}).pipe(
1131-
Effect.tapError((cause) =>
1132-
isAntigravitySignInRequiredError(cause)
1133-
? (options.onAuthRequired ?? Effect.void)
1134-
: Effect.void,
1135-
),
1136-
Effect.mapError((cause) =>
1137-
isAcpError(cause) ? mapAntigravityError(input.threadId, "session/prompt", cause) : cause,
1138-
),
1139-
Effect.tapError((cause) =>
1140-
Effect.suspend(() =>
1141-
intent
1142-
? context.promptLock.withPermit(
1143-
finishTurn(intent, { state: "failed", errorMessage: cause.message }),
1144-
)
1133+
)
1134+
.pipe(
1135+
Effect.tapError((cause) =>
1136+
isAntigravitySignInRequiredError(cause)
1137+
? (options.onAuthRequired ?? Effect.void)
11451138
: Effect.void,
11461139
),
1147-
),
1148-
Effect.onInterrupt(() =>
1149-
context.promptLock.withPermit(
1150-
Effect.gen(function* () {
1151-
const turn = intent;
1152-
if (!turn || turn.settled || context.stopped || context.generation !== turn.generation)
1153-
return;
1154-
const promptFiber = context.promptFiber;
1155-
yield* cancelRequests(context);
1156-
yield* Effect.ignore(context.runtime.cancel);
1157-
if (promptFiber) yield* Fiber.interrupt(promptFiber);
1158-
yield* finishTurn(turn, { state: "cancelled", stopReason: "cancelled" });
1159-
}),
1140+
Effect.mapError((cause) =>
1141+
isAcpError(cause) ? mapAntigravityError(input.threadId, "session/prompt", cause) : cause,
11601142
),
1161-
),
1162-
);
1143+
Effect.tapError((cause) =>
1144+
Effect.suspend(() =>
1145+
intent
1146+
? context.promptLock.withPermit(
1147+
finishTurn(intent, { state: "failed", errorMessage: cause.message }),
1148+
)
1149+
: Effect.void,
1150+
),
1151+
),
1152+
Effect.onInterrupt(() =>
1153+
context.promptLock.withPermit(
1154+
Effect.gen(function* () {
1155+
const turn = intent;
1156+
if (
1157+
!turn ||
1158+
turn.settled ||
1159+
context.stopped ||
1160+
context.generation !== turn.generation
1161+
)
1162+
return;
1163+
const promptFiber = context.promptFiber;
1164+
yield* cancelRequests(context);
1165+
yield* Effect.ignore(context.runtime.cancel);
1166+
if (promptFiber) yield* Fiber.interrupt(promptFiber);
1167+
yield* finishTurn(turn, { state: "cancelled", stopReason: "cancelled" });
1168+
}),
1169+
),
1170+
),
1171+
);
11631172
});
11641173

11651174
const interruptTurn: Adapter["interruptTurn"] = (threadId) =>

0 commit comments

Comments
 (0)