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
162 changes: 162 additions & 0 deletions apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -982,6 +982,168 @@ describe("ClaudeAdapterV2 approval cancellation", () => {
assert.deepEqual(result, { decision: "cancel" });
}),
);

it.effect.each([
{ name: "command approval", toolName: "Bash", toolInput: { command: "rm -rf build" } },
{
name: "user question",
toolName: "AskUserQuestion",
toolInput: {
questions: [
{
header: "Target",
question: "Deploy where?",
options: [
{ label: "Production", description: "Deploy to production." },
{ label: "Staging", description: "Deploy to staging." },
],
multiSelect: false,
},
],
},
},
])("closes the $name when the SDK aborts it", ({ toolName, toolInput }) =>
Effect.scoped(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
let openedOptions: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions | undefined;
const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
settings: DEFAULT_CLAUDE_SETTINGS,
environment: {},
attachmentsDir: yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-claude-aborted-request-",
}),
fileSystem,
path: yield* Path.Path,
crypto: yield* Crypto.Crypto,
idAllocator: yield* IdAllocator.IdAllocatorV2,
queryRunner: {
allocateSessionId: Effect.succeed("native-thread-claude-aborted-request"),
open: (input) =>
Effect.sync(() => {
openedOptions = input.options;
return {
messages: Stream.never,
offer: () => Effect.void,
setModel: () => Effect.void,
applyFlagSettings: () => Effect.void,
setPermissionMode: () => Effect.void,
backgroundTasks: () => Effect.succeed(false),
stopTask: () => Effect.void,
interrupt: Effect.void,
close: Effect.void,
};
}),
forkSession: () => Effect.die("unused"),
subagentLaunchToolUseId: () => Effect.succeed(null),
assertComplete: Effect.void,
},
});
const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
runtimeMode: "approval-required",
interactionMode: "default",
cwd: "/workspace",
});
const threadId = ThreadId.make("thread-claude-aborted-request");
const runtime = yield* adapter.openSession({
threadId,
providerSessionId: ProviderSessionId.make("provider-session-claude-aborted-request"),
modelSelection: CLAUDE_TEST_MODEL_SELECTION,
runtimePolicy,
});
const providerThread = yield* runtime.ensureThread({
threadId,
modelSelection: CLAUDE_TEST_MODEL_SELECTION,
runtimePolicy,
});
yield* runtime.startTurn(
makeClaudeTestTurnInput({
threadId,
providerThread,
now: yield* DateTime.now,
attemptId: RunAttemptId.make("attempt-claude-aborted-request"),
text: "Clean the build.",
attachments: [],
runtimePolicy,
}),
);
const canUseTool = openedOptions?.canUseTool;
assert.isFunction(canUseTool);

const opened = yield* runtime.events.pipe(
Stream.filter((event) => event.type === "runtime_request.updated"),
Stream.runHead,
Effect.forkScoped,
);
// A PermissionRequest hook that answers first makes the SDK abort this callback.
const controller = new AbortController();
const result = yield* Effect.promise(() =>
canUseTool!(toolName, toolInput, {
signal: controller.signal,
toolUseID: "tool-aborted-request",
requestId: "request-aborted-request",
}),
).pipe(Effect.forkScoped);
const openedEvent = yield* Fiber.join(opened);
if (Option.isNone(openedEvent) || openedEvent.value.type !== "runtime_request.updated") {
return assert.fail("the request never opened");
}
const request = openedEvent.value.runtimeRequest;
assert.equal(request.status, "pending");

controller.abort();
assert.equal((yield* Fiber.join(result))?.behavior, "deny");
// The event queue never ends, so a later plan marks where the abort's updates must be.
const marker = yield* Effect.promise(() =>
canUseTool!(
"ExitPlanMode",
{ plan: "# Marker" },
{
signal: new AbortController().signal,
toolUseID: "tool-marker",
requestId: "request-marker",
},
),
);
assert.equal(marker?.behavior, "deny");
const afterAbort = yield* runtime.events.pipe(
Stream.takeUntil((event) => event.type === "plan.updated"),
Stream.runCollect,
);

const closedRequest = afterAbort.findLast(
(event) =>
event.type === "runtime_request.updated" && event.runtimeRequest.id === request.id,
);
assert.deepInclude(
closedRequest?.type === "runtime_request.updated" ? closedRequest.runtimeRequest : {},
{ status: "cancelled" },
);
const closedNode = afterAbort.findLast(
(event) => event.type === "node.updated" && event.node.id === request.nodeId,
);
assert.equal(
closedNode?.type === "node.updated" ? closedNode.node.status : null,
"cancelled",
);
const closedItem = afterAbort.findLast(
(event) =>
event.type === "turn_item.updated" &&
"requestId" in event.turnItem &&
event.turnItem.requestId === request.id,
);
assert.equal(
closedItem?.type === "turn_item.updated" ? closedItem.turnItem.status : null,
"cancelled",
);
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
),
);
});

const captureSdkExecutablePaths = Effect.fn("captureSdkExecutablePaths")(function* (
Expand Down
25 changes: 25 additions & 0 deletions apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8848,6 +8848,29 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
yield* handleRoutedSdkMessage(input);
});

// No user response will close a request the SDK aborted, such as one a hook answered.
const cancelRuntimeRequest = Effect.fn("ClaudeAdapterV2.cancelRuntimeRequest")(function* (
artifacts: Effect.Success<ReturnType<typeof buildApprovalRequestArtifacts>>,
) {
const now = yield* DateTime.now;
const cancelled = { status: "cancelled", completedAt: now } as const;
yield* emitProviderEvent({
type: "node.updated",
driver: CLAUDE_PROVIDER,
node: { ...artifacts.node, ...cancelled },
});
yield* emitProviderEvent({
type: "runtime_request.updated",
driver: CLAUDE_PROVIDER,
runtimeRequest: { ...artifacts.request, status: "cancelled", resolvedAt: now },
});
yield* emitProviderEvent({
type: "turn_item.updated",
driver: CLAUDE_PROVIDER,
turnItem: { ...artifacts.turnItem, ...cancelled, updatedAt: now },
});
});

const canUseToolEffect = Effect.fn("ClaudeAdapterV2.canUseTool")(function* (
toolName: Parameters<CanUseTool>[0],
toolInput: Parameters<CanUseTool>[1],
Expand Down Expand Up @@ -8957,6 +8980,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
}),
),
);
if (!(yield* Deferred.isDone(answers))) yield* cancelRuntimeRequest(artifacts);
return callbackOptions.signal.aborted
? ({
behavior: "deny",
Expand Down Expand Up @@ -9074,6 +9098,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
}),
),
);
if (!(yield* Deferred.isDone(decision))) yield* cancelRuntimeRequest(artifacts);

return permissionResultFromDecision({
toolName,
Expand Down
76 changes: 33 additions & 43 deletions apps/server/src/orchestration-v2/EventSink.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import {
RunAttemptId,
RunId,
RuntimeRequestId,
NodeId,
type ProjectId,
ThreadId,
} from "@t3tools/contracts";
Expand Down Expand Up @@ -73,7 +72,7 @@ export interface EventSinkV2Shape {
OrchestrationV2ProviderThread,
"driver" | "providerInstanceId" | "appThreadId" | "nativeThreadRef"
>;
readonly guardPendingUserInputCancellations?: boolean;
readonly guardPendingRequestCancellations?: boolean;
readonly commandId?: CommandId;
readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
}) => Effect.Effect<ReadonlyArray<OrchestrationV2StoredEvent>, EventSinkV2Error>;
Expand All @@ -87,13 +86,13 @@ export interface EventSinkV2Shape {
OrchestrationV2ProviderThread,
"driver" | "providerInstanceId" | "appThreadId" | "nativeThreadRef"
>;
readonly guardPendingUserInputCancellations?: boolean;
readonly guardPendingRequestCancellations?: boolean;
readonly commandId?: CommandId;
readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
readonly effects: ReadonlyArray<EffectOutbox.PendingOrchestrationEffectV2>;
}) => Effect.Effect<ReadonlyArray<OrchestrationV2StoredEvent>, EventSinkV2Error>;
readonly writeIfRunCurrent: (input: {
readonly guardPendingUserInputCancellations?: boolean;
readonly guardPendingRequestCancellations?: boolean;
readonly commandId?: CommandId;
readonly threadId: ThreadId;
readonly runId: RunId;
Expand All @@ -115,7 +114,7 @@ export interface EventSinkV2Shape {
* a newer attempt that already claimed the thread.
*/
readonly writeIfProviderThreadOwner: (input: {
readonly guardPendingUserInputCancellations?: boolean;
readonly guardPendingRequestCancellations?: boolean;
readonly commandId?: CommandId;
readonly providerThreadId: ProviderThreadId;
readonly runId: RunId;
Expand Down Expand Up @@ -208,6 +207,17 @@ export class EventSinkV2 extends Context.Service<EventSinkV2, EventSinkV2Shape>(
"t3/orchestration-v2/EventSink/EventSinkV2",
) {}

const cancelledRuntimeRequestId = (event: OrchestrationV2DomainEvent) =>
!("status" in event.payload) || event.payload.status !== "cancelled"
? null
: event.type === "runtime-request.updated"
? event.payload.id
: event.type === "node.updated"
? event.payload.runtimeRequestId
: event.type === "turn-item.updated" && "requestId" in event.payload
? event.payload.requestId
: null;

const layerBase: Layer.Layer<
EventSinkV2,
never,
Expand Down Expand Up @@ -293,47 +303,27 @@ const layerBase: Layer.Layer<

// A user can answer after terminal normalization reads the pending request.
// Recheck inside the write transaction so stale cleanup cannot erase answers.
const guardUserInputCancellations =
const guardRuntimeRequestCancellations =
/* This helper runs for individual orchestration events; the enclosing operation owns the span. */
Effect.fnUntraced(function* (events: ReadonlyArray<OrchestrationV2DomainEvent>) {
const staleRequests = new Set<RuntimeRequestId>();
const staleNodes = new Set<NodeId>();
for (const event of events) {
const requestId = cancelledRuntimeRequestId(event);
if (requestId === null) continue;
const current = yield* projectionStore.getRuntimeRequest(event.threadId, requestId);
if (
event.type !== "runtime-request.updated" ||
event.payload.kind !== "user_input" ||
event.payload.status !== "cancelled"
)
continue;
const current = yield* projectionStore.getRuntimeRequest(
event.threadId,
event.payload.id,
);
if (
current?.status !== "pending" ||
current.kind !== "user_input" ||
current.providerTurnId !== event.payload.providerTurnId ||
current.responseCapability.type === "message"
(event.type === "runtime-request.updated"
? current?.status !== "pending" ||
current.providerTurnId !== event.payload.providerTurnId
: current?.status === "resolved") ||
(current?.kind === "user_input" && current.responseCapability.type === "message")
) {
staleRequests.add(event.payload.id);
staleNodes.add(event.payload.nodeId);
staleRequests.add(requestId);
}
}
return events.filter((event) => {
switch (event.type) {
case "runtime-request.updated":
return event.payload.status !== "cancelled" || !staleRequests.has(event.payload.id);
case "node.updated":
return event.payload.status !== "cancelled" || !staleNodes.has(event.payload.id);
case "turn-item.updated":
return (
event.payload.type !== "user_input_request" ||
event.payload.status !== "cancelled" ||
!staleRequests.has(event.payload.requestId)
);
default:
return true;
}
const requestId = cancelledRuntimeRequestId(event);
return requestId === null || !staleRequests.has(requestId);
});
});

Expand Down Expand Up @@ -443,8 +433,8 @@ const layerBase: Layer.Layer<
)
: input.events;
const normalized = yield* normalizeEvents(
input.guardPendingUserInputCancellations === true
? yield* guardUserInputCancellations(events)
input.guardPendingRequestCancellations === true
? yield* guardRuntimeRequestCancellations(events)
: events,
);
const committed = yield* eventStore.append({
Expand Down Expand Up @@ -502,8 +492,8 @@ const layerBase: Layer.Layer<
}

const normalized = yield* normalizeEvents(
input.guardPendingUserInputCancellations === true
? yield* guardUserInputCancellations(input.events)
input.guardPendingRequestCancellations === true
? yield* guardRuntimeRequestCancellations(input.events)
: input.events,
);
const storedEvents = yield* eventStore.append({
Expand Down Expand Up @@ -567,8 +557,8 @@ const layerBase: Layer.Layer<
}

const normalized = yield* normalizeEvents(
input.guardPendingUserInputCancellations === true
? yield* guardUserInputCancellations(input.events)
input.guardPendingRequestCancellations === true
? yield* guardRuntimeRequestCancellations(input.events)
: input.events,
);
const storedEvents = yield* eventStore.append({
Expand Down
Loading
Loading