@devries-cameron20 / t3code-1 / commits / a93b03c8a5
Fork 0

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

feat(web): composer stays usable during approvals, and sending declines and redirects (#21503)

maria committed Oct 21, 2026 at 06:57 UTC a93b03c8a5a888cfa7fac1fd6cb7a814221adf72
9 files changed +391 -136
apps/mobile/src/features/threads/ThreadComposer.tsx
+31 -4
@@ -178,7 +178,11 @@ export interface ThreadComposerProps {
178 readonly onStopThread: () => void;
179 /** Present while the thread's queue is held. */
180 readonly onResumeQueue: (() => Promise<void>) | null;
181 - readonly onSendMessage: (followUp?: ActiveTurnComposerAction) => Promise<MessageId | null>;
181 + /** `stillSendable` reports whether the draft is unchanged after any wait before sending. */
182 + readonly onSendMessage: (
183 + followUp?: ActiveTurnComposerAction,
184 + stillSendable?: () => boolean,
185 + ) => Promise<MessageId | null>;
186 readonly onShowUsageLimits: (report: UsageLimitsReport | null) => void;
187 readonly canSwitchProvider: boolean;
188 readonly onUpdateModelSelection: (modelSelection: ModelSelection) => void;
@@ -356,6 +360,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
360 const inputRef = props.editorRef ?? fallbackInputRef;
361 const [isFocused, setIsFocused] = useState(false);
362 const pendingPastedTextAttachmentCountRef = useRef(0);
363 + const pendingNativeImagePasteCountRef = useRef(0);
364 const [pendingPastedTextAttachmentCount, setPendingPastedTextAttachmentCount] = useState(0);
365 const settingsSheetPresentation = useThreadSettingsSheetPresentation({
366 editorRef: inputRef,
@@ -599,7 +604,12 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
604 setComposerEditing(false);
605 };
606 const handleSend = async (followUp?: ActiveTurnComposerAction) => {
602 - if (isSubmissionLocked || pendingPastedTextAttachmentCountRef.current > 0) return;
607 + if (
608 + isSubmissionLocked ||
609 + pendingPastedTextAttachmentCountRef.current > 0 ||
610 + pendingNativeImagePasteCountRef.current > 0
611 + )
612 + return;
613 if (usageLimitsOffered && isUsageLimitsCommand(draftMessage) && draftAttachments.length === 0) {
614 if (openUsageLimits()) onChangeDraftMessage("");
615 return;
@@ -607,7 +617,20 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
617 const threadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
618 if (inFlightThreadIdsRef.current.has(threadKey)) return;
619 inFlightThreadIdsRef.current.add(threadKey);
610 - const sent = await settlePromise(() => onSendMessage(followUp));
620 + const draftAtSend = getComposerDraftSnapshot(composerDraftKey);
621 + const stillSendable = () => {
622 + const draft = getComposerDraftSnapshot(composerDraftKey);
623 + return (
624 + pendingPastedTextAttachmentCountRef.current === 0 &&
625 + pendingNativeImagePasteCountRef.current === 0 &&
626 + draft.text === draftAtSend.text &&
627 + draft.attachments.length === draftAtSend.attachments.length &&
628 + draft.attachments.every(
629 + (attachment, index) => attachment.id === draftAtSend.attachments[index]?.id,
630 + )
631 + );
632 + };
633 + const sent = await settlePromise(() => onSendMessage(followUp, stillSendable));
634 inFlightThreadIdsRef.current.delete(threadKey);
635 if (AsyncResult.isFailure(sent)) {
636 // The composer state already surfaces send errors; only the lock needed releasing.
@@ -915,7 +938,11 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
938 }}
939 onSelectionChange={composerMenu.onSelectionChange}
940 onPasteImages={(uris) => {
918 - if (!isSubmissionLocked) void props.onNativePasteImages(uris);
941 + if (isSubmissionLocked) return;
942 + pendingNativeImagePasteCountRef.current += 1;
943 + void props.onNativePasteImages(uris).finally(() => {
944 + pendingNativeImagePasteCountRef.current -= 1;
945 + });
946 }}
947 onPasteText={(paste) => {
948 if (isSubmissionLocked) return;
apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+49 -11
@@ -39,7 +39,6 @@ import type {
39 EnvironmentId,
40 MessageId,
41 ModelSelection,
42 - ProviderApprovalDecision,
42 ProviderInteractionMode,
43 RuntimeMode,
44 RuntimeRequestId,
@@ -52,7 +51,11 @@ import {
51 appendCodexArtifactTemplateUsePrompt,
52 type CodexArtifactTemplate,
53 } from "@t3tools/shared/codexArtifactTemplates";
55 -import type { ThreadUserInputQuestion } from "@t3tools/client-runtime/state/thread-requests";
54 +import {
55 + declinePendingApprovals,
56 + type ApprovalResponder,
57 + type ThreadUserInputQuestion,
58 +} from "@t3tools/client-runtime/state/thread-requests";
59 import {
60 presentPendingBackgroundWork,
61 presentProviderGoal,
@@ -199,6 +202,7 @@ export interface ThreadDetailScreenProps {
202 | { readonly kind: "failed"; readonly reason: string; readonly onEditTask: () => void }
203 | null;
204 readonly activePendingApproval: PendingApproval | null;
205 + readonly activePendingApprovals: ReadonlyArray<PendingApproval>;
206 readonly respondingApprovalId: RuntimeRequestId | null;
207 readonly activePendingUserInput: PendingUserInput | null;
208 readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
@@ -236,16 +240,16 @@ export interface ThreadDetailScreenProps {
240 readonly onStopThread: () => void;
241 /** Present while the thread's queue is held. */
242 readonly onResumeQueue: (() => Promise<void>) | null;
239 - readonly onSendMessage: (followUp?: ActiveTurnComposerAction) => Promise<MessageId | null>;
243 + readonly onSendMessage: (
244 + followUp?: ActiveTurnComposerAction,
245 + beforeDispatch?: () => Promise<boolean>,
246 + ) => Promise<MessageId | null>;
247 readonly onReconnectEnvironment: () => void;
248 readonly canSwitchThreadProvider: boolean;
249 readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => void;
250 readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
251 readonly onUpdateThreadInteractionMode: (interactionMode: ProviderInteractionMode) => void;
245 - readonly onRespondToApproval: (
246 - requestId: RuntimeRequestId,
247 - decision: ProviderApprovalDecision,
248 - ) => Promise<unknown>;
252 + readonly onRespondToApproval: ApprovalResponder;
253 readonly onSelectUserInputOption: (
254 requestId: RuntimeRequestId,
255 question: ThreadUserInputQuestion,
@@ -1152,12 +1156,37 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
1156 selectedThreadKey,
1157 ]);
1158
1155 - const handleSendMessage = async (followUp?: ActiveTurnComposerAction) => {
1159 + const activePendingApprovalsRef = useRef(props.activePendingApprovals);
1160 + useLayoutEffect(() => {
1161 + activePendingApprovalsRef.current = props.activePendingApprovals;
1162 + }, [props.activePendingApprovals]);
1163 + const handleSendMessage = async (
1164 + followUp?: ActiveTurnComposerAction,
1165 + stillSendable?: () => boolean,
1166 + ) => {
1167 const targetThreadKey = selectedThreadKey;
1168 const hasUserMessage = selectedThreadFeed.some(
1169 (entry) => entry.type === "message" && entry.message.role === "user",
1170 );
1160 - const messageId = await props.onSendMessage(followUp);
1171 + // Runs only once the send path has validated the draft and is about to deliver it, so an
1172 + // empty submit, a queued-message edit, or `/feedback` leaves approvals alone.
1173 + const approvalsToDecline = props.activePendingApprovals;
1174 + const declineBeforeDispatch =
1175 + approvalsToDecline.length > 0 && props.activePendingUserInput === null
1176 + ? async () =>
1177 + props.respondingApprovalId === null &&
1178 + (await declinePendingApprovals(approvalsToDecline, props.onRespondToApproval)) &&
1179 + selectedThreadKeyRef.current === targetThreadKey &&
1180 + // A draft edited or pasted into during the decline isn't what the user sent.
1181 + stillSendable?.() !== false &&
1182 + // An approval that arrived during the decline would block the redirect; the draft
1183 + // stays so the next send declines it too.
1184 + !activePendingApprovalsRef.current.some(
1185 + (approval) =>
1186 + !approvalsToDecline.some((declined) => declined.requestId === approval.requestId),
1187 + )
1188 + : undefined;
1189 + const messageId = await props.onSendMessage(followUp, declineBeforeDispatch);
1190 if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
1191 return messageId;
1192 }
@@ -1568,7 +1597,11 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
1597 canOperateThread={props.canOperateThread}
1598 reportedModelSelection={reportedModelSelection}
1599 editorRef={composerEditorRef}
1571 - placeholder="Ask the repo agent, or run a command…"
1600 + placeholder={
1601 + props.activePendingApproval
1602 + ? "Send a message to decline and redirect the agent"
1603 + : "Ask the repo agent, or run a command…"
1604 + }
1605 contentMaxWidth={contentMaxWidth}
1606 connectionState={props.connectionStateLabel}
1607 environmentLabel={props.environmentLabel}
@@ -1592,7 +1625,12 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
1625 : null
1626 }
1627 draftKey={props.composerDraftKey ?? undefined}
1595 - followUpBehavior={props.followUpBehavior}
1628 + followUpBehavior={
1629 + props.activePendingApprovals.length > 0 &&
1630 + props.activePendingUserInput === null
1631 + ? "steer"
1632 + : props.followUpBehavior
1633 + }
1634 canSteerActiveTurn={props.canSteerActiveTurn}
1635 hidden={composerSlotHidden}
1636 queuedEdit={
apps/mobile/src/features/threads/ThreadRouteScreen.tsx
+1
@@ -932,6 +932,7 @@ function ThreadRouteContent(
932 : null
933 }
934 activePendingApproval={requests.activePendingApproval}
935 + activePendingApprovals={requests.activePendingApprovals}
936 respondingApprovalId={requests.respondingApprovalId}
937 activePendingUserInput={requests.activePendingUserInput}
938 activePendingUserInputDrafts={requests.activePendingUserInputDrafts}
apps/mobile/src/state/use-selected-thread-requests.ts
+1
@@ -371,6 +371,7 @@ export function useSelectedThreadRequests() {
371
372 return {
373 activePendingApproval,
374 + activePendingApprovals,
375 activePendingUserInput,
376 activePendingUserInputDrafts,
377 activePendingUserInputAnswers,
apps/mobile/src/state/use-thread-composer-state.ts
+26 -3
@@ -528,7 +528,10 @@ export function useThreadComposerState() {
528 scheduleUnusedComposerAttachmentCleanup(draft.attachments);
529 };
530
531 - const onSendMessage = async (followUpOverride?: ActiveTurnComposerAction) => {
531 + const onSendMessage = async (
532 + followUpOverride?: ActiveTurnComposerAction,
533 + beforeDispatch?: () => Promise<boolean>,
534 + ) => {
535 if (
536 selectedThreadShell &&
537 selectedEnvironmentRuntime?.connectionState === "connected" &&
@@ -645,15 +648,35 @@ export function useThreadComposerState() {
648 return null;
649 }
650
651 + if (beforeDispatch !== undefined) {
652 + if (!(await beforeDispatch())) return null;
653 + // A context paste still landing, or any draft or settings change while approvals were
654 + // declined, means this snapshot is no longer what the user sent.
655 + if (appAtomRegistry.get(composerContextImportsAtom)[threadKey]) return null;
656 + const current = getComposerDraftSnapshot(threadKey);
657 + if (
658 + current.text !== draft.text ||
659 + JSON.stringify(current.context) !== JSON.stringify(draft.context) ||
660 + JSON.stringify(current.modelSelection) !== JSON.stringify(draft.modelSelection) ||
661 + current.runtimeMode !== draft.runtimeMode ||
662 + current.interactionMode !== draft.interactionMode ||
663 + current.attachments.length !== attachments.length ||
664 + current.attachments.some((attachment, index) => attachment.id !== attachments[index]?.id)
665 + )
666 + return null;
667 + }
668 +
669 // Resolved here rather than at drain time: the outbox can deliver minutes
670 // later, and the choice belongs to the moment the user pressed send.
671 // Steering travels as "auto" so a turn that ends in the meantime degrades
672 // to a queued run on the server instead of failing the delivery and
673 // bouncing the message back into the draft.
674 + // A redirect declined approvals to steer the waiting turn, not to queue behind it.
675 + const activeTurnDefault = beforeDispatch !== undefined ? "steer" : followUpBehavior;
676 const followUpAction = resolveComposerDispatchMode({
677 running: activeThreadBusy && canSteerActiveTurn,
655 - alternateModifier: followUpOverride !== undefined && followUpOverride !== followUpBehavior,
656 - activeTurnDefault: followUpBehavior,
678 + alternateModifier: followUpOverride !== undefined && followUpOverride !== activeTurnDefault,
679 + activeTurnDefault,
680 });
681 const setupRunning = [selectedThreadActivityRun?.status, selectedThreadRuntime?.status].some(
682 (status) => status === "preparing" || status === "starting",
apps/web/src/components/ChatView.tsx
+99
@@ -91,6 +91,7 @@ import {
91 import { readPastedComposerContext } from "./composerInlineTokenPaste";
92 import { isPasteAsTextShortcut } from "@t3tools/client-runtime/text-paste";
93 import { effectiveSnoozed, threadWokeAt } from "@t3tools/client-runtime/state/thread-settled";
94 +import { declinePendingApprovals } from "@t3tools/client-runtime/state/thread-requests";
95 import { presentThreadShell } from "@t3tools/client-runtime/state/shell";
96 import { childThreadInputsTitle } from "@t3tools/client-runtime/state/threads";
97 import { useAcknowledgeThreadWoke, useThreadActions } from "../hooks/useThreadActions";
@@ -2542,6 +2543,13 @@ export default function ChatView(props: ChatViewProps) {
2543 composerRef,
2544 setThreadError,
2545 });
2546 + // A send awaits uploads before it declines, so it reads the approvals pending by then.
2547 + const pendingApprovalsRef = useRef(pendingApprovals);
2548 + const respondingRequestIdsRef = useRef(respondingRequestIds);
2549 + useLayoutEffect(() => {
2550 + pendingApprovalsRef.current = pendingApprovals;
2551 + respondingRequestIdsRef.current = respondingRequestIds;
2552 + }, [pendingApprovals, respondingRequestIds]);
2553 const activeProposedPlan = (() => {
2554 if (!latestRunSettled) {
2555 return null;
@@ -6213,6 +6221,9 @@ export default function ChatView(props: ChatViewProps) {
6221 },
6222 ) => {
6223 e?.preventDefault();
6224 + // What the user pressed send on; uploads below can take a while, and a redirect must not
6225 + // decline approvals for a draft that changed meanwhile.
6226 + const promptAtSend = promptRef.current;
6227 if (
6228 usageLimitsOffered &&
6229 usageLimitsKey !== null &&
@@ -6787,6 +6798,94 @@ export default function ChatView(props: ChatViewProps) {
6798 );
6799 return;
6800 }
6801 + // A message sent while approvals are pending redirects the agent. They are declined only
6802 + // here, after everything above has accepted the send, so local commands and rejected
6803 + // drafts leave them alone. After navigating away during an upload, the shown approvals
6804 + // are another thread's, so this send leaves them alone too.
6805 + const approvalsToDecline =
6806 + currentRouteThreadKeyRef.current === routeThreadKey
6807 + ? pendingApprovalsRef.current.filter((approval) =>
6808 + sendCtx?.shownPendingApprovalIds.includes(approval.requestId),
6809 + )
6810 + : [];
6811 + if (approvalsToDecline.length > 0) {
6812 + // A draft edited since send, or a paste still landing in it, is no longer the message
6813 + // the user sent.
6814 + const attachmentIdsAtSend = composerAttachmentsSnapshot.map((attachment) => attachment.id);
6815 + // A direct annotation send writes its image and reference into the draft as it sends,
6816 + // so the live draft may still lack them; anything else differing is a real edit.
6817 + const annotationImageId = directAnnotation?.image?.id;
6818 + const attachmentIdsBeforeAnnotation = attachmentIdsAtSend.filter(
6819 + (id) => id !== annotationImageId,
6820 + );
6821 + const sameIds = (left: ReadonlyArray<string>, right: ReadonlyArray<string>) =>
6822 + left.length === right.length && left.every((id, index) => id === right[index]);
6823 + const draftChangedSinceSend = () => {
6824 + if (composerRef.current?.hasPendingAttachments() === true) return true;
6825 + const sendContext = composerRef.current?.getSendContext();
6826 + const attachmentIds = sendContext
6827 + ? [...sendContext.images, ...sendContext.files].map((attachment) => attachment.id)
6828 + : attachmentIdsAtSend;
6829 + const promptUnchanged =
6830 + promptRef.current === promptAtSend || promptRef.current === promptForSend;
6831 + const attachmentsUnchanged =
6832 + sameIds(attachmentIds, attachmentIdsAtSend) ||
6833 + (annotationImageId !== undefined &&
6834 + sameIds(attachmentIds, attachmentIdsBeforeAnnotation));
6835 + return !promptUnchanged || !attachmentsUnchanged;
6836 + };
6837 + const draftBeforeDecline = useComposerDraftStore
6838 + .getState()
6839 + .getComposerDraft(composerDraftTarget);
6840 + const changedBeforeDecline = draftChangedSinceSend();
6841 + const pendingIdsBeforeDecline = pendingApprovalsRef.current.map(
6842 + (approval) => approval.requestId,
6843 + );
6844 + const approvalResponding = approvalsToDecline.some((approval) =>
6845 + respondingRequestIdsRef.current.includes(approval.requestId),
6846 + );
6847 + const declined =
6848 + !changedBeforeDecline &&
6849 + !approvalResponding &&
6850 + (await declinePendingApprovals(approvalsToDecline, onRespondToApprovalStable).catch(
6851 + () => false,
6852 + ));
6853 + const draftChanged =
6854 + changedBeforeDecline ||
6855 + draftChangedSinceSend() ||
6856 + useComposerDraftStore.getState().getComposerDraft(composerDraftTarget) !==
6857 + draftBeforeDecline;
6858 + // An approval that arrived during the decline would block the redirect; keep the draft so
6859 + // the next send declines it too.
6860 + const approvalArrived = pendingApprovalsRef.current.some(
6861 + (approval) => !pendingIdsBeforeDecline.includes(approval.requestId),
6862 + );
6863 + if (
6864 + !declined ||
6865 + draftChanged ||
6866 + approvalArrived ||
6867 + currentRouteThreadKeyRef.current !== routeThreadKey
6868 + ) {
6869 + sendInFlightRef.current = false;
6870 + setDockedDraftHeroThreadKey((currentThreadKey) =>
6871 + currentThreadKey === activeThreadKey ? null : currentThreadKey,
6872 + );
6873 + if (draftChanged || approvalResponding || (declined && approvalArrived)) {
6874 + toastManager.add({
6875 + type: "info",
6876 + title: draftChanged
6877 + ? declined
6878 + ? "Approval declined. Your message changed, so it wasn't sent."
6879 + : "Your message changed, so it wasn't sent."
6880 + : approvalResponding
6881 + ? "An approval is already being answered, so your message wasn't sent."
6882 + : "Another approval arrived, so your message wasn't sent.",
6883 + description: "Send again when it's ready.",
6884 + });
6885 + }
6886 + return;
6887 + }
6888 + }
6889 if (sendQueuesBehindSetup) {
6890 setSetupQueueSendThreadKey(activeThreadKey);
6891 } else {
apps/web/src/components/chat/ChatComposer.tsx
+105 -117
@@ -1489,6 +1489,7 @@ export interface ChatComposerHandle {
1489 selectedProviderModels: ReadonlyArray<ServerProvider["models"][number]>;
1490 interactionMode: ProviderInteractionMode;
1491 interactionModeEnabled: boolean;
1492 + shownPendingApprovalIds: ReadonlyArray<RuntimeRequestId>;
1493 };
1494 validateProviderInput: (providerInput: string) => boolean;
1495 setMultipleModelSelections: (selections: ReadonlyArray<ModelSelection>) => void;
@@ -2828,7 +2829,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2829 const nonPersistedComposerImageIdSet = new Set(nonPersistedComposerImageIds);
2830
2831 const isComposerApprovalState = activePendingApproval !== null;
2831 - const composerSuggestionsVisible = composerMenuOpen && !isComposerApprovalState;
2832 + // A send declines the approvals shown here to redirect the agent, so it steers the waiting
2833 + // turn instead of queueing behind it. Approvals the typing guard holds stay unseen and pending.
2834 + const followUpBehavior = pendingApprovals.some(
2835 + (approval) => !heldRequestIds.has(approval.requestId),
2836 + )
2837 + ? "steer"
2838 + : settings.followUpBehavior;
2839 + const composerSuggestionsVisible = composerMenuOpen;
2840 const composerSuggestionListVisible = composerSuggestionsVisible && composerMenuItems.length > 0;
2841 const activePendingUserInput = pendingUserInputs[0] ?? null;
2842 const isChoiceOnlyPendingQuestion =
@@ -2837,7 +2845,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2845 isComposerApprovalState ||
2846 pendingUserInputs.length > 0 ||
2847 (!isComposerCollapsedMobile && showPlanFollowUpPrompt && activeProposedPlan !== null);
2840 - const showCollapsedMobilePromptRow = isComposerCollapsedMobile && !isComposerApprovalState;
2848 + const showCollapsedMobilePromptRow = isComposerCollapsedMobile;
2849 const showComposerAttachAction =
2850 fileStagingLimit !== null &&
2851 (!activePendingProgress ||
@@ -4057,7 +4065,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
4065 resolveComposerDispatchMode({
4066 running: phase === "running",
4067 alternateModifier: false,
4060 - activeTurnDefault: settings.followUpBehavior,
4068 + activeTurnDefault: followUpBehavior,
4069 canSteer: !isCompacting,
4070 }),
4071 submissionIntent,
@@ -4080,7 +4088,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
4088 resolveComposerDispatchMode({
4089 running: phase === "running",
4090 alternateModifier: event.metaKey || event.ctrlKey,
4083 - activeTurnDefault: settings.followUpBehavior,
4091 + activeTurnDefault: followUpBehavior,
4092 canSteer: !isCompacting,
4093 }),
4094 );
@@ -4092,13 +4100,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
4100 resolveComposerDispatchMode({
4101 running: phase === "running",
4102 alternateModifier: false,
4095 - activeTurnDefault: settings.followUpBehavior,
4103 + activeTurnDefault: followUpBehavior,
4104 canSteer: !isCompacting,
4105 }),
4106 );
4107 };
4108 const submitCitationAndSendStable = useStableCallback(submitCitationAndSend);
4101 - // A question or approval took the editor while a citation comment was
4109 + // A question took the editor while a citation comment was
4110 // unsaved. Keep the comment in the prompt that comes back afterward.
4111 const saveCitationDraftToPrompt = (replacedValue: string, savedValue: string) => {
4112 if (replacedValue !== prompt) return;
@@ -4174,7 +4182,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
4182 if (event.shiftKey || event.altKey || event.metaKey || event.ctrlKey || event.isComposing) {
4183 return false;
4184 }
4177 - if (isComposerApprovalState || pendingUserInputs.length > 0) return false;
4185 + if (pendingUserInputs.length > 0) return false;
4186 if (
4187 composerImagesRef.current.length > 0 ||
4188 composerFilesRef.current.length > 0 ||
@@ -4256,7 +4264,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
4264 resolveComposerDispatchMode({
4265 running: phase === "running",
4266 alternateModifier: submissionIntent === "alternate",
4259 - activeTurnDefault: settings.followUpBehavior,
4267 + activeTurnDefault: followUpBehavior,
4268 canSteer: !isCompacting,
4269 }),
4270 submissionIntent,
@@ -5375,11 +5383,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
5383 if (isCommandPaletteOpen() || isRevertingCheckpoint) {
5384 return;
5385 }
5378 - if (pendingUserInputs.length > 0 && !isComposerApprovalState) {
5386 + if (pendingUserInputs.length > 0) {
5387 setIsStashMenuOpen((open) => !open);
5388 return;
5389 }
5382 - if (isComposerApprovalState || projectSelectionRequired || activePendingProgress !== null) {
5390 + if (projectSelectionRequired || activePendingProgress !== null) {
5391 return;
5392 }
5393 void stashCurrentPromptStable();
@@ -5388,7 +5396,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
5396 return () => window.removeEventListener("keydown", handler, true);
5397 }, [
5398 activePendingProgress,
5391 - isComposerApprovalState,
5399 isComposerModelPickerOpen,
5400 keybindings,
5401 pendingUserInputs.length,
@@ -5427,7 +5434,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
5434 !options?.skipImageInlineChip &&
5435 (options?.selection !== undefined ||
5436 isConnecting ||
5430 - isComposerApprovalState ||
5437 pendingUserInputs.length > 0 ||
5438 projectSelectionRequired ||
5439 stripInlineContextReferences(promptRef.current).trim().length > 0);
@@ -5750,7 +5756,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
5756 if (
5757 text.length === 0 ||
5758 isConnecting ||
5753 - isComposerApprovalState ||
5759 activePendingIsResponding ||
5760 (pendingUserInputs.length > 0 && !activePendingProgress?.activeQuestion) ||
5761 projectSelectionRequired ||
@@ -5980,7 +5985,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
5985 const canAnswer =
5986 canOperateThread &&
5987 !isConnecting &&
5983 - !isComposerApprovalState &&
5988 !activePendingIsResponding &&
5989 activePendingProgress?.activeQuestion?.allowCustomAnswer !== false;
5990 const text = `${records
@@ -6169,7 +6173,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6173 stepReasoningEffort: (direction) => {
6174 if (
6175 noProviderAvailable ||
6172 - isComposerApprovalState ||
6176 pendingUserInputs.length > 0 ||
6177 // A queued-message edit draft is discarded when the edit ends.
6178 isEditingQueuedMessage
@@ -6298,6 +6301,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6301 },
6302 getSendContext: () => ({
6303 answeringPendingUserInput: activePendingProgress !== null,
6304 + shownPendingApprovalIds: pendingApprovals
6305 + .map((approval) => approval.requestId)
6306 + .filter((requestId) => !heldRequestIds.has(requestId)),
6307 prompt: promptRef.current,
6308 images: composerImagesRef.current,
6309 files: composerFilesRef.current,
@@ -6348,6 +6354,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6354 isEditingQueuedMessage,
6355 composerCursor,
6356 activePendingProgress,
6357 + pendingApprovals,
6358 + heldRequestIds,
6359 composerTerminalContexts,
6360 insertComposerDraftTerminalContext,
6361 insertComposerTextStable,
@@ -6362,7 +6370,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6370 environmentId,
6371 primaryEnvironmentId,
6372 isConnecting,
6365 - isComposerApprovalState,
6373 isChoiceOnlyPendingQuestion,
6374 isLiteralPendingAnswer,
6375 pendingUserInputs.length,
@@ -6584,15 +6591,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6591 </ComposerBanner.Attachment>
6592 ) : null}
6593 </ComposerBanner.Column>
6587 - {!isComposerApprovalState ? (
6588 - <ComposerStashBadge
6589 - count={stashQueue.length}
6590 - menuOpen={isStashMenuOpen}
6591 - pulseKey={stashPulse.key}
6592 - pulsing={stashPulse.active}
6593 - onToggleMenu={toggleStashMenuStable}
6594 - />
6595 - ) : null}
6594 + <ComposerStashBadge
6595 + count={stashQueue.length}
6596 + menuOpen={isStashMenuOpen}
6597 + pulseKey={stashPulse.key}
6598 + pulsing={stashPulse.active}
6599 + onToggleMenu={toggleStashMenuStable}
6600 + />
6601 </ComposerBanner.Dock>
6602 <div className="relative">
6603 <ComposerSurface.Main
@@ -6670,12 +6675,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6675 className={cn(
6676 "relative px-3 pb-2 sm:px-4",
6677 "pt-3.5 sm:pt-4",
6673 - isComposerApprovalState && "pb-3 sm:pb-4",
6678 isComposerCollapsedMobile && "hidden",
6679 isComposerResting && "py-2 sm:py-2",
6680 )}
6681 >
6678 - {isStashMenuOpen && !composerMenuOpen && !isComposerApprovalState && (
6682 + {isStashMenuOpen && !composerMenuOpen && (
6683 <ComposerCommandMenuLayer anchor={composerMenuAnchor}>
6684 <ComposerStashMenu
6685 composerFormRef={composerFormRef}
@@ -6720,7 +6724,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6724 )}
6725
6726 {!isComposerCollapsedMobile &&
6723 - !isComposerApprovalState &&
6727 pendingUserInputs.length === 0 &&
6728 editingQueuedAttachments !== null &&
6729 editingQueuedAttachments.length > 0 && (
@@ -6756,7 +6759,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6759 )}
6760
6761 {!isComposerCollapsedMobile &&
6759 - !isComposerApprovalState &&
6762 (uncommittedSnapShotIds.length > 0 ||
6763 composerVideos.length > 0 ||
6764 expandedComposerImages.length > 0) && (
@@ -7013,83 +7015,77 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
7015 </div>
7016 )}
7017
7016 - {!isComposerCollapsedMobile &&
7017 - !isComposerApprovalState &&
7018 - composerOtherFiles.length > 0 && (
7019 - <div className="mb-3 flex flex-col gap-1">
7020 - {composerOtherFiles.map((file) => {
7021 - const fileCanUpload =
7022 - supportsAttachmentUploads &&
7023 - maxFileAttachmentBytes !== null &&
7024 - file.sizeBytes <= maxFileAttachmentBytes;
7025 - const upload = fileCanUpload ? uploadsByImageId[file.id] : undefined;
7026 - const needsReattach = composerFileNeedsReattach(file);
7027 - const canReattachFile =
7028 - fileStagingLimit !== null && file.sizeBytes <= fileStagingLimit;
7029 - return (
7030 - <div
7031 - key={file.id}
7032 - className="flex min-w-0 items-center gap-2 py-1 text-sm text-foreground"
7018 + {!isComposerCollapsedMobile && composerOtherFiles.length > 0 && (
7019 + <div className="mb-3 flex flex-col gap-1">
7020 + {composerOtherFiles.map((file) => {
7021 + const fileCanUpload =
7022 + supportsAttachmentUploads &&
7023 + maxFileAttachmentBytes !== null &&
7024 + file.sizeBytes <= maxFileAttachmentBytes;
7025 + const upload = fileCanUpload ? uploadsByImageId[file.id] : undefined;
7026 + const needsReattach = composerFileNeedsReattach(file);
7027 + const canReattachFile =
7028 + fileStagingLimit !== null && file.sizeBytes <= fileStagingLimit;
7029 + return (
7030 + <div
7031 + key={file.id}
7032 + className="flex min-w-0 items-center gap-2 py-1 text-sm text-foreground"
7033 + >
7034 + <PierreEntryIcon pathValue={file.name} kind="file" theme={resolvedTheme} />
7035 + <button
7036 + type="button"
7037 + disabled={needsReattach}
7038 + className="min-w-0 flex-1 truncate text-left hover:underline focus-visible:outline-2"
7039 + onClick={() => setPreviewFileId(file.id)}
7040 >
7034 - <PierreEntryIcon
7035 - pathValue={file.name}
7036 - kind="file"
7037 - theme={resolvedTheme}
7038 - />
7039 - <button
7040 - type="button"
7041 - disabled={needsReattach}
7042 - className="min-w-0 flex-1 truncate text-left hover:underline focus-visible:outline-2"
7043 - onClick={() => setPreviewFileId(file.id)}
7044 - >
7045 - {file.name}
7046 - </button>
7047 - <span className="shrink-0 text-xs text-secondary-label">
7048 - {needsReattach
7049 - ? canReattachFile
7050 - ? "Attach again"
7051 - : "Remove to send"
7052 - : upload?.status === "uploading"
7053 - ? formatAttachmentUploadProgress(upload.progress)
7054 - : formatAttachmentSize(file.sizeBytes)}
7055 - </span>
7056 - {!needsReattach && upload?.status === "failed" ? (
7057 - <Tooltip>
7058 - <TooltipTrigger
7059 - render={
7060 - <Button
7061 - variant="ghost"
7062 - size="icon-xs"
7063 - onClick={() =>
7064 - retryAttachmentUpload({
7065 - environmentId,
7066 - image: file,
7067 - draftTarget: attachmentDraftTarget,
7068 - })
7069 - }
7070 - disabled={!canOperateThread}
7071 - aria-label={`Retry upload for ${file.name}`}
7072 - />
7073 - }
7074 - >
7075 - <RefreshIcon />
7076 - </TooltipTrigger>
7077 - <TooltipPopup side="top">{upload.reason}</TooltipPopup>
7078 - </Tooltip>
7079 - ) : null}
7080 - <Button
7081 - variant="ghost"
7082 - size="icon-xs"
7083 - onClick={() => removeComposerFileFromDraft(file.id)}
7084 - aria-label={`Remove ${file.name}`}
7085 - >
7086 - <XIcon />
7087 - </Button>
7088 - </div>
7089 - );
7090 - })}
7091 - </div>
7092 - )}
7041 + {file.name}
7042 + </button>
7043 + <span className="shrink-0 text-xs text-secondary-label">
7044 + {needsReattach
7045 + ? canReattachFile
7046 + ? "Attach again"
7047 + : "Remove to send"
7048 + : upload?.status === "uploading"
7049 + ? formatAttachmentUploadProgress(upload.progress)
7050 + : formatAttachmentSize(file.sizeBytes)}
7051 + </span>
7052 + {!needsReattach && upload?.status === "failed" ? (
7053 + <Tooltip>
7054 + <TooltipTrigger
7055 + render={
7056 + <Button
7057 + variant="ghost"
7058 + size="icon-xs"
7059 + onClick={() =>
7060 + retryAttachmentUpload({
7061 + environmentId,
7062 + image: file,
7063 + draftTarget: attachmentDraftTarget,
7064 + })
7065 + }
7066 + disabled={!canOperateThread}
7067 + aria-label={`Retry upload for ${file.name}`}
7068 + />
7069 + }
7070 + >
7071 + <RefreshIcon />
7072 + </TooltipTrigger>
7073 + <TooltipPopup side="top">{upload.reason}</TooltipPopup>
7074 + </Tooltip>
7075 + ) : null}
7076 + <Button
7077 + variant="ghost"
7078 + size="icon-xs"
7079 + onClick={() => removeComposerFileFromDraft(file.id)}
7080 + aria-label={`Remove ${file.name}`}
7081 + >
7082 + <XIcon />
7083 + </Button>
7084 + </div>
7085 + );
7086 + })}
7087 + </div>
7088 + )}
7089
7090 <div
7091 className={cn("relative", isComposerResting && "flex min-w-0 items-center gap-1")}
@@ -7153,13 +7149,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
7149 richTextEnabled={settings.composerRichTextEnabled}
7150 literalText={isLiteralPendingAnswer}
7151 isPathQueryActive={isPathQueryActiveStable}
7156 - value={
7157 - isComposerApprovalState
7158 - ? ""
7159 - : activePendingProgress
7160 - ? activePendingProgress.customAnswer
7161 - : prompt
7162 - }
7152 + value={activePendingProgress ? activePendingProgress.customAnswer : prompt}
7153 cursor={composerCursor}
7154 contextRecords={composerContextRecords}
7155 buildContextClipboardFragment={buildContextClipboardFragmentStable}
@@ -7170,7 +7160,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
7160 showMobilePendingAnswerActions && "max-sm:pb-12",
7161 isComposerResting &&
7162 "my-0 max-h-8 min-h-8 overflow-hidden py-0 whitespace-pre! leading-8",
7173 - isComposerApprovalState && "min-h-0",
7163 )}
7164 placeholderClassName={cn(
7165 isComposerResting &&
@@ -7187,7 +7176,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
7176 onPaste={onComposerPasteStable}
7177 placeholder={
7178 isComposerApprovalState
7190 - ? "Resolve this approval request to continue"
7179 + ? "Send a message to decline and redirect the agent"
7180 : activePendingProgress
7181 ? isChoiceOnlyPendingQuestion
7182 ? "Choose an option above"
@@ -7204,7 +7193,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
7193 }
7194 disabled={
7195 isConnecting ||
7207 - isComposerApprovalState ||
7196 projectSelectionRequired ||
7197 isChoiceOnlyPendingQuestion ||
7198 activePendingIsResponding
@@ -7249,7 +7237,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
7237 message={providerInputSubmissionError ?? composerSubmissionError}
7238 />
7239
7252 - {isComposerCollapsedMobile || isComposerApprovalState ? null : (
7240 + {isComposerCollapsedMobile ? null : (
7241 <div
7242 data-chat-composer-footer="true"
7243 data-chat-composer-footer-compact={isComposerFooterCompact ? "true" : "false"}
@@ -7333,7 +7321,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
7321 pendingAction={pendingPrimaryAction}
7322 isRunning={phase === "running"}
7323 canInterrupt={canInterrupt}
7336 - followUpBehavior={settings.followUpBehavior}
7324 + followUpBehavior={followUpBehavior}
7325 canSteer={!isCompacting}
7326 alternateShortcutLabel={shortcutLabelForCommand(
7327 keybindings,
packages/client-runtime/src/state/threadRequests.test.ts
+59 -1
@@ -5,17 +5,75 @@ import {
5 TurnItemId,
6 type OrchestrationV2ThreadProjection,
7 } from "@t3tools/contracts";
8 -import { describe, expect, it } from "vite-plus/test";
8 +import { describe, expect, it, vi } from "vite-plus/test";
9 +import { AsyncResult } from "effect/reactivity";
10 +import * as Cause from "effect/Cause";
11 import { v2Now, v2Projection } from "./orchestrationV2TestFixtures.ts";
12 import {
13 createQuestionHistoryProjector,
14 derivePendingThreadRequests,
15 + declinePendingApprovals,
16 seedUserInputDraftAnswers,
17 + type ApprovalResponder,
18 + type ThreadPendingApproval,
19 } from "./threadRequests.ts";
20
21 const requestId = RuntimeRequestId.make("async-question");
22 const nodeId = NodeId.make("async-question-node");
23
24 +describe("declining approvals before sending", () => {
25 + const approval: ThreadPendingApproval = {
26 + requestId,
27 + requestKind: "command",
28 + createdAt: "2026-10-19T00:00:00Z",
29 + responseCapability: "live",
30 + };
31 + const second: ThreadPendingApproval = {
32 + ...approval,
33 + requestId: RuntimeRequestId.make("second-approval"),
34 + };
35 +
36 + it("declines every pending approval before the send continues", async () => {
37 + let resolve!: (value: Awaited<ReturnType<ApprovalResponder>>) => void;
38 + const firstResponse = new Promise<Awaited<ReturnType<ApprovalResponder>>>((done) => {
39 + resolve = done;
40 + });
41 + const respond = vi.fn<ApprovalResponder>(async (id) =>
42 + id === requestId ? firstResponse : AsyncResult.success(undefined),
43 + );
44 + const send = vi.fn();
45 + const submission = (async () => {
46 + if (await declinePendingApprovals([approval, second], respond)) send();
47 + })();
48 + expect(respond).toHaveBeenCalledWith(requestId, "decline");
49 + expect(send).not.toHaveBeenCalled();
50 + resolve(AsyncResult.success(undefined));
51 + await submission;
52 + expect(respond).toHaveBeenCalledWith(second.requestId, "decline");
53 + expect(send).toHaveBeenCalledOnce();
54 + });
55 +
56 + it.each([AsyncResult.failure(Cause.fail("decline failed")), undefined])(
57 + "does not send when a decline is unsuccessful: %s",
58 + async (response) => {
59 + const send = vi.fn();
60 + if (await declinePendingApprovals([approval], async () => response)) send();
61 + expect(send).not.toHaveBeenCalled();
62 + },
63 + );
64 +
65 + it("skips approvals the provider can no longer answer", async () => {
66 + const respond = vi.fn(async () => AsyncResult.success(undefined));
67 + expect(
68 + await declinePendingApprovals(
69 + [{ ...approval, responseCapability: "not_resumable" }],
70 + respond,
71 + ),
72 + ).toBe(true);
73 + expect(respond).not.toHaveBeenCalled();
74 + });
75 +});
76 +
77 describe("initial user input drafts", () => {
78 const questions = [
79 { id: "editor", initialAnswer: " Proposed commit\n\n" },
packages/client-runtime/src/state/threadRequests.ts
+20
@@ -3,10 +3,30 @@ import type {
3 OrchestrationV2RuntimeRequest,
4 OrchestrationV2UserInputQuestion,
5 ProviderApprovalOption,
6 + ProviderApprovalDecision,
7 ProviderRequestKind,
8 RuntimeRequestId,
9 } from "@t3tools/contracts";
10 import * as DateTime from "effect/DateTime";
11 +import type { AtomCommandResult } from "./runtime.ts";
12 +
13 +export type ApprovalResponder = (
14 + requestId: RuntimeRequestId,
15 + decision: ProviderApprovalDecision,
16 +) => Promise<AtomCommandResult<unknown, unknown> | undefined>;
17 +
18 +/** Declines every approval a redirect replaces; any one still pending would block the agent. */
19 +export async function declinePendingApprovals(
20 + approvals: ReadonlyArray<ThreadPendingApproval>,
21 + respond: ApprovalResponder,
22 +): Promise<boolean> {
23 + for (const approval of approvals) {
24 + // A request the provider can no longer answer has nothing to decline.
25 + if (approval.responseCapability !== "live") continue;
26 + if ((await respond(approval.requestId, "decline"))?._tag !== "Success") return false;
27 + }
28 + return true;
29 +}
30
31 export interface ThreadPendingApproval {
32 readonly requestId: RuntimeRequestId;