@devries-cameron20 / t3code Mirror · read-only / commits / b7e802bdec
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 19:30 UTC

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

Yash Singh committed Oct 23, 2026 at 00:32 UTC b7e802bdec917c948b6b4302676e2266ec01bc1d
21 files changed +596 -92
apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+41 -13
@@ -55,6 +55,7 @@ import {
55 } from "@t3tools/shared/codexArtifactTemplates";
56 import {
57 declinePendingApprovals,
58 + sendApprovalFeedback,
59 type ApprovalResponder,
60 type ThreadUserInputQuestion,
61 } from "@t3tools/client-runtime/state/thread-requests";
@@ -258,7 +259,10 @@ export interface ThreadDetailScreenProps {
259 readonly onResumeQueue: (() => Promise<void>) | null;
260 readonly onSendMessage: (
261 followUp?: ActiveTurnComposerAction,
261 - beforeDispatch?: () => Promise<boolean>,
262 + beforeDispatch?: (
263 + text: string,
264 + hasAttachmentsOrContext: boolean,
265 + ) => Promise<boolean | "responded">,
266 ) => Promise<MessageId | null>;
267 readonly onReconnectEnvironment: () => void;
268 readonly canSwitchThreadProvider: boolean;
@@ -1199,18 +1203,40 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
1203 const approvalsToDecline = props.activePendingApprovals;
1204 const declineBeforeDispatch =
1205 approvalsToDecline.length > 0 && props.activePendingUserInput === null
1202 - ? async () =>
1203 - props.respondingApprovalId === null &&
1204 - (await declinePendingApprovals(approvalsToDecline, props.onRespondToApproval)) &&
1205 - selectedThreadKeyRef.current === targetThreadKey &&
1206 - // A draft edited or pasted into during the decline isn't what the user sent.
1207 - stillSendable?.() !== false &&
1208 - // An approval that arrived during the decline would block the redirect; the draft
1209 - // stays so the next send declines it too.
1210 - !activePendingApprovalsRef.current.some(
1211 - (approval) =>
1212 - !approvalsToDecline.some((declined) => declined.requestId === approval.requestId),
1206 + ? async (text: string, hasAttachmentsOrContext: boolean) => {
1207 + if (
1208 + selectedThreadKeyRef.current !== targetThreadKey ||
1209 + stillSendable?.() === false ||
1210 + props.respondingApprovalId !== null
1211 )
1212 + return false;
1213 + const feedbackTarget = approvalsToDecline[0];
1214 + if (feedbackTarget?.supportsFeedback) {
1215 + if (hasAttachmentsOrContext) {
1216 + Dialog.alert(
1217 + "Approval feedback",
1218 + "Send approval feedback without attachments or added context.",
1219 + );
1220 + return false;
1221 + }
1222 + return (await sendApprovalFeedback(feedbackTarget, text, props.onRespondToApproval))
1223 + ? ("responded" as const)
1224 + : false;
1225 + }
1226 + return (
1227 + props.respondingApprovalId === null &&
1228 + (await declinePendingApprovals(approvalsToDecline, props.onRespondToApproval)) &&
1229 + selectedThreadKeyRef.current === targetThreadKey &&
1230 + // A draft edited or pasted into during the decline isn't what the user sent.
1231 + stillSendable?.() !== false &&
1232 + // An approval that arrived during the decline would block the redirect; the draft
1233 + // stays so the next send declines it too.
1234 + !activePendingApprovalsRef.current.some(
1235 + (approval) =>
1236 + !approvalsToDecline.some((declined) => declined.requestId === approval.requestId),
1237 + )
1238 + );
1239 + }
1240 : undefined;
1241 const messageId = await props.onSendMessage(followUp, declineBeforeDispatch);
1242 if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
@@ -1642,7 +1668,9 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
1668 editorRef={composerEditorRef}
1669 placeholder={
1670 props.activePendingApproval
1645 - ? "Send a message to decline and redirect the agent"
1671 + ? props.activePendingApproval.supportsFeedback
1672 + ? "Send feedback to decline this request"
1673 + : "Send a message to decline and redirect the agent"
1674 : "Ask the repo agent, or run a command…"
1675 }
1676 contentMaxWidth={contentMaxWidth}
apps/mobile/src/state/thread-task-permissions.test.ts
+38
@@ -18,6 +18,7 @@ import {
18 } from "../../../../packages/client-runtime/src/state/orchestrationV2TestFixtures";
19 import type { DraftComposerImageAttachment } from "../lib/composerImages";
20 import type { PendingThreadRequests } from "@t3tools/client-runtime/state/thread-requests";
21 +import { sendApprovalFeedback } from "@t3tools/client-runtime/state/thread-requests";
22 import { AsyncResult, type Atom } from "effect/reactivity";
23 import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
24
@@ -202,6 +203,43 @@ beforeEach(() => {
203 });
204
205 describe("mobile task permissions", () => {
206 + it("consumes an approval reply without queueing a parent message", async () => {
207 + state.grantedEnvironments.add("secondary");
208 + const composer = useThreadComposerState();
209 + const requests = useSelectedThreadRequests();
210 + const approval = { ...state.pendingRequests.approvals[0]!, supportsFeedback: true };
211 + const messageId = await composer.onSendMessage(undefined, async (text) =>
212 + (await sendApprovalFeedback(approval, text, requests.onRespondToApproval))
213 + ? "responded"
214 + : false,
215 + );
216 + expect(messageId).toBeNull();
217 + expect(state.approve).toHaveBeenCalledWith({
218 + environmentId: "secondary",
219 + input: {
220 + threadId: "thread",
221 + requestId: "approval",
222 + decision: "decline",
223 + feedback: "Keep my draft",
224 + },
225 + });
226 + expect(state.enqueue).not.toHaveBeenCalled();
227 + expect(state.clearDraft).toHaveBeenCalledOnce();
228 + });
229 +
230 + it("preserves a draft changed during an approval reply and never sends it to the parent", async () => {
231 + state.grantedEnvironments.add("secondary");
232 + const composer = useThreadComposerState();
233 + const beforeDispatch = async () => {
234 + state.draft = { ...state.draft, text: "New feedback" };
235 + return "responded" as const;
236 + };
237 + expect(await composer.onSendMessage(undefined, beforeDispatch)).toBeNull();
238 + expect(state.enqueue).not.toHaveBeenCalled();
239 + expect(state.clearDraft).not.toHaveBeenCalled();
240 + expect(state.draft.text).toBe("New feedback");
241 + });
242 +
243 it("keeps a connected read-only task's draft instead of queueing it with another environment's grant", async () => {
244 const composer = useThreadComposerState();
245 expect(await composer.onSendMessage()).toBeNull();
apps/mobile/src/state/use-selected-thread-requests.ts
+2 -1
@@ -236,7 +236,7 @@ export function useSelectedThreadRequests() {
236 );
237
238 const onRespondToApproval = useCallback(
239 - async (requestId: RuntimeRequestId, decision: ProviderApprovalDecision) => {
239 + async (requestId: RuntimeRequestId, decision: ProviderApprovalDecision, feedback?: string) => {
240 if (
241 !selectedThreadShell ||
242 !readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope)
@@ -257,6 +257,7 @@ export function useSelectedThreadRequests() {
257 threadId: selectedThreadShell.id,
258 requestId,
259 decision,
260 + ...(feedback === undefined ? {} : { feedback }),
261 },
262 });
263 setRespondingApprovalId((current) => (current === requestId ? null : current));
apps/mobile/src/state/use-thread-composer-state.ts
+13 -2
@@ -526,7 +526,10 @@ export function useThreadComposerState() {
526
527 const onSendMessage = async (
528 followUpOverride?: ActiveTurnComposerAction,
529 - beforeDispatch?: () => Promise<boolean>,
529 + beforeDispatch?: (
530 + text: string,
531 + hasAttachmentsOrContext: boolean,
532 + ) => Promise<boolean | "responded">,
533 ) => {
534 if (
535 selectedThreadShell &&
@@ -645,7 +648,11 @@ export function useThreadComposerState() {
648 }
649
650 if (beforeDispatch !== undefined) {
648 - if (!(await beforeDispatch())) return null;
651 + const response = await beforeDispatch(
652 + text,
653 + attachments.length > 0 || draft.context !== undefined,
654 + );
655 + if (!response) return null;
656 // A context paste still landing, or any draft or settings change while approvals were
657 // declined, means this snapshot is no longer what the user sent.
658 if (appAtomRegistry.get(composerContextImportsAtom)[threadKey]) return null;
@@ -660,6 +667,10 @@ export function useThreadComposerState() {
667 current.attachments.some((attachment, index) => attachment.id !== attachments[index]?.id)
668 )
669 return null;
670 + if (response === "responded") {
671 + clearComposerDraftContent(threadKey);
672 + return null;
673 + }
674 }
675
676 // Resolved here rather than at drain time: the outbox can deliver minutes
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+63 -3
@@ -967,7 +967,10 @@ describe("ClaudeAdapterV2 append-system-prompt-file launch argument", () => {
967 describe("ClaudeAdapterV2 approval cancellation", () => {
968 it.effect("observes an approval signal that was already aborted", () =>
969 Effect.gen(function* () {
970 - const decision = yield* Deferred.make<ProviderApprovalDecision>();
970 + const decision = yield* Deferred.make<{
971 + decision: ProviderApprovalDecision;
972 + feedback?: string;
973 + }>();
974 const controller = new AbortController();
975 controller.abort();
976
@@ -976,7 +979,7 @@ describe("ClaudeAdapterV2 approval cancellation", () => {
979 controller.signal,
980 );
981
979 - assert.equal(result, "cancel");
982 + assert.deepEqual(result, { decision: "cancel" });
983 }),
984 );
985 });
@@ -2873,12 +2876,14 @@ describe("ClaudeAdapterV2 background wake turns", () => {
2876 turn: Effect.Success<ReturnType<typeof openPlanTurn>>,
2877 toolName: string,
2878 toolInput: Record<string, unknown>,
2879 + options?: { toolUseID: string; agentID?: string },
2880 ) {
2881 const decision = yield* Effect.promise(() =>
2882 turn.canUseTool(toolName, toolInput, {
2883 signal: new AbortController().signal,
2880 - toolUseID: "tool-plan-write",
2884 + toolUseID: options?.toolUseID ?? "tool-plan-write",
2885 requestId: "request-plan-write",
2886 + ...(options?.agentID === undefined ? {} : { agentID: options.agentID }),
2887 }),
2888 ).pipe(Effect.forkScoped);
2889 const first = yield* Effect.raceFirst(
@@ -2954,6 +2959,61 @@ describe("ClaudeAdapterV2 background wake turns", () => {
2959 ),
2960 );
2961
2962 + it.effect(
2963 + "returns approval feedback to the requesting tool without sending a parent prompt",
2964 + () =>
2965 + Effect.gen(function* () {
2966 + const turn = yield* openPlanTurn("full-access");
2967 + const parentPermission = yield* requestWrite(
2968 + turn,
2969 + "Bash",
2970 + { command: "git status" },
2971 + { toolUseID: "parent-command" },
2972 + );
2973 + assert.equal(parentPermission.first.type, "request");
2974 + if (parentPermission.first.type !== "request") return;
2975 + const permission = yield* requestWrite(
2976 + turn,
2977 + "Bash",
2978 + { command: "rm -f $W/*/*.obj" },
2979 + { toolUseID: "child-command", agentID: "child-worker" },
2980 + );
2981 + assert.equal(permission.first.type, "request");
2982 + if (permission.first.type !== "request") return;
2983 + const request = permission.first.event.runtimeRequest;
2984 + assert.equal(request.responseCapability.type, "live");
2985 + assert.isTrue(
2986 + request.responseCapability.type === "live" &&
2987 + request.responseCapability.supportsFeedback,
2988 + );
2989 + yield* turn.runtime.respondToRuntimeRequest({
2990 + requestId: request.id,
2991 + decision: "decline",
2992 + feedback: "Run it in a safer manner.",
2993 + });
2994 + const result = yield* Fiber.join(permission.decision);
2995 + assert.equal(result?.behavior, "deny");
2996 + if (result?.behavior === "deny") {
2997 + assert.include(result.message, "Run it in a safer manner.");
2998 + assert.notProperty(result, "interrupt");
2999 + }
3000 + assert.equal(turn.offeredMessages.length, 1);
3001 + yield* turn.runtime.respondToRuntimeRequest({
3002 + requestId: parentPermission.first.event.runtimeRequest.id,
3003 + decision: "accept",
3004 + });
3005 + const parentResult = yield* Fiber.join(parentPermission.decision);
3006 + assert.equal(parentResult?.behavior, "allow");
3007 + if (parentResult?.behavior === "allow")
3008 + assert.equal(parentResult.toolUseID, "parent-command");
3009 + }).pipe(
3010 + Effect.scoped,
3011 + Effect.provide(
3012 + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
3013 + ),
3014 + ),
3015 + );
3016 +
3017 it.effect("still captures ExitPlanMode when Plan approvals are never allowed", () =>
3018 Effect.gen(function* () {
3019 const turn = yield* openPlanTurn("full-access", "never");
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+20 -9
@@ -2892,6 +2892,7 @@ export function permissionResultFromDecision(input: {
2892 readonly toolInput: Record<string, unknown>;
2893 readonly toolUseID: string;
2894 readonly suggestions?: Parameters<CanUseTool>[2]["suggestions"];
2895 + readonly feedback?: string;
2896 }): PermissionResult {
2897 if (input.decision === "accept" || input.decision === "acceptForSession") {
2898 return {
@@ -2911,9 +2912,10 @@ export function permissionResultFromDecision(input: {
2912 return {
2913 behavior: "deny",
2914 message:
2914 - input.decision === "cancel"
2915 + input.feedback?.trim() ||
2916 + (input.decision === "cancel"
2917 ? "User cancelled tool execution."
2916 - : "User declined tool execution.",
2918 + : "User declined tool execution."),
2919 toolUseID: input.toolUseID,
2920 decisionClassification: "user_reject",
2921 ...(input.decision === "cancel" ? { interrupt: true } : {}),
@@ -2942,11 +2944,11 @@ function toSessionPermissionUpdates(
2944 }
2945
2946 export const awaitClaudeApprovalDecision = Effect.fn("awaitClaudeApprovalDecision")(function* (
2945 - decision: Deferred.Deferred<ProviderApprovalDecision>,
2947 + decision: Deferred.Deferred<ClaudeApprovalResponse>,
2948 signal: AbortSignal,
2949 ) {
2948 - const cancellation = Effect.callback<ProviderApprovalDecision>((resume) => {
2949 - const abort = () => resume(Effect.succeed("cancel"));
2950 + const cancellation = Effect.callback<ClaudeApprovalResponse>((resume) => {
2951 + const abort = () => resume(Effect.succeed({ decision: "cancel" }));
2952 signal.addEventListener("abort", abort, { once: true });
2953 if (signal.aborted) {
2954 abort();
@@ -3625,12 +3627,17 @@ function rememberClaudeSubagentLaunch(
3627 }
3628 }
3629
3630 +type ClaudeApprovalResponse = {
3631 + readonly decision: ProviderApprovalDecision;
3632 + readonly feedback?: string;
3633 +};
3634 +
3635 type PendingClaudeRuntimeRequest =
3636 | {
3637 readonly type: "approval";
3638 readonly requestId: OrchestrationV2RuntimeRequest["id"];
3639 readonly requestKind: ProviderRequestKind;
3633 - readonly decision: Deferred.Deferred<ProviderApprovalDecision, never>;
3640 + readonly decision: Deferred.Deferred<ClaudeApprovalResponse, never>;
3641 }
3642 | {
3643 readonly type: "user_input";
@@ -6467,6 +6474,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
6474 responseCapability: {
6475 type: "live",
6476 providerSessionId,
6477 + ...(input.questions === undefined ? { supportsFeedback: true } : {}),
6478 },
6479 createdAt,
6480 resolvedAt: null,
@@ -8986,7 +8994,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
8994 callbackOptions,
8995 }),
8996 });
8989 - const decision = yield* Deferred.make<ProviderApprovalDecision, never>();
8997 + const decision = yield* Deferred.make<ClaudeApprovalResponse, never>();
8998 yield* Ref.update(pendingRuntimeRequests, (current) => {
8999 const updated = new Map(current);
9000 updated.set(String(artifacts.request.id), {
@@ -9033,7 +9041,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
9041
9042 return permissionResultFromDecision({
9043 toolName,
9036 - decision: resolvedDecision,
9044 + ...resolvedDecision,
9045 toolInput,
9046 toolUseID: callbackOptions.toolUseID,
9047 ...(callbackOptions.suggestions === undefined
@@ -10283,7 +10291,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
10291 }),
10292 });
10293 }
10286 - yield* Deferred.succeed(pending.decision, requestInput.decision);
10294 + yield* Deferred.succeed(pending.decision, {
10295 + decision: requestInput.decision,
10296 + ...(requestInput.feedback === undefined ? {} : { feedback: requestInput.feedback }),
10297 + });
10298 },
10299 (effect, requestInput) =>
10300 effect.pipe(
apps/server/src/orchestration-v2/EffectOutbox.ts
+1
@@ -80,6 +80,7 @@ export const OrchestrationEffectRequestV2 = Schema.Union([
80 providerSessionId: ProviderSessionId,
81 requestId: RuntimeRequestId,
82 decision: Schema.optional(ProviderApprovalDecision),
83 + feedback: Schema.optional(Schema.String),
84 answers: Schema.optional(ProviderUserInputAnswers),
85 }),
86 Schema.Struct({
apps/server/src/orchestration-v2/EffectWorker.ts
+3
@@ -384,6 +384,9 @@ export const layerExecutor: Layer.Layer<
384 ...(effect.request.decision === undefined
385 ? {}
386 : { decision: effect.request.decision }),
387 + ...(effect.request.feedback === undefined
388 + ? {}
389 + : { feedback: effect.request.feedback }),
390 ...(effect.request.answers === undefined
391 ? {}
392 : { answers: effect.request.answers }),
apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts
+136
@@ -57,6 +57,142 @@ const layerTest = Layer.mergeAll(
57 ),
58 );
59
60 +it.effect(
61 + "records approval feedback and targets only its runtime request without dispatching a parent turn",
62 + () =>
63 + Effect.gen(function* () {
64 + const orchestrator = yield* Orchestrator.OrchestratorV2;
65 + const projections = yield* ProjectionStore.ProjectionStoreV2;
66 + const outbox = yield* EffectOutbox.EffectOutboxV2;
67 + const threadId = ThreadId.make("thread:approval-feedback");
68 + const sessionId = ProviderSessionId.make("session:approval-feedback");
69 + const now = yield* DateTime.now;
70 + yield* orchestrator.dispatch({
71 + type: "thread.create",
72 + commandId: CommandId.make("create-approval-feedback"),
73 + threadId,
74 + projectId: ProjectId.make("project:approval-feedback"),
75 + title: "Parent",
76 + modelSelection,
77 + runtimeMode: "full-access",
78 + interactionMode: "default",
79 + branch: null,
80 + worktreePath: null,
81 + createdBy: "user",
82 + creationSource: "web",
83 + });
84 + yield* projections.apply({
85 + id: EventId.make("session:approval-feedback"),
86 + type: "provider-session.attached",
87 + threadId,
88 + occurredAt: now,
89 + payload: {
90 + id: sessionId,
91 + driver: adapter.driver,
92 + providerInstanceId: instanceId,
93 + status: "ready",
94 + cwd: "/repo",
95 + model: modelSelection.model,
96 + capabilities: CodexProviderCapabilitiesV2,
97 + createdAt: now,
98 + updatedAt: now,
99 + lastError: null,
100 + },
101 + });
102 + for (const name of ["child", "other"]) {
103 + yield* projections.apply({
104 + id: EventId.make(`request:${name}`),
105 + type: "runtime-request.updated",
106 + threadId,
107 + occurredAt: now,
108 + payload: {
109 + id: RuntimeRequestId.make(name),
110 + nodeId: NodeId.make(`node:${name}`),
111 + providerTurnId: null,
112 + nativeRequestRef: null,
113 + kind: "command",
114 + status: "pending",
115 + responseCapability: {
116 + type: "live",
117 + providerSessionId: sessionId,
118 + supportsFeedback: name === "child",
119 + },
120 + createdAt: now,
121 + resolvedAt: null,
122 + },
123 + });
124 + }
125 + const commandId = CommandId.make("respond:approval-feedback");
126 + const feedback = "Run it in a safer manner.";
127 + for (const [index, invalid] of [
128 + { requestId: RuntimeRequestId.make("other"), decision: "decline" as const, feedback },
129 + { requestId: RuntimeRequestId.make("child"), decision: "accept" as const, feedback },
130 + { requestId: RuntimeRequestId.make("child"), decision: "decline" as const, feedback: " " },
131 + ].entries()) {
132 + const rejectedId = CommandId.make(`invalid-feedback:${index}`);
133 + const rejected = yield* orchestrator
134 + .dispatch({
135 + type: "runtime-request.respond",
136 + commandId: rejectedId,
137 + threadId,
138 + ...invalid,
139 + })
140 + .pipe(Effect.result);
141 + assert.isTrue(Result.isFailure(rejected));
142 + assert.deepEqual(yield* outbox.listByCommandId(rejectedId), []);
143 + }
144 + yield* orchestrator.dispatch({
145 + type: "runtime-request.respond",
146 + commandId,
147 + threadId,
148 + requestId: RuntimeRequestId.make("child"),
149 + decision: "decline",
150 + feedback,
151 + });
152 + const projection = yield* projections.getThreadProjection(threadId);
153 + assert.equal(
154 + projection.runtimeRequests.find((request) => request.id === "child")?.feedback,
155 + feedback,
156 + );
157 + assert.equal(
158 + projection.runtimeRequests.find((request) => request.id === "other")?.status,
159 + "pending",
160 + );
161 + assert.equal(projection.messages.at(-1)?.text, feedback);
162 + const feedbackMessageId = MessageId.make("approval-feedback:child");
163 + assert.ok(
164 + projection.visibleTurnItems.some(
165 + ({ item }) =>
166 + item.type === "user_message" &&
167 + item.messageId === feedbackMessageId &&
168 + item.text === feedback,
169 + ),
170 + );
171 + const history = yield* projections.getTimelinePage(threadId, { limit: 20, view: "messages" });
172 + assert.ok(
173 + history.items.some(
174 + ({ item }) =>
175 + item.type === "user_message" &&
176 + item.messageId === feedbackMessageId &&
177 + item.text === feedback,
178 + ),
179 + );
180 + assert.equal(projection.runs.length, 0);
181 + assert.deepEqual(
182 + (yield* outbox.listByCommandId(commandId)).map((effect) => effect.request),
183 + [
184 + {
185 + type: "runtime-request.respond",
186 + providerSessionId: sessionId,
187 + requestId: RuntimeRequestId.make("child"),
188 + decision: "decline",
189 + feedback,
190 + },
191 + ],
192 + );
193 + }).pipe(Effect.provide(layerTest)),
194 +);
195 +
196 it.effect("marks a never-visited thread's first completion unread", () =>
197 Effect.gen(function* () {
198 const orchestrator = yield* Orchestrator.OrchestratorV2;
apps/server/src/orchestration-v2/Orchestrator.ts
+78
@@ -7673,6 +7673,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
7673 cause: runtimeRequest.responseCapability.reason,
7674 });
7675 }
7676 + if (
7677 + command.feedback !== undefined &&
7678 + (runtimeRequest.responseCapability.type !== "live" ||
7679 + !runtimeRequest.responseCapability.supportsFeedback ||
7680 + runtimeRequest.kind === "user_input" ||
7681 + command.decision !== "decline" ||
7682 + !command.feedback.trim())
7683 + ) {
7684 + return yield* new OrchestratorDispatchError({
7685 + commandId: command.commandId,
7686 + commandType: command.type,
7687 + cause: "Feedback requires a live approval that supports it and a decline decision.",
7688 + });
7689 + }
7690 const providerSessionId =
7691 runtimeRequest.responseCapability.type === "live"
7692 ? runtimeRequest.responseCapability.providerSessionId
@@ -7702,10 +7716,73 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
7716 status: "resolved" as const,
7717 resolvedAt: now,
7718 ...(command.decision === undefined ? {} : { decision: command.decision }),
7719 + ...(command.feedback === undefined ? {} : { feedback: command.feedback }),
7720 ...(answers === undefined ? {} : { answers }),
7721 };
7722 const emitEvent = emit(events, command);
7723 const requestNode = context.node;
7724 + if (command.feedback !== undefined) {
7725 + const messageId = MessageId.make(`approval-feedback:${command.requestId}`);
7726 + // Record the reply for every client without dispatching a prompt to the parent agent.
7727 + yield* emitEvent({
7728 + type: "message.updated",
7729 + threadId: command.threadId,
7730 + ...(requestNode?.runId == null ? {} : { runId: requestNode.runId }),
7731 + nodeId: runtimeRequest.nodeId,
7732 + occurredAt: now,
7733 + payload: {
7734 + id: messageId,
7735 + threadId: command.threadId,
7736 + runId: requestNode?.runId ?? null,
7737 + nodeId: runtimeRequest.nodeId,
7738 + role: "user",
7739 + text: command.feedback,
7740 + attachments: [],
7741 + streaming: false,
7742 + createdBy: "user",
7743 + creationSource: "server",
7744 + createdAt: now,
7745 + updatedAt: now,
7746 + },
7747 + });
7748 + yield* emitEvent({
7749 + type: "turn-item.updated",
7750 + threadId: command.threadId,
7751 + ...(requestNode?.runId == null ? {} : { runId: requestNode.runId }),
7752 + nodeId: runtimeRequest.nodeId,
7753 + occurredAt: now,
7754 + payload: {
7755 + id: idAllocator.derive.userTurnItem({ messageId }),
7756 + threadId: command.threadId,
7757 + runId: requestNode?.runId ?? null,
7758 + nodeId: runtimeRequest.nodeId,
7759 + providerThreadId:
7760 + context.item?.providerThreadId ?? requestNode?.providerThreadId ?? null,
7761 + providerTurnId: runtimeRequest.providerTurnId,
7762 + nativeItemRef: null,
7763 + parentItemId: null,
7764 + ordinal: yield* projectionStore
7765 + .getNextTurnItemOrdinal(command.threadId)
7766 + .pipe(
7767 + Effect.mapError(
7768 + (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }),
7769 + ),
7770 + ),
7771 + status: "completed",
7772 + title: null,
7773 + startedAt: now,
7774 + completedAt: now,
7775 + updatedAt: now,
7776 + type: "user_message",
7777 + messageId,
7778 + inputIntent: "steer",
7779 + text: command.feedback,
7780 + attachments: [],
7781 + createdBy: "user",
7782 + creationSource: "server",
7783 + },
7784 + });
7785 + }
7786 const resolvedNodeStatus =
7787 command.decision === "decline" || command.decision === "cancel"
7788 ? ("cancelled" as const)
@@ -7872,6 +7949,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
7949 providerSessionId,
7950 requestId: command.requestId,
7951 ...(command.decision === undefined ? {} : { decision: command.decision }),
7952 + ...(command.feedback === undefined ? {} : { feedback: command.feedback }),
7953 ...(answers === undefined ? {} : { answers }),
7954 },
7955 } satisfies PendingOrchestrationEffectV2,
apps/server/src/orchestration-v2/RuntimeRequestService.test.ts
+78 -60
@@ -16,70 +16,88 @@ import * as ProjectionStore from "./ProjectionStore.ts";
16 import * as ProviderSessionManager from "./ProviderSessionManager.ts";
17 import * as RuntimeRequestService from "./RuntimeRequestService.ts";
18
19 -it.effect("rejects expired runtime requests before invoking the live adapter", () => {
20 - const threadId = ThreadId.make("thread-runtime-request-expired");
21 - const providerSessionId = ProviderSessionId.make("provider-session-runtime-request-expired");
22 - const requestId = RuntimeRequestId.make("request-expired");
23 - const respondToRuntimeRequest = vi.fn(
24 - (_input: ProviderAdapter.ProviderAdapterV2RuntimeRequestResponseInput) => Effect.void,
25 - );
26 - const getSession = vi.fn(() =>
27 - Effect.succeed(
28 - Option.some({
29 - respondToRuntimeRequest,
30 - } as never),
31 - ),
32 - );
33 - const projection = {
34 - runtimeRequests: [
35 - {
36 - id: requestId,
37 - nodeId: NodeId.make("node-runtime-request-expired"),
38 - providerTurnId: null,
39 - nativeRequestRef: null,
40 - kind: "command",
41 - status: "expired",
42 - responseCapability: {
43 - type: "live",
44 - providerSessionId,
19 +it.effect.each(["expired", "resolved"] as const)(
20 + "responds only to resolved requests and preserves feedback (%s)",
21 + (status) => {
22 + const threadId = ThreadId.make("thread-runtime-request-expired");
23 + const providerSessionId = ProviderSessionId.make("provider-session-runtime-request-expired");
24 + const requestId = RuntimeRequestId.make("request-expired");
25 + const respondToRuntimeRequest = vi.fn(
26 + (_input: ProviderAdapter.ProviderAdapterV2RuntimeRequestResponseInput) => Effect.void,
27 + );
28 + const getSession = vi.fn(() =>
29 + Effect.succeed(
30 + Option.some({
31 + respondToRuntimeRequest,
32 + } as never),
33 + ),
34 + );
35 + const projection = {
36 + runtimeRequests: [
37 + {
38 + id: requestId,
39 + nodeId: NodeId.make("node-runtime-request-expired"),
40 + providerTurnId: null,
41 + nativeRequestRef: null,
42 + kind: "command",
43 + status,
44 + responseCapability: {
45 + type: "live",
46 + providerSessionId,
47 + },
48 + createdAt: DateTime.makeUnsafe("2026-07-29T00:00:00.000Z"),
49 + resolvedAt: DateTime.makeUnsafe("2026-07-29T00:00:01.000Z"),
50 },
46 - createdAt: DateTime.makeUnsafe("2026-07-29T00:00:00.000Z"),
47 - resolvedAt: DateTime.makeUnsafe("2026-07-29T00:00:01.000Z"),
48 - },
49 - ],
50 - } as unknown as OrchestrationV2ThreadProjection;
51 - const layerTest = RuntimeRequestService.layer.pipe(
52 - Layer.provide(
53 - Layer.mergeAll(
54 - Layer.mock(ProjectionStore.ProjectionStoreV2)({
55 - getRuntimeRequest: (_threadId, requestId) =>
56 - Effect.succeed(projection.runtimeRequests.find((request) => request.id === requestId)),
57 - }),
58 - Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({
59 - get: getSession,
60 - }),
51 + ],
52 + } as unknown as OrchestrationV2ThreadProjection;
53 + const layerTest = RuntimeRequestService.layer.pipe(
54 + Layer.provide(
55 + Layer.mergeAll(
56 + Layer.mock(ProjectionStore.ProjectionStoreV2)({
57 + getRuntimeRequest: (_threadId, requestId) =>
58 + Effect.succeed(
59 + projection.runtimeRequests.find((request) => request.id === requestId),
60 + ),
61 + }),
62 + Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({
63 + get: getSession,
64 + }),
65 + ),
66 ),
62 - ),
63 - );
67 + );
68
65 - return Effect.gen(function* () {
66 - const service = yield* RuntimeRequestService.RuntimeRequestServiceV2;
67 - const error = yield* service
68 - .respond({
69 + return Effect.gen(function* () {
70 + const service = yield* RuntimeRequestService.RuntimeRequestServiceV2;
71 + const response = service.respond({
72 threadId,
73 providerSessionId,
74 requestId,
72 - decision: "accept",
73 - })
74 - .pipe(Effect.flip);
75 + decision: "decline",
76 + feedback: "Use an explicit path.",
77 + });
78 + if (status === "resolved") {
79 + yield* response;
80 + assert.deepEqual(respondToRuntimeRequest.mock.calls, [
81 + [
82 + {
83 + requestId,
84 + decision: "decline",
85 + feedback: "Use an explicit path.",
86 + },
87 + ],
88 + ]);
89 + return;
90 + }
91 + const error = yield* response.pipe(Effect.flip);
92
76 - assert.equal(error.reason, "request-not-ready");
77 - assert.equal(
78 - error.message,
79 - `Runtime request ${requestId} on thread ${threadId} is not ready for response execution.`,
80 - );
81 - assert.isUndefined(error.cause);
82 - assert.equal(getSession.mock.calls.length, 0);
83 - assert.equal(respondToRuntimeRequest.mock.calls.length, 0);
84 - }).pipe(Effect.provide(layerTest));
85 -});
93 + assert.equal(error.reason, "request-not-ready");
94 + assert.equal(
95 + error.message,
96 + `Runtime request ${requestId} on thread ${threadId} is not ready for response execution.`,
97 + );
98 + assert.isUndefined(error.cause);
99 + assert.equal(getSession.mock.calls.length, 0);
100 + assert.equal(respondToRuntimeRequest.mock.calls.length, 0);
101 + }).pipe(Effect.provide(layerTest));
102 + },
103 +);
apps/server/src/orchestration-v2/RuntimeRequestService.ts
+2
@@ -54,6 +54,7 @@ export interface RuntimeRequestServiceV2Shape {
54 readonly providerSessionId: ProviderSessionId;
55 readonly requestId: RuntimeRequestId;
56 readonly decision?: ProviderApprovalDecision;
57 + readonly feedback?: string;
58 readonly answers?: ProviderUserInputAnswers;
59 }) => Effect.Effect<void, RuntimeRequestResponseExecutionError>;
60 }
@@ -118,6 +119,7 @@ export const layer: Layer.Layer<
119 yield* session.value.respondToRuntimeRequest({
120 requestId: input.requestId,
121 ...(input.decision === undefined ? {} : { decision: input.decision }),
122 + ...(input.feedback === undefined ? {} : { feedback: input.feedback }),
123 ...(input.answers === undefined ? {} : { answers: input.answers }),
124 });
125 },
apps/web/src/components/chat/ChatComposer.tsx
+3 -1
@@ -3801,7 +3801,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
3801 onPaste={onComposerPasteStable}
3802 placeholder={
3803 isComposerApprovalState
3804 - ? "Send a message to decline and redirect the agent"
3804 + ? activePendingApproval?.supportsFeedback
3805 + ? "Send feedback to decline this request"
3806 + : "Send a message to decline and redirect the agent"
3807 : activePendingProgress
3808 ? isChoiceOnlyPendingQuestion
3809 ? "Choose an option above"
apps/web/src/components/chat/useComposerSend.ts
+45 -2
@@ -28,7 +28,10 @@ import {
28 } from "@t3tools/contracts";
29 import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
30 import { wasBootstrapThreadDeleted } from "@t3tools/client-runtime/errors";
31 -import { declinePendingApprovals } from "@t3tools/client-runtime/state/thread-requests";
31 +import {
32 + declinePendingApprovals,
33 + sendApprovalFeedback,
34 +} from "@t3tools/client-runtime/state/thread-requests";
35 import {
36 parseCodexFeedbackCommand,
37 submitCodexFeedback,
@@ -475,6 +478,10 @@ export function useComposerSend(input: ComposerSendInput) {
478 return;
479 }
480 const multipleModelSelections = sendCtx.multipleModelSelections;
481 + const approvalFeedbackTarget = pendingApprovalsRef.current.find(
482 + (approval) =>
483 + approval.supportsFeedback && approval.requestId === sendCtx.shownPendingApprovalIds[0],
484 + );
485 const multipleModelBlock =
486 multipleModelSelections === null
487 ? null
@@ -945,7 +952,7 @@ export function useComposerSend(input: ComposerSendInput) {
952 sendCtx?.shownPendingApprovalIds.includes(approval.requestId),
953 )
954 : [];
948 - if (approvalsToDecline.length > 0) {
955 + if (approvalsToDecline.length > 0 || approvalFeedbackTarget !== undefined) {
956 // A draft edited since send, or a paste still landing in it, is no longer the message
957 // the user sent.
958 const attachmentIdsAtSend = composerAttachmentsSnapshot.map((attachment) => attachment.id);
@@ -981,6 +988,42 @@ export function useComposerSend(input: ComposerSendInput) {
988 const approvalResponding = approvalsToDecline.some((approval) =>
989 respondingRequestIdsRef.current.includes(approval.requestId),
990 );
991 + if (approvalFeedbackTarget !== undefined) {
992 + if (composerAttachmentsSnapshot.length > 0 || outgoingMessageContext !== undefined) {
993 + setThreadError(
994 + threadIdForSend,
995 + "Send approval feedback without attachments or added context.",
996 + );
997 + sendInFlightRef.current = false;
998 + return;
999 + }
1000 + if (
1001 + changedBeforeDecline ||
1002 + approvalResponding ||
1003 + currentRouteThreadKeyRef.current !== routeThreadKey
1004 + ) {
1005 + sendInFlightRef.current = false;
1006 + return;
1007 + }
1008 + const sent = await sendApprovalFeedback(
1009 + approvalFeedbackTarget,
1010 + messageTextForSend,
1011 + onRespondToApprovalStable,
1012 + ).catch(() => false);
1013 + sendInFlightRef.current = false;
1014 + if (
1015 + sent &&
1016 + !draftChangedSinceSend() &&
1017 + currentRouteThreadKeyRef.current === routeThreadKey &&
1018 + useComposerDraftStore.getState().getComposerDraft(composerDraftTarget) ===
1019 + draftBeforeDecline
1020 + ) {
1021 + promptRef.current = "";
1022 + clearComposerDraftContent(composerDraftTarget);
1023 + composerRef.current?.resetCursorState();
1024 + }
1025 + return;
1026 + }
1027 const declined =
1028 !changedBeforeDecline &&
1029 !approvalResponding &&
apps/web/src/components/chat/usePendingThreadRequests.ts
+2
@@ -300,6 +300,7 @@ export function usePendingThreadRequests(input: {
300 const onRespondToApproval = async (
301 requestId: RuntimeRequestId,
302 decision: ProviderApprovalDecision,
303 + feedback?: string,
304 ) => {
305 if (!activeThreadId || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope))
306 return;
@@ -318,6 +319,7 @@ export function usePendingThreadRequests(input: {
319 threadId: activeThreadId,
320 requestId,
321 decision,
322 + ...(feedback === undefined ? {} : { feedback }),
323 },
324 });
325 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
docs/user/permission-modes.md
+2
@@ -37,6 +37,8 @@ by the permission mode. See [ACP Registry permissions](./providers-acp.md#permis
37
38 Claude can still ask in **Full access** when its settings disable bypass permissions or require
39 approval for an action.
40 +While a Claude approval is pending, type a text reply to decline that request and give feedback
41 +directly to the agent that asked, including a subagent. Other pending requests stay unanswered.
42
43 Antigravity can still send native approval requests in **Full access**. It only offers remembered
44 approvals for actions that support them.
packages/client-runtime/src/operations/commands.ts
+2
@@ -185,6 +185,7 @@ export interface InterruptThreadTurnInput extends ThreadCommandInput {
185 export interface RespondToThreadApprovalInput extends ThreadCommandInput {
186 readonly requestId: RuntimeRequestId;
187 readonly decision: ProviderApprovalDecision;
188 + readonly feedback?: string;
189 }
190
191 export interface RespondToThreadUserInputInput extends ThreadCommandInput {
@@ -873,6 +874,7 @@ export const respondToThreadApproval = Effect.fn("EnvironmentCommands.respondToT
874 threadId: input.threadId,
875 requestId: input.requestId,
876 decision: input.decision,
877 + ...(input.feedback === undefined ? {} : { feedback: input.feedback }),
878 });
879 },
880 );
packages/client-runtime/src/state/threadRequests.test.ts
+43
@@ -13,6 +13,7 @@ import {
13 createQuestionHistoryProjector,
14 derivePendingThreadRequests,
15 declinePendingApprovals,
16 + sendApprovalFeedback,
17 seedUserInputDraftAnswers,
18 type ApprovalResponder,
19 type ThreadPendingApproval,
@@ -72,6 +73,48 @@ describe("declining approvals before sending", () => {
73 ).toBe(true);
74 expect(respond).not.toHaveBeenCalled();
75 });
76 +
77 + it("sends feedback only to the displayed request, leaving other approvals pending", async () => {
78 + const respond = vi.fn<ApprovalResponder>(async () => AsyncResult.success(undefined));
79 + const pending = derivePendingThreadRequests({
80 + runtimeRequests: [
81 + {
82 + ...projection.runtimeRequests[0]!,
83 + kind: "command",
84 + responseCapability: {
85 + type: "live",
86 + providerSessionId: ProviderSessionId.make("claude-session"),
87 + supportsFeedback: true,
88 + },
89 + },
90 + { ...projection.runtimeRequests[0]!, id: second.requestId, kind: "command" },
91 + ],
92 + turnItems: [],
93 + });
94 + expect(await sendApprovalFeedback(pending.approvals[0]!, " Safer please. ", respond)).toBe(
95 + true,
96 + );
97 + expect(respond.mock.calls).toEqual([[approval.requestId, "decline", "Safer please."]]);
98 + });
99 +
100 + it("keeps feedback unsent when unsupported, stale, empty or rejected", async () => {
101 + const respond = vi.fn<ApprovalResponder>(async () => AsyncResult.failure(Cause.fail("failed")));
102 + expect(await sendApprovalFeedback(approval, "Safer please.", respond)).toBe(false);
103 + expect(
104 + await sendApprovalFeedback(
105 + { ...approval, supportsFeedback: true, responseCapability: "not_resumable" },
106 + "Safer please.",
107 + respond,
108 + ),
109 + ).toBe(false);
110 + expect(await sendApprovalFeedback({ ...approval, supportsFeedback: true }, " ", respond)).toBe(
111 + false,
112 + );
113 + expect(respond).not.toHaveBeenCalled();
114 + expect(
115 + await sendApprovalFeedback({ ...approval, supportsFeedback: true }, "Safer please.", respond),
116 + ).toBe(false);
117 + });
118 });
119
120 describe("initial user input drafts", () => {
packages/client-runtime/src/state/threadRequests.ts
+16
@@ -15,8 +15,20 @@ import type { ThreadStructure, ThreadStructureVisibleTurnItem } from "./models.t
15 export type ApprovalResponder = (
16 requestId: RuntimeRequestId,
17 decision: ProviderApprovalDecision,
18 + feedback?: string,
19 ) => Promise<AtomCommandResult<unknown, unknown> | undefined>;
20
21 +/** Feedback belongs to the displayed request, which may be a native child's tool call. */
22 +export async function sendApprovalFeedback(
23 + approval: ThreadPendingApproval,
24 + feedback: string,
25 + respond: ApprovalResponder,
26 +): Promise<boolean> {
27 + if (!approval.supportsFeedback || approval.responseCapability !== "live" || !feedback.trim())
28 + return false;
29 + return (await respond(approval.requestId, "decline", feedback.trim()))?._tag === "Success";
30 +}
31 +
32 /** Declines every approval a redirect replaces; any one still pending would block the agent. */
33 export async function declinePendingApprovals(
34 approvals: ReadonlyArray<ThreadPendingApproval>,
@@ -40,6 +52,7 @@ export interface ThreadPendingApproval {
52 readonly appName?: string;
53 readonly options?: ReadonlyArray<ProviderApprovalOption>;
54 readonly responseCapability: "live" | "not_resumable";
55 + readonly supportsFeedback?: boolean;
56 }
57
58 export const FULL_ACCESS_OVERRIDE_QUESTION = "Why am I being asked this?";
@@ -142,6 +155,9 @@ export function derivePendingThreadRequests(
155 ? { options: item.options }
156 : {}),
157 responseCapability: responseCapability === "live" ? "live" : "not_resumable",
158 + ...(request.responseCapability.type === "live" && request.responseCapability.supportsFeedback
159 + ? { supportsFeedback: true }
160 + : {}),
161 });
162 }
163
packages/contracts/src/orchestrationV2.ts
+7 -1
@@ -1020,13 +1020,18 @@ export const OrchestrationV2RuntimeRequest = Schema.Struct({
1020 ]),
1021 status: Schema.Literals(["pending", "resolved", "expired", "cancelled"]),
1022 responseCapability: Schema.Union([
1023 - Schema.Struct({ type: Schema.Literal("live"), providerSessionId: ProviderSessionId }),
1023 + Schema.Struct({
1024 + type: Schema.Literal("live"),
1025 + providerSessionId: ProviderSessionId,
1026 + supportsFeedback: Schema.optional(Schema.Boolean),
1027 + }),
1028 Schema.Struct({ type: Schema.Literal("message") }),
1029 Schema.Struct({ type: Schema.Literal("not_resumable"), reason: Schema.String }),
1030 ]),
1031 createdAt: Schema.DateTimeUtc,
1032 resolvedAt: Schema.NullOr(Schema.DateTimeUtc),
1033 decision: Schema.optional(ProviderApprovalDecision),
1034 + feedback: Schema.optional(Schema.String),
1035 answers: Schema.optional(ProviderUserInputAnswers),
1036 });
1037 export type OrchestrationV2RuntimeRequest = typeof OrchestrationV2RuntimeRequest.Type;
@@ -2921,6 +2926,7 @@ export const OrchestrationV2Command = Schema.Union([
2926 threadId: ThreadId,
2927 requestId: RuntimeRequestId,
2928 decision: Schema.optional(ProviderApprovalDecision),
2929 + feedback: Schema.optional(Schema.String),
2930 answers: Schema.optional(ProviderUserInputAnswers),
2931 attachmentsByQuestionId: Schema.optional(UserInputAttachments),
2932 }),
packages/provider-core/src/server/ProviderAdapter.ts
+1
@@ -455,6 +455,7 @@ export interface ProviderAdapterV2InterruptInput {
455 export interface ProviderAdapterV2RuntimeRequestResponseInput {
456 readonly requestId: RuntimeRequestId;
457 readonly decision?: ProviderApprovalDecision;
458 + readonly feedback?: string;
459 readonly answers?: ProviderUserInputAnswers;
460 readonly response?: unknown;
461 }