Skip to content

Commit b7e802b

Browse files
authored
fix(claude): route approval feedback to the requesting agent (pingdotgg#23657)
1 parent 6ed47b5 commit b7e802b

21 files changed

Lines changed: 596 additions & 92 deletions

‎apps/mobile/src/features/threads/ThreadDetailScreen.tsx‎

Lines changed: 41 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ import {
5555
} from "@t3tools/shared/codexArtifactTemplates";
5656
import {
5757
declinePendingApprovals,
58+
sendApprovalFeedback,
5859
type ApprovalResponder,
5960
type ThreadUserInputQuestion,
6061
} from "@t3tools/client-runtime/state/thread-requests";
@@ -258,7 +259,10 @@ export interface ThreadDetailScreenProps {
258259
readonly onResumeQueue: (() => Promise<void>) | null;
259260
readonly onSendMessage: (
260261
followUp?: ActiveTurnComposerAction,
261-
beforeDispatch?: () => Promise<boolean>,
262+
beforeDispatch?: (
263+
text: string,
264+
hasAttachmentsOrContext: boolean,
265+
) => Promise<boolean | "responded">,
262266
) => Promise<MessageId | null>;
263267
readonly onReconnectEnvironment: () => void;
264268
readonly canSwitchThreadProvider: boolean;
@@ -1199,18 +1203,40 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
11991203
const approvalsToDecline = props.activePendingApprovals;
12001204
const declineBeforeDispatch =
12011205
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
12131211
)
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+
}
12141240
: undefined;
12151241
const messageId = await props.onSendMessage(followUp, declineBeforeDispatch);
12161242
if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
@@ -1642,7 +1668,9 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
16421668
editorRef={composerEditorRef}
16431669
placeholder={
16441670
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"
16461674
: "Ask the repo agent, or run a command…"
16471675
}
16481676
contentMaxWidth={contentMaxWidth}

‎apps/mobile/src/state/thread-task-permissions.test.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
} from "../../../../packages/client-runtime/src/state/orchestrationV2TestFixtures";
1919
import type { DraftComposerImageAttachment } from "../lib/composerImages";
2020
import type { PendingThreadRequests } from "@t3tools/client-runtime/state/thread-requests";
21+
import { sendApprovalFeedback } from "@t3tools/client-runtime/state/thread-requests";
2122
import { AsyncResult, type Atom } from "effect/reactivity";
2223
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
2324

@@ -202,6 +203,43 @@ beforeEach(() => {
202203
});
203204

204205
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+
205243
it("keeps a connected read-only task's draft instead of queueing it with another environment's grant", async () => {
206244
const composer = useThreadComposerState();
207245
expect(await composer.onSendMessage()).toBeNull();

‎apps/mobile/src/state/use-selected-thread-requests.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -236,7 +236,7 @@ export function useSelectedThreadRequests() {
236236
);
237237

238238
const onRespondToApproval = useCallback(
239-
async (requestId: RuntimeRequestId, decision: ProviderApprovalDecision) => {
239+
async (requestId: RuntimeRequestId, decision: ProviderApprovalDecision, feedback?: string) => {
240240
if (
241241
!selectedThreadShell ||
242242
!readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope)
@@ -257,6 +257,7 @@ export function useSelectedThreadRequests() {
257257
threadId: selectedThreadShell.id,
258258
requestId,
259259
decision,
260+
...(feedback === undefined ? {} : { feedback }),
260261
},
261262
});
262263
setRespondingApprovalId((current) => (current === requestId ? null : current));

‎apps/mobile/src/state/use-thread-composer-state.ts‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -526,7 +526,10 @@ export function useThreadComposerState() {
526526

527527
const onSendMessage = async (
528528
followUpOverride?: ActiveTurnComposerAction,
529-
beforeDispatch?: () => Promise<boolean>,
529+
beforeDispatch?: (
530+
text: string,
531+
hasAttachmentsOrContext: boolean,
532+
) => Promise<boolean | "responded">,
530533
) => {
531534
if (
532535
selectedThreadShell &&
@@ -645,7 +648,11 @@ export function useThreadComposerState() {
645648
}
646649

647650
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;
649656
// A context paste still landing, or any draft or settings change while approvals were
650657
// declined, means this snapshot is no longer what the user sent.
651658
if (appAtomRegistry.get(composerContextImportsAtom)[threadKey]) return null;
@@ -660,6 +667,10 @@ export function useThreadComposerState() {
660667
current.attachments.some((attachment, index) => attachment.id !== attachments[index]?.id)
661668
)
662669
return null;
670+
if (response === "responded") {
671+
clearComposerDraftContent(threadKey);
672+
return null;
673+
}
663674
}
664675

665676
// Resolved here rather than at drain time: the outbox can deliver minutes

‎apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts‎

Lines changed: 63 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -967,7 +967,10 @@ describe("ClaudeAdapterV2 append-system-prompt-file launch argument", () => {
967967
describe("ClaudeAdapterV2 approval cancellation", () => {
968968
it.effect("observes an approval signal that was already aborted", () =>
969969
Effect.gen(function* () {
970-
const decision = yield* Deferred.make<ProviderApprovalDecision>();
970+
const decision = yield* Deferred.make<{
971+
decision: ProviderApprovalDecision;
972+
feedback?: string;
973+
}>();
971974
const controller = new AbortController();
972975
controller.abort();
973976

@@ -976,7 +979,7 @@ describe("ClaudeAdapterV2 approval cancellation", () => {
976979
controller.signal,
977980
);
978981

979-
assert.equal(result, "cancel");
982+
assert.deepEqual(result, { decision: "cancel" });
980983
}),
981984
);
982985
});
@@ -2873,12 +2876,14 @@ describe("ClaudeAdapterV2 background wake turns", () => {
28732876
turn: Effect.Success<ReturnType<typeof openPlanTurn>>,
28742877
toolName: string,
28752878
toolInput: Record<string, unknown>,
2879+
options?: { toolUseID: string; agentID?: string },
28762880
) {
28772881
const decision = yield* Effect.promise(() =>
28782882
turn.canUseTool(toolName, toolInput, {
28792883
signal: new AbortController().signal,
2880-
toolUseID: "tool-plan-write",
2884+
toolUseID: options?.toolUseID ?? "tool-plan-write",
28812885
requestId: "request-plan-write",
2886+
...(options?.agentID === undefined ? {} : { agentID: options.agentID }),
28822887
}),
28832888
).pipe(Effect.forkScoped);
28842889
const first = yield* Effect.raceFirst(
@@ -2954,6 +2959,61 @@ describe("ClaudeAdapterV2 background wake turns", () => {
29542959
),
29552960
);
29562961

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+
29573017
it.effect("still captures ExitPlanMode when Plan approvals are never allowed", () =>
29583018
Effect.gen(function* () {
29593019
const turn = yield* openPlanTurn("full-access", "never");

‎apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts‎

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2892,6 +2892,7 @@ export function permissionResultFromDecision(input: {
28922892
readonly toolInput: Record<string, unknown>;
28932893
readonly toolUseID: string;
28942894
readonly suggestions?: Parameters<CanUseTool>[2]["suggestions"];
2895+
readonly feedback?: string;
28952896
}): PermissionResult {
28962897
if (input.decision === "accept" || input.decision === "acceptForSession") {
28972898
return {
@@ -2911,9 +2912,10 @@ export function permissionResultFromDecision(input: {
29112912
return {
29122913
behavior: "deny",
29132914
message:
2914-
input.decision === "cancel"
2915+
input.feedback?.trim() ||
2916+
(input.decision === "cancel"
29152917
? "User cancelled tool execution."
2916-
: "User declined tool execution.",
2918+
: "User declined tool execution."),
29172919
toolUseID: input.toolUseID,
29182920
decisionClassification: "user_reject",
29192921
...(input.decision === "cancel" ? { interrupt: true } : {}),
@@ -2942,11 +2944,11 @@ function toSessionPermissionUpdates(
29422944
}
29432945

29442946
export const awaitClaudeApprovalDecision = Effect.fn("awaitClaudeApprovalDecision")(function* (
2945-
decision: Deferred.Deferred<ProviderApprovalDecision>,
2947+
decision: Deferred.Deferred<ClaudeApprovalResponse>,
29462948
signal: AbortSignal,
29472949
) {
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" }));
29502952
signal.addEventListener("abort", abort, { once: true });
29512953
if (signal.aborted) {
29522954
abort();
@@ -3625,12 +3627,17 @@ function rememberClaudeSubagentLaunch(
36253627
}
36263628
}
36273629

3630+
type ClaudeApprovalResponse = {
3631+
readonly decision: ProviderApprovalDecision;
3632+
readonly feedback?: string;
3633+
};
3634+
36283635
type PendingClaudeRuntimeRequest =
36293636
| {
36303637
readonly type: "approval";
36313638
readonly requestId: OrchestrationV2RuntimeRequest["id"];
36323639
readonly requestKind: ProviderRequestKind;
3633-
readonly decision: Deferred.Deferred<ProviderApprovalDecision, never>;
3640+
readonly decision: Deferred.Deferred<ClaudeApprovalResponse, never>;
36343641
}
36353642
| {
36363643
readonly type: "user_input";
@@ -6467,6 +6474,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
64676474
responseCapability: {
64686475
type: "live",
64696476
providerSessionId,
6477+
...(input.questions === undefined ? { supportsFeedback: true } : {}),
64706478
},
64716479
createdAt,
64726480
resolvedAt: null,
@@ -8986,7 +8994,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
89868994
callbackOptions,
89878995
}),
89888996
});
8989-
const decision = yield* Deferred.make<ProviderApprovalDecision, never>();
8997+
const decision = yield* Deferred.make<ClaudeApprovalResponse, never>();
89908998
yield* Ref.update(pendingRuntimeRequests, (current) => {
89918999
const updated = new Map(current);
89929000
updated.set(String(artifacts.request.id), {
@@ -9033,7 +9041,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
90339041

90349042
return permissionResultFromDecision({
90359043
toolName,
9036-
decision: resolvedDecision,
9044+
...resolvedDecision,
90379045
toolInput,
90389046
toolUseID: callbackOptions.toolUseID,
90399047
...(callbackOptions.suggestions === undefined
@@ -10283,7 +10291,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
1028310291
}),
1028410292
});
1028510293
}
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+
});
1028710298
},
1028810299
(effect, requestInput) =>
1028910300
effect.pipe(

‎apps/server/src/orchestration-v2/EffectOutbox.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ export const OrchestrationEffectRequestV2 = Schema.Union([
8080
providerSessionId: ProviderSessionId,
8181
requestId: RuntimeRequestId,
8282
decision: Schema.optional(ProviderApprovalDecision),
83+
feedback: Schema.optional(Schema.String),
8384
answers: Schema.optional(ProviderUserInputAnswers),
8485
}),
8586
Schema.Struct({

‎apps/server/src/orchestration-v2/EffectWorker.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -384,6 +384,9 @@ export const layerExecutor: Layer.Layer<
384384
...(effect.request.decision === undefined
385385
? {}
386386
: { decision: effect.request.decision }),
387+
...(effect.request.feedback === undefined
388+
? {}
389+
: { feedback: effect.request.feedback }),
387390
...(effect.request.answers === undefined
388391
? {}
389392
: { answers: effect.request.answers }),

0 commit comments

Comments
 (0)