Skip to content
TypeScript

fix(claude): route approval feedback to the requesting agent (#23657)

Yash Singhb7e802bdec91
diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
index e8f99bf4e64..57f671957a8 100644
--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
@@ -55,6 +55,7 @@ import {
} from "@t3tools/shared/codexArtifactTemplates";
import {
declinePendingApprovals,
+ sendApprovalFeedback,
type ApprovalResponder,
type ThreadUserInputQuestion,
} from "@t3tools/client-runtime/state/thread-requests";
@@ -258,7 +259,10 @@ export interface ThreadDetailScreenProps {
readonly onResumeQueue: (() => Promise<void>) | null;
readonly onSendMessage: (
followUp?: ActiveTurnComposerAction,
- beforeDispatch?: () => Promise<boolean>,
+ beforeDispatch?: (
+ text: string,
+ hasAttachmentsOrContext: boolean,
+ ) => Promise<boolean | "responded">,
) => Promise<MessageId | null>;
readonly onReconnectEnvironment: () => void;
readonly canSwitchThreadProvider: boolean;
@@ -1199,18 +1203,40 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
const approvalsToDecline = props.activePendingApprovals;
const declineBeforeDispatch =
approvalsToDecline.length > 0 && props.activePendingUserInput === null
- ? async () =>
- props.respondingApprovalId === null &&
- (await declinePendingApprovals(approvalsToDecline, props.onRespondToApproval)) &&
- selectedThreadKeyRef.current === targetThreadKey &&
- // A draft edited or pasted into during the decline isn't what the user sent.
- stillSendable?.() !== false &&
- // An approval that arrived during the decline would block the redirect; the draft
- // stays so the next send declines it too.
- !activePendingApprovalsRef.current.some(
- (approval) =>
- !approvalsToDecline.some((declined) => declined.requestId === approval.requestId),
+ ? async (text: string, hasAttachmentsOrContext: boolean) => {
+ if (
+ selectedThreadKeyRef.current !== targetThreadKey ||
+ stillSendable?.() === false ||
+ props.respondingApprovalId !== null
)
+ return false;
+ const feedbackTarget = approvalsToDecline[0];
+ if (feedbackTarget?.supportsFeedback) {
+ if (hasAttachmentsOrContext) {
+ Dialog.alert(
+ "Approval feedback",
+ "Send approval feedback without attachments or added context.",
+ );
+ return false;
+ }
+ return (await sendApprovalFeedback(feedbackTarget, text, props.onRespondToApproval))
+ ? ("responded" as const)
+ : false;
+ }
+ return (
+ props.respondingApprovalId === null &&
+ (await declinePendingApprovals(approvalsToDecline, props.onRespondToApproval)) &&
+ selectedThreadKeyRef.current === targetThreadKey &&
+ // A draft edited or pasted into during the decline isn't what the user sent.
+ stillSendable?.() !== false &&
+ // An approval that arrived during the decline would block the redirect; the draft
+ // stays so the next send declines it too.
+ !activePendingApprovalsRef.current.some(
+ (approval) =>
+ !approvalsToDecline.some((declined) => declined.requestId === approval.requestId),
+ )
+ );
+ }
: undefined;
const messageId = await props.onSendMessage(followUp, declineBeforeDispatch);
if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
@@ -1642,7 +1668,9 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
editorRef={composerEditorRef}
placeholder={
props.activePendingApproval
- ? "Send a message to decline and redirect the agent"
+ ? props.activePendingApproval.supportsFeedback
+ ? "Send feedback to decline this request"
+ : "Send a message to decline and redirect the agent"
: "Ask the repo agent, or run a command…"
}
contentMaxWidth={contentMaxWidth}
diff --git a/apps/mobile/src/state/thread-task-permissions.test.ts b/apps/mobile/src/state/thread-task-permissions.test.ts
index eac2e40e983..4c962cf5be6 100644
--- a/apps/mobile/src/state/thread-task-permissions.test.ts
+++ b/apps/mobile/src/state/thread-task-permissions.test.ts
@@ -18,6 +18,7 @@ import {
} from "../../../../packages/client-runtime/src/state/orchestrationV2TestFixtures";
import type { DraftComposerImageAttachment } from "../lib/composerImages";
import type { PendingThreadRequests } from "@t3tools/client-runtime/state/thread-requests";
+import { sendApprovalFeedback } from "@t3tools/client-runtime/state/thread-requests";
import { AsyncResult, type Atom } from "effect/reactivity";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
@@ -202,6 +203,43 @@ beforeEach(() => {
});
describe("mobile task permissions", () => {
+ it("consumes an approval reply without queueing a parent message", async () => {
+ state.grantedEnvironments.add("secondary");
+ const composer = useThreadComposerState();
+ const requests = useSelectedThreadRequests();
+ const approval = { ...state.pendingRequests.approvals[0]!, supportsFeedback: true };
+ const messageId = await composer.onSendMessage(undefined, async (text) =>
+ (await sendApprovalFeedback(approval, text, requests.onRespondToApproval))
+ ? "responded"
+ : false,
+ );
+ expect(messageId).toBeNull();
+ expect(state.approve).toHaveBeenCalledWith({
+ environmentId: "secondary",
+ input: {
+ threadId: "thread",
+ requestId: "approval",
+ decision: "decline",
+ feedback: "Keep my draft",
+ },
+ });
+ expect(state.enqueue).not.toHaveBeenCalled();
+ expect(state.clearDraft).toHaveBeenCalledOnce();
+ });
+
+ it("preserves a draft changed during an approval reply and never sends it to the parent", async () => {
+ state.grantedEnvironments.add("secondary");
+ const composer = useThreadComposerState();
+ const beforeDispatch = async () => {
+ state.draft = { ...state.draft, text: "New feedback" };
+ return "responded" as const;
+ };
+ expect(await composer.onSendMessage(undefined, beforeDispatch)).toBeNull();
+ expect(state.enqueue).not.toHaveBeenCalled();
+ expect(state.clearDraft).not.toHaveBeenCalled();
+ expect(state.draft.text).toBe("New feedback");
+ });
+
it("keeps a connected read-only task's draft instead of queueing it with another environment's grant", async () => {
const composer = useThreadComposerState();
expect(await composer.onSendMessage()).toBeNull();
diff --git a/apps/mobile/src/state/use-selected-thread-requests.ts b/apps/mobile/src/state/use-selected-thread-requests.ts
index 98bec975332..1371b520604 100644
--- a/apps/mobile/src/state/use-selected-thread-requests.ts
+++ b/apps/mobile/src/state/use-selected-thread-requests.ts
@@ -236,7 +236,7 @@ export function useSelectedThreadRequests() {
);
const onRespondToApproval = useCallback(
- async (requestId: RuntimeRequestId, decision: ProviderApprovalDecision) => {
+ async (requestId: RuntimeRequestId, decision: ProviderApprovalDecision, feedback?: string) => {
if (
!selectedThreadShell ||
!readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope)
@@ -257,6 +257,7 @@ export function useSelectedThreadRequests() {
threadId: selectedThreadShell.id,
requestId,
decision,
+ ...(feedback === undefined ? {} : { feedback }),
},
});
setRespondingApprovalId((current) => (current === requestId ? null : current));
diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts
index afd952d43ab..ec71677013b 100644
--- a/apps/mobile/src/state/use-thread-composer-state.ts
+++ b/apps/mobile/src/state/use-thread-composer-state.ts
@@ -526,7 +526,10 @@ export function useThreadComposerState() {
const onSendMessage = async (
followUpOverride?: ActiveTurnComposerAction,
- beforeDispatch?: () => Promise<boolean>,
+ beforeDispatch?: (
+ text: string,
+ hasAttachmentsOrContext: boolean,
+ ) => Promise<boolean | "responded">,
) => {
if (
selectedThreadShell &&
@@ -645,7 +648,11 @@ export function useThreadComposerState() {
}
if (beforeDispatch !== undefined) {
- if (!(await beforeDispatch())) return null;
+ const response = await beforeDispatch(
+ text,
+ attachments.length > 0 || draft.context !== undefined,
+ );
+ if (!response) return null;
// A context paste still landing, or any draft or settings change while approvals were
// declined, means this snapshot is no longer what the user sent.
if (appAtomRegistry.get(composerContextImportsAtom)[threadKey]) return null;
@@ -660,6 +667,10 @@ export function useThreadComposerState() {
current.attachments.some((attachment, index) => attachment.id !== attachments[index]?.id)
)
return null;
+ if (response === "responded") {
+ clearComposerDraftContent(threadKey);
+ return null;
+ }
}
// Resolved here rather than at drain time: the outbox can deliver minutes
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
index b231fbfca9d..0c8b2ad588a 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
@@ -967,7 +967,10 @@ describe("ClaudeAdapterV2 append-system-prompt-file launch argument", () => {
describe("ClaudeAdapterV2 approval cancellation", () => {
it.effect("observes an approval signal that was already aborted", () =>
Effect.gen(function* () {
- const decision = yield* Deferred.make<ProviderApprovalDecision>();
+ const decision = yield* Deferred.make<{
+ decision: ProviderApprovalDecision;
+ feedback?: string;
+ }>();
const controller = new AbortController();
controller.abort();
@@ -976,7 +979,7 @@ describe("ClaudeAdapterV2 approval cancellation", () => {
controller.signal,
);
- assert.equal(result, "cancel");
+ assert.deepEqual(result, { decision: "cancel" });
}),
);
});
@@ -2873,12 +2876,14 @@ describe("ClaudeAdapterV2 background wake turns", () => {
turn: Effect.Success<ReturnType<typeof openPlanTurn>>,
toolName: string,
toolInput: Record<string, unknown>,
+ options?: { toolUseID: string; agentID?: string },
) {
const decision = yield* Effect.promise(() =>
turn.canUseTool(toolName, toolInput, {
signal: new AbortController().signal,
- toolUseID: "tool-plan-write",
+ toolUseID: options?.toolUseID ?? "tool-plan-write",
requestId: "request-plan-write",
+ ...(options?.agentID === undefined ? {} : { agentID: options.agentID }),
}),
).pipe(Effect.forkScoped);
const first = yield* Effect.raceFirst(
@@ -2954,6 +2959,61 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);
+ it.effect(
+ "returns approval feedback to the requesting tool without sending a parent prompt",
+ () =>
+ Effect.gen(function* () {
+ const turn = yield* openPlanTurn("full-access");
+ const parentPermission = yield* requestWrite(
+ turn,
+ "Bash",
+ { command: "git status" },
+ { toolUseID: "parent-command" },
+ );
+ assert.equal(parentPermission.first.type, "request");
+ if (parentPermission.first.type !== "request") return;
+ const permission = yield* requestWrite(
+ turn,
+ "Bash",
+ { command: "rm -f $W/*/*.obj" },
+ { toolUseID: "child-command", agentID: "child-worker" },
+ );
+ assert.equal(permission.first.type, "request");
+ if (permission.first.type !== "request") return;
+ const request = permission.first.event.runtimeRequest;
+ assert.equal(request.responseCapability.type, "live");
+ assert.isTrue(
+ request.responseCapability.type === "live" &&
+ request.responseCapability.supportsFeedback,
+ );
+ yield* turn.runtime.respondToRuntimeRequest({
+ requestId: request.id,
+ decision: "decline",
+ feedback: "Run it in a safer manner.",
+ });
+ const result = yield* Fiber.join(permission.decision);
+ assert.equal(result?.behavior, "deny");
+ if (result?.behavior === "deny") {
+ assert.include(result.message, "Run it in a safer manner.");
+ assert.notProperty(result, "interrupt");
+ }
+ assert.equal(turn.offeredMessages.length, 1);
+ yield* turn.runtime.respondToRuntimeRequest({
+ requestId: parentPermission.first.event.runtimeRequest.id,
+ decision: "accept",
+ });
+ const parentResult = yield* Fiber.join(parentPermission.decision);
+ assert.equal(parentResult?.behavior, "allow");
+ if (parentResult?.behavior === "allow")
+ assert.equal(parentResult.toolUseID, "parent-command");
+ }).pipe(
+ Effect.scoped,
+ Effect.provide(
+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
+ ),
+ ),
+ );
+
it.effect("still captures ExitPlanMode when Plan approvals are never allowed", () =>
Effect.gen(function* () {
const turn = yield* openPlanTurn("full-access", "never");
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
index 49b344961b3..91c08f565a2 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
@@ -2892,6 +2892,7 @@ export function permissionResultFromDecision(input: {
readonly toolInput: Record<string, unknown>;
readonly toolUseID: string;
readonly suggestions?: Parameters<CanUseTool>[2]["suggestions"];
+ readonly feedback?: string;
}): PermissionResult {
if (input.decision === "accept" || input.decision === "acceptForSession") {
return {
@@ -2911,9 +2912,10 @@ export function permissionResultFromDecision(input: {
return {
behavior: "deny",
message:
- input.decision === "cancel"
+ input.feedback?.trim() ||
+ (input.decision === "cancel"
? "User cancelled tool execution."
- : "User declined tool execution.",
+ : "User declined tool execution."),
toolUseID: input.toolUseID,
decisionClassification: "user_reject",
...(input.decision === "cancel" ? { interrupt: true } : {}),
@@ -2942,11 +2944,11 @@ function toSessionPermissionUpdates(
}
export const awaitClaudeApprovalDecision = Effect.fn("awaitClaudeApprovalDecision")(function* (
- decision: Deferred.Deferred<ProviderApprovalDecision>,
+ decision: Deferred.Deferred<ClaudeApprovalResponse>,
signal: AbortSignal,
) {
- const cancellation = Effect.callback<ProviderApprovalDecision>((resume) => {
- const abort = () => resume(Effect.succeed("cancel"));
+ const cancellation = Effect.callback<ClaudeApprovalResponse>((resume) => {
+ const abort = () => resume(Effect.succeed({ decision: "cancel" }));
signal.addEventListener("abort", abort, { once: true });
if (signal.aborted) {
abort();
@@ -3625,12 +3627,17 @@ function rememberClaudeSubagentLaunch(
}
}
+type ClaudeApprovalResponse = {
+ readonly decision: ProviderApprovalDecision;
+ readonly feedback?: string;
+};
+
type PendingClaudeRuntimeRequest =
| {
readonly type: "approval";
readonly requestId: OrchestrationV2RuntimeRequest["id"];
readonly requestKind: ProviderRequestKind;
- readonly decision: Deferred.Deferred<ProviderApprovalDecision, never>;
+ readonly decision: Deferred.Deferred<ClaudeApprovalResponse, never>;
}
| {
readonly type: "user_input";
@@ -6467,6 +6474,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
responseCapability: {
type: "live",
providerSessionId,
+ ...(input.questions === undefined ? { supportsFeedback: true } : {}),
},
createdAt,
resolvedAt: null,
@@ -8986,7 +8994,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
callbackOptions,
}),
});
- const decision = yield* Deferred.make<ProviderApprovalDecision, never>();
+ const decision = yield* Deferred.make<ClaudeApprovalResponse, never>();
yield* Ref.update(pendingRuntimeRequests, (current) => {
const updated = new Map(current);
updated.set(String(artifacts.request.id), {
@@ -9033,7 +9041,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
return permissionResultFromDecision({
toolName,
- decision: resolvedDecision,
+ ...resolvedDecision,
toolInput,
toolUseID: callbackOptions.toolUseID,
...(callbackOptions.suggestions === undefined
@@ -10283,7 +10291,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
}),
});
}
- yield* Deferred.succeed(pending.decision, requestInput.decision);
+ yield* Deferred.succeed(pending.decision, {
+ decision: requestInput.decision,
+ ...(requestInput.feedback === undefined ? {} : { feedback: requestInput.feedback }),
+ });
},
(effect, requestInput) =>
effect.pipe(
diff --git a/apps/server/src/orchestration-v2/EffectOutbox.ts b/apps/server/src/orchestration-v2/EffectOutbox.ts
index c89beae951e..6818ba361df 100644
--- a/apps/server/src/orchestration-v2/EffectOutbox.ts
+++ b/apps/server/src/orchestration-v2/EffectOutbox.ts
@@ -80,6 +80,7 @@ export const OrchestrationEffectRequestV2 = Schema.Union([
providerSessionId: ProviderSessionId,
requestId: RuntimeRequestId,
decision: Schema.optional(ProviderApprovalDecision),
+ feedback: Schema.optional(Schema.String),
answers: Schema.optional(ProviderUserInputAnswers),
}),
Schema.Struct({
diff --git a/apps/server/src/orchestration-v2/EffectWorker.ts b/apps/server/src/orchestration-v2/EffectWorker.ts
index ebcb50debd1..42128b88371 100644
--- a/apps/server/src/orchestration-v2/EffectWorker.ts
+++ b/apps/server/src/orchestration-v2/EffectWorker.ts
@@ -384,6 +384,9 @@ export const layerExecutor: Layer.Layer<
...(effect.request.decision === undefined
? {}
: { decision: effect.request.decision }),
+ ...(effect.request.feedback === undefined
+ ? {}
+ : { feedback: effect.request.feedback }),
...(effect.request.answers === undefined
? {}
: { answers: effect.request.answers }),
diff --git a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts
index eda76857a9e..6259fd78db6 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts
@@ -57,6 +57,142 @@ const layerTest = Layer.mergeAll(
),
);
+it.effect(
+ "records approval feedback and targets only its runtime request without dispatching a parent turn",
+ () =>
+ Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
+ const outbox = yield* EffectOutbox.EffectOutboxV2;
+ const threadId = ThreadId.make("thread:approval-feedback");
+ const sessionId = ProviderSessionId.make("session:approval-feedback");
+ const now = yield* DateTime.now;
+ yield* orchestrator.dispatch({
+ type: "thread.create",
+ commandId: CommandId.make("create-approval-feedback"),
+ threadId,
+ projectId: ProjectId.make("project:approval-feedback"),
+ title: "Parent",
+ modelSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ createdBy: "user",
+ creationSource: "web",
+ });
+ yield* projections.apply({
+ id: EventId.make("session:approval-feedback"),
+ type: "provider-session.attached",
+ threadId,
+ occurredAt: now,
+ payload: {
+ id: sessionId,
+ driver: adapter.driver,
+ providerInstanceId: instanceId,
+ status: "ready",
+ cwd: "/repo",
+ model: modelSelection.model,
+ capabilities: CodexProviderCapabilitiesV2,
+ createdAt: now,
+ updatedAt: now,
+ lastError: null,
+ },
+ });
+ for (const name of ["child", "other"]) {
+ yield* projections.apply({
+ id: EventId.make(`request:${name}`),
+ type: "runtime-request.updated",
+ threadId,
+ occurredAt: now,
+ payload: {
+ id: RuntimeRequestId.make(name),
+ nodeId: NodeId.make(`node:${name}`),
+ providerTurnId: null,
+ nativeRequestRef: null,
+ kind: "command",
+ status: "pending",
+ responseCapability: {
+ type: "live",
+ providerSessionId: sessionId,
+ supportsFeedback: name === "child",
+ },
+ createdAt: now,
+ resolvedAt: null,
+ },
+ });
+ }
+ const commandId = CommandId.make("respond:approval-feedback");
+ const feedback = "Run it in a safer manner.";
+ for (const [index, invalid] of [
+ { requestId: RuntimeRequestId.make("other"), decision: "decline" as const, feedback },
+ { requestId: RuntimeRequestId.make("child"), decision: "accept" as const, feedback },
+ { requestId: RuntimeRequestId.make("child"), decision: "decline" as const, feedback: " " },
+ ].entries()) {
+ const rejectedId = CommandId.make(`invalid-feedback:${index}`);
+ const rejected = yield* orchestrator
+ .dispatch({
+ type: "runtime-request.respond",
+ commandId: rejectedId,
+ threadId,
+ ...invalid,
+ })
+ .pipe(Effect.result);
+ assert.isTrue(Result.isFailure(rejected));
+ assert.deepEqual(yield* outbox.listByCommandId(rejectedId), []);
+ }
+ yield* orchestrator.dispatch({
+ type: "runtime-request.respond",
+ commandId,
+ threadId,
+ requestId: RuntimeRequestId.make("child"),
+ decision: "decline",
+ feedback,
+ });
+ const projection = yield* projections.getThreadProjection(threadId);
+ assert.equal(
+ projection.runtimeRequests.find((request) => request.id === "child")?.feedback,
+ feedback,
+ );
+ assert.equal(
+ projection.runtimeRequests.find((request) => request.id === "other")?.status,
+ "pending",
+ );
+ assert.equal(projection.messages.at(-1)?.text, feedback);
+ const feedbackMessageId = MessageId.make("approval-feedback:child");
+ assert.ok(
+ projection.visibleTurnItems.some(
+ ({ item }) =>
+ item.type === "user_message" &&
+ item.messageId === feedbackMessageId &&
+ item.text === feedback,
+ ),
+ );
+ const history = yield* projections.getTimelinePage(threadId, { limit: 20, view: "messages" });
+ assert.ok(
+ history.items.some(
+ ({ item }) =>
+ item.type === "user_message" &&
+ item.messageId === feedbackMessageId &&
+ item.text === feedback,
+ ),
+ );
+ assert.equal(projection.runs.length, 0);
+ assert.deepEqual(
+ (yield* outbox.listByCommandId(commandId)).map((effect) => effect.request),
+ [
+ {
+ type: "runtime-request.respond",
+ providerSessionId: sessionId,
+ requestId: RuntimeRequestId.make("child"),
+ decision: "decline",
+ feedback,
+ },
+ ],
+ );
+ }).pipe(Effect.provide(layerTest)),
+);
+
it.effect("marks a never-visited thread's first completion unread", () =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts
index f9cb1bf9dd9..5dd48ba548d 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.ts
@@ -7673,6 +7673,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
cause: runtimeRequest.responseCapability.reason,
});
}
+ if (
+ command.feedback !== undefined &&
+ (runtimeRequest.responseCapability.type !== "live" ||
+ !runtimeRequest.responseCapability.supportsFeedback ||
+ runtimeRequest.kind === "user_input" ||
+ command.decision !== "decline" ||
+ !command.feedback.trim())
+ ) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: "Feedback requires a live approval that supports it and a decline decision.",
+ });
+ }
const providerSessionId =
runtimeRequest.responseCapability.type === "live"
? runtimeRequest.responseCapability.providerSessionId
@@ -7702,10 +7716,73 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
status: "resolved" as const,
resolvedAt: now,
...(command.decision === undefined ? {} : { decision: command.decision }),
+ ...(command.feedback === undefined ? {} : { feedback: command.feedback }),
...(answers === undefined ? {} : { answers }),
};
const emitEvent = emit(events, command);
const requestNode = context.node;
+ if (command.feedback !== undefined) {
+ const messageId = MessageId.make(`approval-feedback:${command.requestId}`);
+ // Record the reply for every client without dispatching a prompt to the parent agent.
+ yield* emitEvent({
+ type: "message.updated",
+ threadId: command.threadId,
+ ...(requestNode?.runId == null ? {} : { runId: requestNode.runId }),
+ nodeId: runtimeRequest.nodeId,
+ occurredAt: now,
+ payload: {
+ id: messageId,
+ threadId: command.threadId,
+ runId: requestNode?.runId ?? null,
+ nodeId: runtimeRequest.nodeId,
+ role: "user",
+ text: command.feedback,
+ attachments: [],
+ streaming: false,
+ createdBy: "user",
+ creationSource: "server",
+ createdAt: now,
+ updatedAt: now,
+ },
+ });
+ yield* emitEvent({
+ type: "turn-item.updated",
+ threadId: command.threadId,
+ ...(requestNode?.runId == null ? {} : { runId: requestNode.runId }),
+ nodeId: runtimeRequest.nodeId,
+ occurredAt: now,
+ payload: {
+ id: idAllocator.derive.userTurnItem({ messageId }),
+ threadId: command.threadId,
+ runId: requestNode?.runId ?? null,
+ nodeId: runtimeRequest.nodeId,
+ providerThreadId:
+ context.item?.providerThreadId ?? requestNode?.providerThreadId ?? null,
+ providerTurnId: runtimeRequest.providerTurnId,
+ nativeItemRef: null,
+ parentItemId: null,
+ ordinal: yield* projectionStore
+ .getNextTurnItemOrdinal(command.threadId)
+ .pipe(
+ Effect.mapError(
+ (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }),
+ ),
+ ),
+ status: "completed",
+ title: null,
+ startedAt: now,
+ completedAt: now,
+ updatedAt: now,
+ type: "user_message",
+ messageId,
+ inputIntent: "steer",
+ text: command.feedback,
+ attachments: [],
+ createdBy: "user",
+ creationSource: "server",
+ },
+ });
+ }
const resolvedNodeStatus =
command.decision === "decline" || command.decision === "cancel"
? ("cancelled" as const)
@@ -7872,6 +7949,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
providerSessionId,
requestId: command.requestId,
...(command.decision === undefined ? {} : { decision: command.decision }),
+ ...(command.feedback === undefined ? {} : { feedback: command.feedback }),
...(answers === undefined ? {} : { answers }),
},
} satisfies PendingOrchestrationEffectV2,
diff --git a/apps/server/src/orchestration-v2/RuntimeRequestService.test.ts b/apps/server/src/orchestration-v2/RuntimeRequestService.test.ts
index 70ddb5e84ef..0c6aa9d97b1 100644
--- a/apps/server/src/orchestration-v2/RuntimeRequestService.test.ts
+++ b/apps/server/src/orchestration-v2/RuntimeRequestService.test.ts
@@ -16,70 +16,88 @@ import * as ProjectionStore from "./ProjectionStore.ts";
import * as ProviderSessionManager from "./ProviderSessionManager.ts";
import * as RuntimeRequestService from "./RuntimeRequestService.ts";
-it.effect("rejects expired runtime requests before invoking the live adapter", () => {
- const threadId = ThreadId.make("thread-runtime-request-expired");
- const providerSessionId = ProviderSessionId.make("provider-session-runtime-request-expired");
- const requestId = RuntimeRequestId.make("request-expired");
- const respondToRuntimeRequest = vi.fn(
- (_input: ProviderAdapter.ProviderAdapterV2RuntimeRequestResponseInput) => Effect.void,
- );
- const getSession = vi.fn(() =>
- Effect.succeed(
- Option.some({
- respondToRuntimeRequest,
- } as never),
- ),
- );
- const projection = {
- runtimeRequests: [
- {
- id: requestId,
- nodeId: NodeId.make("node-runtime-request-expired"),
- providerTurnId: null,
- nativeRequestRef: null,
- kind: "command",
- status: "expired",
- responseCapability: {
- type: "live",
- providerSessionId,
+it.effect.each(["expired", "resolved"] as const)(
+ "responds only to resolved requests and preserves feedback (%s)",
+ (status) => {
+ const threadId = ThreadId.make("thread-runtime-request-expired");
+ const providerSessionId = ProviderSessionId.make("provider-session-runtime-request-expired");
+ const requestId = RuntimeRequestId.make("request-expired");
+ const respondToRuntimeRequest = vi.fn(
+ (_input: ProviderAdapter.ProviderAdapterV2RuntimeRequestResponseInput) => Effect.void,
+ );
+ const getSession = vi.fn(() =>
+ Effect.succeed(
+ Option.some({
+ respondToRuntimeRequest,
+ } as never),
+ ),
+ );
+ const projection = {
+ runtimeRequests: [
+ {
+ id: requestId,
+ nodeId: NodeId.make("node-runtime-request-expired"),
+ providerTurnId: null,
+ nativeRequestRef: null,
+ kind: "command",
+ status,
+ responseCapability: {
+ type: "live",
+ providerSessionId,
+ },
+ createdAt: DateTime.makeUnsafe("2026-07-29T00:00:00.000Z"),
+ resolvedAt: DateTime.makeUnsafe("2026-07-29T00:00:01.000Z"),
},
- createdAt: DateTime.makeUnsafe("2026-07-29T00:00:00.000Z"),
- resolvedAt: DateTime.makeUnsafe("2026-07-29T00:00:01.000Z"),
- },
- ],
- } as unknown as OrchestrationV2ThreadProjection;
- const layerTest = RuntimeRequestService.layer.pipe(
- Layer.provide(
- Layer.mergeAll(
- Layer.mock(ProjectionStore.ProjectionStoreV2)({
- getRuntimeRequest: (_threadId, requestId) =>
- Effect.succeed(projection.runtimeRequests.find((request) => request.id === requestId)),
- }),
- Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({
- get: getSession,
- }),
+ ],
+ } as unknown as OrchestrationV2ThreadProjection;
+ const layerTest = RuntimeRequestService.layer.pipe(
+ Layer.provide(
+ Layer.mergeAll(
+ Layer.mock(ProjectionStore.ProjectionStoreV2)({
+ getRuntimeRequest: (_threadId, requestId) =>
+ Effect.succeed(
+ projection.runtimeRequests.find((request) => request.id === requestId),
+ ),
+ }),
+ Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({
+ get: getSession,
+ }),
+ ),
),
- ),
- );
+ );
- return Effect.gen(function* () {
- const service = yield* RuntimeRequestService.RuntimeRequestServiceV2;
- const error = yield* service
- .respond({
+ return Effect.gen(function* () {
+ const service = yield* RuntimeRequestService.RuntimeRequestServiceV2;
+ const response = service.respond({
threadId,
providerSessionId,
requestId,
- decision: "accept",
- })
- .pipe(Effect.flip);
+ decision: "decline",
+ feedback: "Use an explicit path.",
+ });
+ if (status === "resolved") {
+ yield* response;
+ assert.deepEqual(respondToRuntimeRequest.mock.calls, [
+ [
+ {
+ requestId,
+ decision: "decline",
+ feedback: "Use an explicit path.",
+ },
+ ],
+ ]);
+ return;
+ }
+ const error = yield* response.pipe(Effect.flip);
- assert.equal(error.reason, "request-not-ready");
- assert.equal(
- error.message,
- `Runtime request ${requestId} on thread ${threadId} is not ready for response execution.`,
- );
- assert.isUndefined(error.cause);
- assert.equal(getSession.mock.calls.length, 0);
- assert.equal(respondToRuntimeRequest.mock.calls.length, 0);
- }).pipe(Effect.provide(layerTest));
-});
+ assert.equal(error.reason, "request-not-ready");
+ assert.equal(
+ error.message,
+ `Runtime request ${requestId} on thread ${threadId} is not ready for response execution.`,
+ );
+ assert.isUndefined(error.cause);
+ assert.equal(getSession.mock.calls.length, 0);
+ assert.equal(respondToRuntimeRequest.mock.calls.length, 0);
+ }).pipe(Effect.provide(layerTest));
+ },
+);
diff --git a/apps/server/src/orchestration-v2/RuntimeRequestService.ts b/apps/server/src/orchestration-v2/RuntimeRequestService.ts
index 9c96ea5d6b4..e58b7211ea3 100644
--- a/apps/server/src/orchestration-v2/RuntimeRequestService.ts
+++ b/apps/server/src/orchestration-v2/RuntimeRequestService.ts
@@ -54,6 +54,7 @@ export interface RuntimeRequestServiceV2Shape {
readonly providerSessionId: ProviderSessionId;
readonly requestId: RuntimeRequestId;
readonly decision?: ProviderApprovalDecision;
+ readonly feedback?: string;
readonly answers?: ProviderUserInputAnswers;
}) => Effect.Effect<void, RuntimeRequestResponseExecutionError>;
}
@@ -118,6 +119,7 @@ export const layer: Layer.Layer<
yield* session.value.respondToRuntimeRequest({
requestId: input.requestId,
...(input.decision === undefined ? {} : { decision: input.decision }),
+ ...(input.feedback === undefined ? {} : { feedback: input.feedback }),
...(input.answers === undefined ? {} : { answers: input.answers }),
});
},
diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx
index b74e691ddd1..162069163f9 100644
--- a/apps/web/src/components/chat/ChatComposer.tsx
+++ b/apps/web/src/components/chat/ChatComposer.tsx
@@ -3801,7 +3801,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
onPaste={onComposerPasteStable}
placeholder={
isComposerApprovalState
- ? "Send a message to decline and redirect the agent"
+ ? activePendingApproval?.supportsFeedback
+ ? "Send feedback to decline this request"
+ : "Send a message to decline and redirect the agent"
: activePendingProgress
? isChoiceOnlyPendingQuestion
? "Choose an option above"
diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts
index d3bcbdf4702..ed7def98c88 100644
--- a/apps/web/src/components/chat/useComposerSend.ts
+++ b/apps/web/src/components/chat/useComposerSend.ts
@@ -28,7 +28,10 @@ import {
} from "@t3tools/contracts";
import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
import { wasBootstrapThreadDeleted } from "@t3tools/client-runtime/errors";
-import { declinePendingApprovals } from "@t3tools/client-runtime/state/thread-requests";
+import {
+ declinePendingApprovals,
+ sendApprovalFeedback,
+} from "@t3tools/client-runtime/state/thread-requests";
import {
parseCodexFeedbackCommand,
submitCodexFeedback,
@@ -475,6 +478,10 @@ export function useComposerSend(input: ComposerSendInput) {
return;
}
const multipleModelSelections = sendCtx.multipleModelSelections;
+ const approvalFeedbackTarget = pendingApprovalsRef.current.find(
+ (approval) =>
+ approval.supportsFeedback && approval.requestId === sendCtx.shownPendingApprovalIds[0],
+ );
const multipleModelBlock =
multipleModelSelections === null
? null
@@ -945,7 +952,7 @@ export function useComposerSend(input: ComposerSendInput) {
sendCtx?.shownPendingApprovalIds.includes(approval.requestId),
)
: [];
- if (approvalsToDecline.length > 0) {
+ if (approvalsToDecline.length > 0 || approvalFeedbackTarget !== undefined) {
// A draft edited since send, or a paste still landing in it, is no longer the message
// the user sent.
const attachmentIdsAtSend = composerAttachmentsSnapshot.map((attachment) => attachment.id);
@@ -981,6 +988,42 @@ export function useComposerSend(input: ComposerSendInput) {
const approvalResponding = approvalsToDecline.some((approval) =>
respondingRequestIdsRef.current.includes(approval.requestId),
);
+ if (approvalFeedbackTarget !== undefined) {
+ if (composerAttachmentsSnapshot.length > 0 || outgoingMessageContext !== undefined) {
+ setThreadError(
+ threadIdForSend,
+ "Send approval feedback without attachments or added context.",
+ );
+ sendInFlightRef.current = false;
+ return;
+ }
+ if (
+ changedBeforeDecline ||
+ approvalResponding ||
+ currentRouteThreadKeyRef.current !== routeThreadKey
+ ) {
+ sendInFlightRef.current = false;
+ return;
+ }
+ const sent = await sendApprovalFeedback(
+ approvalFeedbackTarget,
+ messageTextForSend,
+ onRespondToApprovalStable,
+ ).catch(() => false);
+ sendInFlightRef.current = false;
+ if (
+ sent &&
+ !draftChangedSinceSend() &&
+ currentRouteThreadKeyRef.current === routeThreadKey &&
+ useComposerDraftStore.getState().getComposerDraft(composerDraftTarget) ===
+ draftBeforeDecline
+ ) {
+ promptRef.current = "";
+ clearComposerDraftContent(composerDraftTarget);
+ composerRef.current?.resetCursorState();
+ }
+ return;
+ }
const declined =
!changedBeforeDecline &&
!approvalResponding &&
diff --git a/apps/web/src/components/chat/usePendingThreadRequests.ts b/apps/web/src/components/chat/usePendingThreadRequests.ts
index 3b1e73e5938..0f29e61e503 100644
--- a/apps/web/src/components/chat/usePendingThreadRequests.ts
+++ b/apps/web/src/components/chat/usePendingThreadRequests.ts
@@ -300,6 +300,7 @@ export function usePendingThreadRequests(input: {
const onRespondToApproval = async (
requestId: RuntimeRequestId,
decision: ProviderApprovalDecision,
+ feedback?: string,
) => {
if (!activeThreadId || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope))
return;
@@ -318,6 +319,7 @@ export function usePendingThreadRequests(input: {
threadId: activeThreadId,
requestId,
decision,
+ ...(feedback === undefined ? {} : { feedback }),
},
});
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
diff --git a/docs/user/permission-modes.md b/docs/user/permission-modes.md
index 150c857db94..a15850973fb 100644
--- a/docs/user/permission-modes.md
+++ b/docs/user/permission-modes.md
@@ -37,6 +37,8 @@ by the permission mode. See [ACP Registry permissions](./providers-acp.md#permis
Claude can still ask in **Full access** when its settings disable bypass permissions or require
approval for an action.
+While a Claude approval is pending, type a text reply to decline that request and give feedback
+directly to the agent that asked, including a subagent. Other pending requests stay unanswered.
Antigravity can still send native approval requests in **Full access**. It only offers remembered
approvals for actions that support them.
diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts
index db343d2d0f8..8663b433d2c 100644
--- a/packages/client-runtime/src/operations/commands.ts
+++ b/packages/client-runtime/src/operations/commands.ts
@@ -185,6 +185,7 @@ export interface InterruptThreadTurnInput extends ThreadCommandInput {
export interface RespondToThreadApprovalInput extends ThreadCommandInput {
readonly requestId: RuntimeRequestId;
readonly decision: ProviderApprovalDecision;
+ readonly feedback?: string;
}
export interface RespondToThreadUserInputInput extends ThreadCommandInput {
@@ -873,6 +874,7 @@ export const respondToThreadApproval = Effect.fn("EnvironmentCommands.respondToT
threadId: input.threadId,
requestId: input.requestId,
decision: input.decision,
+ ...(input.feedback === undefined ? {} : { feedback: input.feedback }),
});
},
);
diff --git a/packages/client-runtime/src/state/threadRequests.test.ts b/packages/client-runtime/src/state/threadRequests.test.ts
index 1d3db9ce27d..b4a6447c2fc 100644
--- a/packages/client-runtime/src/state/threadRequests.test.ts
+++ b/packages/client-runtime/src/state/threadRequests.test.ts
@@ -13,6 +13,7 @@ import {
createQuestionHistoryProjector,
derivePendingThreadRequests,
declinePendingApprovals,
+ sendApprovalFeedback,
seedUserInputDraftAnswers,
type ApprovalResponder,
type ThreadPendingApproval,
@@ -72,6 +73,48 @@ describe("declining approvals before sending", () => {
).toBe(true);
expect(respond).not.toHaveBeenCalled();
});
+
+ it("sends feedback only to the displayed request, leaving other approvals pending", async () => {
+ const respond = vi.fn<ApprovalResponder>(async () => AsyncResult.success(undefined));
+ const pending = derivePendingThreadRequests({
+ runtimeRequests: [
+ {
+ ...projection.runtimeRequests[0]!,
+ kind: "command",
+ responseCapability: {
+ type: "live",
+ providerSessionId: ProviderSessionId.make("claude-session"),
+ supportsFeedback: true,
+ },
+ },
+ { ...projection.runtimeRequests[0]!, id: second.requestId, kind: "command" },
+ ],
+ turnItems: [],
+ });
+ expect(await sendApprovalFeedback(pending.approvals[0]!, " Safer please. ", respond)).toBe(
+ true,
+ );
+ expect(respond.mock.calls).toEqual([[approval.requestId, "decline", "Safer please."]]);
+ });
+
+ it("keeps feedback unsent when unsupported, stale, empty or rejected", async () => {
+ const respond = vi.fn<ApprovalResponder>(async () => AsyncResult.failure(Cause.fail("failed")));
+ expect(await sendApprovalFeedback(approval, "Safer please.", respond)).toBe(false);
+ expect(
+ await sendApprovalFeedback(
+ { ...approval, supportsFeedback: true, responseCapability: "not_resumable" },
+ "Safer please.",
+ respond,
+ ),
+ ).toBe(false);
+ expect(await sendApprovalFeedback({ ...approval, supportsFeedback: true }, " ", respond)).toBe(
+ false,
+ );
+ expect(respond).not.toHaveBeenCalled();
+ expect(
+ await sendApprovalFeedback({ ...approval, supportsFeedback: true }, "Safer please.", respond),
+ ).toBe(false);
+ });
});
describe("initial user input drafts", () => {
diff --git a/packages/client-runtime/src/state/threadRequests.ts b/packages/client-runtime/src/state/threadRequests.ts
index 5a9289fe396..e14f5471571 100644
--- a/packages/client-runtime/src/state/threadRequests.ts
+++ b/packages/client-runtime/src/state/threadRequests.ts
@@ -15,8 +15,20 @@ import type { ThreadStructure, ThreadStructureVisibleTurnItem } from "./models.t
export type ApprovalResponder = (
requestId: RuntimeRequestId,
decision: ProviderApprovalDecision,
+ feedback?: string,
) => Promise<AtomCommandResult<unknown, unknown> | undefined>;
+/** Feedback belongs to the displayed request, which may be a native child's tool call. */
+export async function sendApprovalFeedback(
+ approval: ThreadPendingApproval,
+ feedback: string,
+ respond: ApprovalResponder,
+): Promise<boolean> {
+ if (!approval.supportsFeedback || approval.responseCapability !== "live" || !feedback.trim())
+ return false;
+ return (await respond(approval.requestId, "decline", feedback.trim()))?._tag === "Success";
+}
+
/** Declines every approval a redirect replaces; any one still pending would block the agent. */
export async function declinePendingApprovals(
approvals: ReadonlyArray<ThreadPendingApproval>,
@@ -40,6 +52,7 @@ export interface ThreadPendingApproval {
readonly appName?: string;
readonly options?: ReadonlyArray<ProviderApprovalOption>;
readonly responseCapability: "live" | "not_resumable";
+ readonly supportsFeedback?: boolean;
}
export const FULL_ACCESS_OVERRIDE_QUESTION = "Why am I being asked this?";
@@ -142,6 +155,9 @@ export function derivePendingThreadRequests(
? { options: item.options }
: {}),
responseCapability: responseCapability === "live" ? "live" : "not_resumable",
+ ...(request.responseCapability.type === "live" && request.responseCapability.supportsFeedback
+ ? { supportsFeedback: true }
+ : {}),
});
}
diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts
index 881a316f59a..cb748cc5005 100644
--- a/packages/contracts/src/orchestrationV2.ts
+++ b/packages/contracts/src/orchestrationV2.ts
@@ -1020,13 +1020,18 @@ export const OrchestrationV2RuntimeRequest = Schema.Struct({
]),
status: Schema.Literals(["pending", "resolved", "expired", "cancelled"]),
responseCapability: Schema.Union([
- Schema.Struct({ type: Schema.Literal("live"), providerSessionId: ProviderSessionId }),
+ Schema.Struct({
+ type: Schema.Literal("live"),
+ providerSessionId: ProviderSessionId,
+ supportsFeedback: Schema.optional(Schema.Boolean),
+ }),
Schema.Struct({ type: Schema.Literal("message") }),
Schema.Struct({ type: Schema.Literal("not_resumable"), reason: Schema.String }),
]),
createdAt: Schema.DateTimeUtc,
resolvedAt: Schema.NullOr(Schema.DateTimeUtc),
decision: Schema.optional(ProviderApprovalDecision),
+ feedback: Schema.optional(Schema.String),
answers: Schema.optional(ProviderUserInputAnswers),
});
export type OrchestrationV2RuntimeRequest = typeof OrchestrationV2RuntimeRequest.Type;
@@ -2921,6 +2926,7 @@ export const OrchestrationV2Command = Schema.Union([
threadId: ThreadId,
requestId: RuntimeRequestId,
decision: Schema.optional(ProviderApprovalDecision),
+ feedback: Schema.optional(Schema.String),
answers: Schema.optional(ProviderUserInputAnswers),
attachmentsByQuestionId: Schema.optional(UserInputAttachments),
}),
diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts
index db5a18f77b4..314705eca3a 100644
--- a/packages/provider-core/src/server/ProviderAdapter.ts
+++ b/packages/provider-core/src/server/ProviderAdapter.ts
@@ -455,6 +455,7 @@ export interface ProviderAdapterV2InterruptInput {
export interface ProviderAdapterV2RuntimeRequestResponseInput {
readonly requestId: RuntimeRequestId;
readonly decision?: ProviderApprovalDecision;
+ readonly feedback?: string;
readonly answers?: ProviderUserInputAnswers;
readonly response?: unknown;
}