Skip to content
TypeScript

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

mariaa93b03c8a5a8
diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx
index f0132833c4f..1df4dcab7e4 100644
--- a/apps/mobile/src/features/threads/ThreadComposer.tsx
+++ b/apps/mobile/src/features/threads/ThreadComposer.tsx
@@ -178,7 +178,11 @@ export interface ThreadComposerProps {
readonly onStopThread: () => void;
/** Present while the thread's queue is held. */
readonly onResumeQueue: (() => Promise<void>) | null;
- readonly onSendMessage: (followUp?: ActiveTurnComposerAction) => Promise<MessageId | null>;
+ /** `stillSendable` reports whether the draft is unchanged after any wait before sending. */
+ readonly onSendMessage: (
+ followUp?: ActiveTurnComposerAction,
+ stillSendable?: () => boolean,
+ ) => Promise<MessageId | null>;
readonly onShowUsageLimits: (report: UsageLimitsReport | null) => void;
readonly canSwitchProvider: boolean;
readonly onUpdateModelSelection: (modelSelection: ModelSelection) => void;
@@ -356,6 +360,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
const inputRef = props.editorRef ?? fallbackInputRef;
const [isFocused, setIsFocused] = useState(false);
const pendingPastedTextAttachmentCountRef = useRef(0);
+ const pendingNativeImagePasteCountRef = useRef(0);
const [pendingPastedTextAttachmentCount, setPendingPastedTextAttachmentCount] = useState(0);
const settingsSheetPresentation = useThreadSettingsSheetPresentation({
editorRef: inputRef,
@@ -599,7 +604,12 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
setComposerEditing(false);
};
const handleSend = async (followUp?: ActiveTurnComposerAction) => {
- if (isSubmissionLocked || pendingPastedTextAttachmentCountRef.current > 0) return;
+ if (
+ isSubmissionLocked ||
+ pendingPastedTextAttachmentCountRef.current > 0 ||
+ pendingNativeImagePasteCountRef.current > 0
+ )
+ return;
if (usageLimitsOffered && isUsageLimitsCommand(draftMessage) && draftAttachments.length === 0) {
if (openUsageLimits()) onChangeDraftMessage("");
return;
@@ -607,7 +617,20 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
const threadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
if (inFlightThreadIdsRef.current.has(threadKey)) return;
inFlightThreadIdsRef.current.add(threadKey);
- const sent = await settlePromise(() => onSendMessage(followUp));
+ const draftAtSend = getComposerDraftSnapshot(composerDraftKey);
+ const stillSendable = () => {
+ const draft = getComposerDraftSnapshot(composerDraftKey);
+ return (
+ pendingPastedTextAttachmentCountRef.current === 0 &&
+ pendingNativeImagePasteCountRef.current === 0 &&
+ draft.text === draftAtSend.text &&
+ draft.attachments.length === draftAtSend.attachments.length &&
+ draft.attachments.every(
+ (attachment, index) => attachment.id === draftAtSend.attachments[index]?.id,
+ )
+ );
+ };
+ const sent = await settlePromise(() => onSendMessage(followUp, stillSendable));
inFlightThreadIdsRef.current.delete(threadKey);
if (AsyncResult.isFailure(sent)) {
// The composer state already surfaces send errors; only the lock needed releasing.
@@ -915,7 +938,11 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
}}
onSelectionChange={composerMenu.onSelectionChange}
onPasteImages={(uris) => {
- if (!isSubmissionLocked) void props.onNativePasteImages(uris);
+ if (isSubmissionLocked) return;
+ pendingNativeImagePasteCountRef.current += 1;
+ void props.onNativePasteImages(uris).finally(() => {
+ pendingNativeImagePasteCountRef.current -= 1;
+ });
}}
onPasteText={(paste) => {
if (isSubmissionLocked) return;
diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
index 85e8dd96183..9741e464444 100644
--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
@@ -39,7 +39,6 @@ import type {
EnvironmentId,
MessageId,
ModelSelection,
- ProviderApprovalDecision,
ProviderInteractionMode,
RuntimeMode,
RuntimeRequestId,
@@ -52,7 +51,11 @@ import {
appendCodexArtifactTemplateUsePrompt,
type CodexArtifactTemplate,
} from "@t3tools/shared/codexArtifactTemplates";
-import type { ThreadUserInputQuestion } from "@t3tools/client-runtime/state/thread-requests";
+import {
+ declinePendingApprovals,
+ type ApprovalResponder,
+ type ThreadUserInputQuestion,
+} from "@t3tools/client-runtime/state/thread-requests";
import {
presentPendingBackgroundWork,
presentProviderGoal,
@@ -199,6 +202,7 @@ export interface ThreadDetailScreenProps {
| { readonly kind: "failed"; readonly reason: string; readonly onEditTask: () => void }
| null;
readonly activePendingApproval: PendingApproval | null;
+ readonly activePendingApprovals: ReadonlyArray<PendingApproval>;
readonly respondingApprovalId: RuntimeRequestId | null;
readonly activePendingUserInput: PendingUserInput | null;
readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
@@ -236,16 +240,16 @@ export interface ThreadDetailScreenProps {
readonly onStopThread: () => void;
/** Present while the thread's queue is held. */
readonly onResumeQueue: (() => Promise<void>) | null;
- readonly onSendMessage: (followUp?: ActiveTurnComposerAction) => Promise<MessageId | null>;
+ readonly onSendMessage: (
+ followUp?: ActiveTurnComposerAction,
+ beforeDispatch?: () => Promise<boolean>,
+ ) => Promise<MessageId | null>;
readonly onReconnectEnvironment: () => void;
readonly canSwitchThreadProvider: boolean;
readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => void;
readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
readonly onUpdateThreadInteractionMode: (interactionMode: ProviderInteractionMode) => void;
- readonly onRespondToApproval: (
- requestId: RuntimeRequestId,
- decision: ProviderApprovalDecision,
- ) => Promise<unknown>;
+ readonly onRespondToApproval: ApprovalResponder;
readonly onSelectUserInputOption: (
requestId: RuntimeRequestId,
question: ThreadUserInputQuestion,
@@ -1152,12 +1156,37 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
selectedThreadKey,
]);
- const handleSendMessage = async (followUp?: ActiveTurnComposerAction) => {
+ const activePendingApprovalsRef = useRef(props.activePendingApprovals);
+ useLayoutEffect(() => {
+ activePendingApprovalsRef.current = props.activePendingApprovals;
+ }, [props.activePendingApprovals]);
+ const handleSendMessage = async (
+ followUp?: ActiveTurnComposerAction,
+ stillSendable?: () => boolean,
+ ) => {
const targetThreadKey = selectedThreadKey;
const hasUserMessage = selectedThreadFeed.some(
(entry) => entry.type === "message" && entry.message.role === "user",
);
- const messageId = await props.onSendMessage(followUp);
+ // Runs only once the send path has validated the draft and is about to deliver it, so an
+ // empty submit, a queued-message edit, or `/feedback` leaves approvals alone.
+ const approvalsToDecline = props.activePendingApprovals;
+ const declineBeforeDispatch =
+ approvalsToDecline.length > 0 && props.activePendingUserInput === null
+ ? async () =>
+ props.respondingApprovalId === null &&
+ (await declinePendingApprovals(approvalsToDecline, props.onRespondToApproval)) &&
+ selectedThreadKeyRef.current === targetThreadKey &&
+ // A draft edited or pasted into during the decline isn't what the user sent.
+ stillSendable?.() !== false &&
+ // An approval that arrived during the decline would block the redirect; the draft
+ // stays so the next send declines it too.
+ !activePendingApprovalsRef.current.some(
+ (approval) =>
+ !approvalsToDecline.some((declined) => declined.requestId === approval.requestId),
+ )
+ : undefined;
+ const messageId = await props.onSendMessage(followUp, declineBeforeDispatch);
if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
return messageId;
}
@@ -1568,7 +1597,11 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
canOperateThread={props.canOperateThread}
reportedModelSelection={reportedModelSelection}
editorRef={composerEditorRef}
- placeholder="Ask the repo agent, or run a command…"
+ placeholder={
+ props.activePendingApproval
+ ? "Send a message to decline and redirect the agent"
+ : "Ask the repo agent, or run a command…"
+ }
contentMaxWidth={contentMaxWidth}
connectionState={props.connectionStateLabel}
environmentLabel={props.environmentLabel}
@@ -1592,7 +1625,12 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
: null
}
draftKey={props.composerDraftKey ?? undefined}
- followUpBehavior={props.followUpBehavior}
+ followUpBehavior={
+ props.activePendingApprovals.length > 0 &&
+ props.activePendingUserInput === null
+ ? "steer"
+ : props.followUpBehavior
+ }
canSteerActiveTurn={props.canSteerActiveTurn}
hidden={composerSlotHidden}
queuedEdit={
diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
index 0abb16df645..e134283ae54 100644
--- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
@@ -932,6 +932,7 @@ function ThreadRouteContent(
: null
}
activePendingApproval={requests.activePendingApproval}
+ activePendingApprovals={requests.activePendingApprovals}
respondingApprovalId={requests.respondingApprovalId}
activePendingUserInput={requests.activePendingUserInput}
activePendingUserInputDrafts={requests.activePendingUserInputDrafts}
diff --git a/apps/mobile/src/state/use-selected-thread-requests.ts b/apps/mobile/src/state/use-selected-thread-requests.ts
index ac58170cd0d..98bec975332 100644
--- a/apps/mobile/src/state/use-selected-thread-requests.ts
+++ b/apps/mobile/src/state/use-selected-thread-requests.ts
@@ -371,6 +371,7 @@ export function useSelectedThreadRequests() {
return {
activePendingApproval,
+ activePendingApprovals,
activePendingUserInput,
activePendingUserInputDrafts,
activePendingUserInputAnswers,
diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts
index f40da862253..ebdf9769d46 100644
--- a/apps/mobile/src/state/use-thread-composer-state.ts
+++ b/apps/mobile/src/state/use-thread-composer-state.ts
@@ -528,7 +528,10 @@ export function useThreadComposerState() {
scheduleUnusedComposerAttachmentCleanup(draft.attachments);
};
- const onSendMessage = async (followUpOverride?: ActiveTurnComposerAction) => {
+ const onSendMessage = async (
+ followUpOverride?: ActiveTurnComposerAction,
+ beforeDispatch?: () => Promise<boolean>,
+ ) => {
if (
selectedThreadShell &&
selectedEnvironmentRuntime?.connectionState === "connected" &&
@@ -645,15 +648,35 @@ export function useThreadComposerState() {
return null;
}
+ if (beforeDispatch !== undefined) {
+ if (!(await beforeDispatch())) return null;
+ // A context paste still landing, or any draft or settings change while approvals were
+ // declined, means this snapshot is no longer what the user sent.
+ if (appAtomRegistry.get(composerContextImportsAtom)[threadKey]) return null;
+ const current = getComposerDraftSnapshot(threadKey);
+ if (
+ current.text !== draft.text ||
+ JSON.stringify(current.context) !== JSON.stringify(draft.context) ||
+ JSON.stringify(current.modelSelection) !== JSON.stringify(draft.modelSelection) ||
+ current.runtimeMode !== draft.runtimeMode ||
+ current.interactionMode !== draft.interactionMode ||
+ current.attachments.length !== attachments.length ||
+ current.attachments.some((attachment, index) => attachment.id !== attachments[index]?.id)
+ )
+ return null;
+ }
+
// Resolved here rather than at drain time: the outbox can deliver minutes
// later, and the choice belongs to the moment the user pressed send.
// Steering travels as "auto" so a turn that ends in the meantime degrades
// to a queued run on the server instead of failing the delivery and
// bouncing the message back into the draft.
+ // A redirect declined approvals to steer the waiting turn, not to queue behind it.
+ const activeTurnDefault = beforeDispatch !== undefined ? "steer" : followUpBehavior;
const followUpAction = resolveComposerDispatchMode({
running: activeThreadBusy && canSteerActiveTurn,
- alternateModifier: followUpOverride !== undefined && followUpOverride !== followUpBehavior,
- activeTurnDefault: followUpBehavior,
+ alternateModifier: followUpOverride !== undefined && followUpOverride !== activeTurnDefault,
+ activeTurnDefault,
});
const setupRunning = [selectedThreadActivityRun?.status, selectedThreadRuntime?.status].some(
(status) => status === "preparing" || status === "starting",
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index 1f9eb813a45..f8b37133d46 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -91,6 +91,7 @@ import {
import { readPastedComposerContext } from "./composerInlineTokenPaste";
import { isPasteAsTextShortcut } from "@t3tools/client-runtime/text-paste";
import { effectiveSnoozed, threadWokeAt } from "@t3tools/client-runtime/state/thread-settled";
+import { declinePendingApprovals } from "@t3tools/client-runtime/state/thread-requests";
import { presentThreadShell } from "@t3tools/client-runtime/state/shell";
import { childThreadInputsTitle } from "@t3tools/client-runtime/state/threads";
import { useAcknowledgeThreadWoke, useThreadActions } from "../hooks/useThreadActions";
@@ -2542,6 +2543,13 @@ export default function ChatView(props: ChatViewProps) {
composerRef,
setThreadError,
});
+ // A send awaits uploads before it declines, so it reads the approvals pending by then.
+ const pendingApprovalsRef = useRef(pendingApprovals);
+ const respondingRequestIdsRef = useRef(respondingRequestIds);
+ useLayoutEffect(() => {
+ pendingApprovalsRef.current = pendingApprovals;
+ respondingRequestIdsRef.current = respondingRequestIds;
+ }, [pendingApprovals, respondingRequestIds]);
const activeProposedPlan = (() => {
if (!latestRunSettled) {
return null;
@@ -6213,6 +6221,9 @@ export default function ChatView(props: ChatViewProps) {
},
) => {
e?.preventDefault();
+ // What the user pressed send on; uploads below can take a while, and a redirect must not
+ // decline approvals for a draft that changed meanwhile.
+ const promptAtSend = promptRef.current;
if (
usageLimitsOffered &&
usageLimitsKey !== null &&
@@ -6787,6 +6798,94 @@ export default function ChatView(props: ChatViewProps) {
);
return;
}
+ // A message sent while approvals are pending redirects the agent. They are declined only
+ // here, after everything above has accepted the send, so local commands and rejected
+ // drafts leave them alone. After navigating away during an upload, the shown approvals
+ // are another thread's, so this send leaves them alone too.
+ const approvalsToDecline =
+ currentRouteThreadKeyRef.current === routeThreadKey
+ ? pendingApprovalsRef.current.filter((approval) =>
+ sendCtx?.shownPendingApprovalIds.includes(approval.requestId),
+ )
+ : [];
+ if (approvalsToDecline.length > 0) {
+ // A draft edited since send, or a paste still landing in it, is no longer the message
+ // the user sent.
+ const attachmentIdsAtSend = composerAttachmentsSnapshot.map((attachment) => attachment.id);
+ // A direct annotation send writes its image and reference into the draft as it sends,
+ // so the live draft may still lack them; anything else differing is a real edit.
+ const annotationImageId = directAnnotation?.image?.id;
+ const attachmentIdsBeforeAnnotation = attachmentIdsAtSend.filter(
+ (id) => id !== annotationImageId,
+ );
+ const sameIds = (left: ReadonlyArray<string>, right: ReadonlyArray<string>) =>
+ left.length === right.length && left.every((id, index) => id === right[index]);
+ const draftChangedSinceSend = () => {
+ if (composerRef.current?.hasPendingAttachments() === true) return true;
+ const sendContext = composerRef.current?.getSendContext();
+ const attachmentIds = sendContext
+ ? [...sendContext.images, ...sendContext.files].map((attachment) => attachment.id)
+ : attachmentIdsAtSend;
+ const promptUnchanged =
+ promptRef.current === promptAtSend || promptRef.current === promptForSend;
+ const attachmentsUnchanged =
+ sameIds(attachmentIds, attachmentIdsAtSend) ||
+ (annotationImageId !== undefined &&
+ sameIds(attachmentIds, attachmentIdsBeforeAnnotation));
+ return !promptUnchanged || !attachmentsUnchanged;
+ };
+ const draftBeforeDecline = useComposerDraftStore
+ .getState()
+ .getComposerDraft(composerDraftTarget);
+ const changedBeforeDecline = draftChangedSinceSend();
+ const pendingIdsBeforeDecline = pendingApprovalsRef.current.map(
+ (approval) => approval.requestId,
+ );
+ const approvalResponding = approvalsToDecline.some((approval) =>
+ respondingRequestIdsRef.current.includes(approval.requestId),
+ );
+ const declined =
+ !changedBeforeDecline &&
+ !approvalResponding &&
+ (await declinePendingApprovals(approvalsToDecline, onRespondToApprovalStable).catch(
+ () => false,
+ ));
+ const draftChanged =
+ changedBeforeDecline ||
+ draftChangedSinceSend() ||
+ useComposerDraftStore.getState().getComposerDraft(composerDraftTarget) !==
+ draftBeforeDecline;
+ // An approval that arrived during the decline would block the redirect; keep the draft so
+ // the next send declines it too.
+ const approvalArrived = pendingApprovalsRef.current.some(
+ (approval) => !pendingIdsBeforeDecline.includes(approval.requestId),
+ );
+ if (
+ !declined ||
+ draftChanged ||
+ approvalArrived ||
+ currentRouteThreadKeyRef.current !== routeThreadKey
+ ) {
+ sendInFlightRef.current = false;
+ setDockedDraftHeroThreadKey((currentThreadKey) =>
+ currentThreadKey === activeThreadKey ? null : currentThreadKey,
+ );
+ if (draftChanged || approvalResponding || (declined && approvalArrived)) {
+ toastManager.add({
+ type: "info",
+ title: draftChanged
+ ? declined
+ ? "Approval declined. Your message changed, so it wasn't sent."
+ : "Your message changed, so it wasn't sent."
+ : approvalResponding
+ ? "An approval is already being answered, so your message wasn't sent."
+ : "Another approval arrived, so your message wasn't sent.",
+ description: "Send again when it's ready.",
+ });
+ }
+ return;
+ }
+ }
if (sendQueuesBehindSetup) {
setSetupQueueSendThreadKey(activeThreadKey);
} else {
diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx
index f600b831c53..ad8c6603ec1 100644
--- a/apps/web/src/components/chat/ChatComposer.tsx
+++ b/apps/web/src/components/chat/ChatComposer.tsx
@@ -1489,6 +1489,7 @@ export interface ChatComposerHandle {
selectedProviderModels: ReadonlyArray<ServerProvider["models"][number]>;
interactionMode: ProviderInteractionMode;
interactionModeEnabled: boolean;
+ shownPendingApprovalIds: ReadonlyArray<RuntimeRequestId>;
};
validateProviderInput: (providerInput: string) => boolean;
setMultipleModelSelections: (selections: ReadonlyArray<ModelSelection>) => void;
@@ -2828,7 +2829,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const nonPersistedComposerImageIdSet = new Set(nonPersistedComposerImageIds);
const isComposerApprovalState = activePendingApproval !== null;
- const composerSuggestionsVisible = composerMenuOpen && !isComposerApprovalState;
+ // A send declines the approvals shown here to redirect the agent, so it steers the waiting
+ // turn instead of queueing behind it. Approvals the typing guard holds stay unseen and pending.
+ const followUpBehavior = pendingApprovals.some(
+ (approval) => !heldRequestIds.has(approval.requestId),
+ )
+ ? "steer"
+ : settings.followUpBehavior;
+ const composerSuggestionsVisible = composerMenuOpen;
const composerSuggestionListVisible = composerSuggestionsVisible && composerMenuItems.length > 0;
const activePendingUserInput = pendingUserInputs[0] ?? null;
const isChoiceOnlyPendingQuestion =
@@ -2837,7 +2845,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
isComposerApprovalState ||
pendingUserInputs.length > 0 ||
(!isComposerCollapsedMobile && showPlanFollowUpPrompt && activeProposedPlan !== null);
- const showCollapsedMobilePromptRow = isComposerCollapsedMobile && !isComposerApprovalState;
+ const showCollapsedMobilePromptRow = isComposerCollapsedMobile;
const showComposerAttachAction =
fileStagingLimit !== null &&
(!activePendingProgress ||
@@ -4057,7 +4065,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
resolveComposerDispatchMode({
running: phase === "running",
alternateModifier: false,
- activeTurnDefault: settings.followUpBehavior,
+ activeTurnDefault: followUpBehavior,
canSteer: !isCompacting,
}),
submissionIntent,
@@ -4080,7 +4088,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
resolveComposerDispatchMode({
running: phase === "running",
alternateModifier: event.metaKey || event.ctrlKey,
- activeTurnDefault: settings.followUpBehavior,
+ activeTurnDefault: followUpBehavior,
canSteer: !isCompacting,
}),
);
@@ -4092,13 +4100,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
resolveComposerDispatchMode({
running: phase === "running",
alternateModifier: false,
- activeTurnDefault: settings.followUpBehavior,
+ activeTurnDefault: followUpBehavior,
canSteer: !isCompacting,
}),
);
};
const submitCitationAndSendStable = useStableCallback(submitCitationAndSend);
- // A question or approval took the editor while a citation comment was
+ // A question took the editor while a citation comment was
// unsaved. Keep the comment in the prompt that comes back afterward.
const saveCitationDraftToPrompt = (replacedValue: string, savedValue: string) => {
if (replacedValue !== prompt) return;
@@ -4174,7 +4182,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
if (event.shiftKey || event.altKey || event.metaKey || event.ctrlKey || event.isComposing) {
return false;
}
- if (isComposerApprovalState || pendingUserInputs.length > 0) return false;
+ if (pendingUserInputs.length > 0) return false;
if (
composerImagesRef.current.length > 0 ||
composerFilesRef.current.length > 0 ||
@@ -4256,7 +4264,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
resolveComposerDispatchMode({
running: phase === "running",
alternateModifier: submissionIntent === "alternate",
- activeTurnDefault: settings.followUpBehavior,
+ activeTurnDefault: followUpBehavior,
canSteer: !isCompacting,
}),
submissionIntent,
@@ -5375,11 +5383,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
if (isCommandPaletteOpen() || isRevertingCheckpoint) {
return;
}
- if (pendingUserInputs.length > 0 && !isComposerApprovalState) {
+ if (pendingUserInputs.length > 0) {
setIsStashMenuOpen((open) => !open);
return;
}
- if (isComposerApprovalState || projectSelectionRequired || activePendingProgress !== null) {
+ if (projectSelectionRequired || activePendingProgress !== null) {
return;
}
void stashCurrentPromptStable();
@@ -5388,7 +5396,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
return () => window.removeEventListener("keydown", handler, true);
}, [
activePendingProgress,
- isComposerApprovalState,
isComposerModelPickerOpen,
keybindings,
pendingUserInputs.length,
@@ -5427,7 +5434,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
!options?.skipImageInlineChip &&
(options?.selection !== undefined ||
isConnecting ||
- isComposerApprovalState ||
pendingUserInputs.length > 0 ||
projectSelectionRequired ||
stripInlineContextReferences(promptRef.current).trim().length > 0);
@@ -5750,7 +5756,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
if (
text.length === 0 ||
isConnecting ||
- isComposerApprovalState ||
activePendingIsResponding ||
(pendingUserInputs.length > 0 && !activePendingProgress?.activeQuestion) ||
projectSelectionRequired ||
@@ -5980,7 +5985,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const canAnswer =
canOperateThread &&
!isConnecting &&
- !isComposerApprovalState &&
!activePendingIsResponding &&
activePendingProgress?.activeQuestion?.allowCustomAnswer !== false;
const text = `${records
@@ -6169,7 +6173,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
stepReasoningEffort: (direction) => {
if (
noProviderAvailable ||
- isComposerApprovalState ||
pendingUserInputs.length > 0 ||
// A queued-message edit draft is discarded when the edit ends.
isEditingQueuedMessage
@@ -6298,6 +6301,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
},
getSendContext: () => ({
answeringPendingUserInput: activePendingProgress !== null,
+ shownPendingApprovalIds: pendingApprovals
+ .map((approval) => approval.requestId)
+ .filter((requestId) => !heldRequestIds.has(requestId)),
prompt: promptRef.current,
images: composerImagesRef.current,
files: composerFilesRef.current,
@@ -6348,6 +6354,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
isEditingQueuedMessage,
composerCursor,
activePendingProgress,
+ pendingApprovals,
+ heldRequestIds,
composerTerminalContexts,
insertComposerDraftTerminalContext,
insertComposerTextStable,
@@ -6362,7 +6370,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
environmentId,
primaryEnvironmentId,
isConnecting,
- isComposerApprovalState,
isChoiceOnlyPendingQuestion,
isLiteralPendingAnswer,
pendingUserInputs.length,
@@ -6584,15 +6591,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
</ComposerBanner.Attachment>
) : null}
</ComposerBanner.Column>
- {!isComposerApprovalState ? (
- <ComposerStashBadge
- count={stashQueue.length}
- menuOpen={isStashMenuOpen}
- pulseKey={stashPulse.key}
- pulsing={stashPulse.active}
- onToggleMenu={toggleStashMenuStable}
- />
- ) : null}
+ <ComposerStashBadge
+ count={stashQueue.length}
+ menuOpen={isStashMenuOpen}
+ pulseKey={stashPulse.key}
+ pulsing={stashPulse.active}
+ onToggleMenu={toggleStashMenuStable}
+ />
</ComposerBanner.Dock>
<div className="relative">
<ComposerSurface.Main
@@ -6670,12 +6675,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
className={cn(
"relative px-3 pb-2 sm:px-4",
"pt-3.5 sm:pt-4",
- isComposerApprovalState && "pb-3 sm:pb-4",
isComposerCollapsedMobile && "hidden",
isComposerResting && "py-2 sm:py-2",
)}
>
- {isStashMenuOpen && !composerMenuOpen && !isComposerApprovalState && (
+ {isStashMenuOpen && !composerMenuOpen && (
<ComposerCommandMenuLayer anchor={composerMenuAnchor}>
<ComposerStashMenu
composerFormRef={composerFormRef}
@@ -6720,7 +6724,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
)}
{!isComposerCollapsedMobile &&
- !isComposerApprovalState &&
pendingUserInputs.length === 0 &&
editingQueuedAttachments !== null &&
editingQueuedAttachments.length > 0 && (
@@ -6756,7 +6759,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
)}
{!isComposerCollapsedMobile &&
- !isComposerApprovalState &&
(uncommittedSnapShotIds.length > 0 ||
composerVideos.length > 0 ||
expandedComposerImages.length > 0) && (
@@ -7013,83 +7015,77 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
</div>
)}
- {!isComposerCollapsedMobile &&
- !isComposerApprovalState &&
- composerOtherFiles.length > 0 && (
- <div className="mb-3 flex flex-col gap-1">
- {composerOtherFiles.map((file) => {
- const fileCanUpload =
- supportsAttachmentUploads &&
- maxFileAttachmentBytes !== null &&
- file.sizeBytes <= maxFileAttachmentBytes;
- const upload = fileCanUpload ? uploadsByImageId[file.id] : undefined;
- const needsReattach = composerFileNeedsReattach(file);
- const canReattachFile =
- fileStagingLimit !== null && file.sizeBytes <= fileStagingLimit;
- return (
- <div
- key={file.id}
- className="flex min-w-0 items-center gap-2 py-1 text-sm text-foreground"
+ {!isComposerCollapsedMobile && composerOtherFiles.length > 0 && (
+ <div className="mb-3 flex flex-col gap-1">
+ {composerOtherFiles.map((file) => {
+ const fileCanUpload =
+ supportsAttachmentUploads &&
+ maxFileAttachmentBytes !== null &&
+ file.sizeBytes <= maxFileAttachmentBytes;
+ const upload = fileCanUpload ? uploadsByImageId[file.id] : undefined;
+ const needsReattach = composerFileNeedsReattach(file);
+ const canReattachFile =
+ fileStagingLimit !== null && file.sizeBytes <= fileStagingLimit;
+ return (
+ <div
+ key={file.id}
+ className="flex min-w-0 items-center gap-2 py-1 text-sm text-foreground"
+ >
+ <PierreEntryIcon pathValue={file.name} kind="file" theme={resolvedTheme} />
+ <button
+ type="button"
+ disabled={needsReattach}
+ className="min-w-0 flex-1 truncate text-left hover:underline focus-visible:outline-2"
+ onClick={() => setPreviewFileId(file.id)}
>
- <PierreEntryIcon
- pathValue={file.name}
- kind="file"
- theme={resolvedTheme}
- />
- <button
- type="button"
- disabled={needsReattach}
- className="min-w-0 flex-1 truncate text-left hover:underline focus-visible:outline-2"
- onClick={() => setPreviewFileId(file.id)}
- >
- {file.name}
- </button>
- <span className="shrink-0 text-xs text-secondary-label">
- {needsReattach
- ? canReattachFile
- ? "Attach again"
- : "Remove to send"
- : upload?.status === "uploading"
- ? formatAttachmentUploadProgress(upload.progress)
- : formatAttachmentSize(file.sizeBytes)}
- </span>
- {!needsReattach && upload?.status === "failed" ? (
- <Tooltip>
- <TooltipTrigger
- render={
- <Button
- variant="ghost"
- size="icon-xs"
- onClick={() =>
- retryAttachmentUpload({
- environmentId,
- image: file,
- draftTarget: attachmentDraftTarget,
- })
- }
- disabled={!canOperateThread}
- aria-label={`Retry upload for ${file.name}`}
- />
- }
- >
- <RefreshIcon />
- </TooltipTrigger>
- <TooltipPopup side="top">{upload.reason}</TooltipPopup>
- </Tooltip>
- ) : null}
- <Button
- variant="ghost"
- size="icon-xs"
- onClick={() => removeComposerFileFromDraft(file.id)}
- aria-label={`Remove ${file.name}`}
- >
- <XIcon />
- </Button>
- </div>
- );
- })}
- </div>
- )}
+ {file.name}
+ </button>
+ <span className="shrink-0 text-xs text-secondary-label">
+ {needsReattach
+ ? canReattachFile
+ ? "Attach again"
+ : "Remove to send"
+ : upload?.status === "uploading"
+ ? formatAttachmentUploadProgress(upload.progress)
+ : formatAttachmentSize(file.sizeBytes)}
+ </span>
+ {!needsReattach && upload?.status === "failed" ? (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ onClick={() =>
+ retryAttachmentUpload({
+ environmentId,
+ image: file,
+ draftTarget: attachmentDraftTarget,
+ })
+ }
+ disabled={!canOperateThread}
+ aria-label={`Retry upload for ${file.name}`}
+ />
+ }
+ >
+ <RefreshIcon />
+ </TooltipTrigger>
+ <TooltipPopup side="top">{upload.reason}</TooltipPopup>
+ </Tooltip>
+ ) : null}
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ onClick={() => removeComposerFileFromDraft(file.id)}
+ aria-label={`Remove ${file.name}`}
+ >
+ <XIcon />
+ </Button>
+ </div>
+ );
+ })}
+ </div>
+ )}
<div
className={cn("relative", isComposerResting && "flex min-w-0 items-center gap-1")}
@@ -7153,13 +7149,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
richTextEnabled={settings.composerRichTextEnabled}
literalText={isLiteralPendingAnswer}
isPathQueryActive={isPathQueryActiveStable}
- value={
- isComposerApprovalState
- ? ""
- : activePendingProgress
- ? activePendingProgress.customAnswer
- : prompt
- }
+ value={activePendingProgress ? activePendingProgress.customAnswer : prompt}
cursor={composerCursor}
contextRecords={composerContextRecords}
buildContextClipboardFragment={buildContextClipboardFragmentStable}
@@ -7170,7 +7160,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
showMobilePendingAnswerActions && "max-sm:pb-12",
isComposerResting &&
"my-0 max-h-8 min-h-8 overflow-hidden py-0 whitespace-pre! leading-8",
- isComposerApprovalState && "min-h-0",
)}
placeholderClassName={cn(
isComposerResting &&
@@ -7187,7 +7176,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
onPaste={onComposerPasteStable}
placeholder={
isComposerApprovalState
- ? "Resolve this approval request to continue"
+ ? "Send a message to decline and redirect the agent"
: activePendingProgress
? isChoiceOnlyPendingQuestion
? "Choose an option above"
@@ -7204,7 +7193,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
}
disabled={
isConnecting ||
- isComposerApprovalState ||
projectSelectionRequired ||
isChoiceOnlyPendingQuestion ||
activePendingIsResponding
@@ -7249,7 +7237,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
message={providerInputSubmissionError ?? composerSubmissionError}
/>
- {isComposerCollapsedMobile || isComposerApprovalState ? null : (
+ {isComposerCollapsedMobile ? null : (
<div
data-chat-composer-footer="true"
data-chat-composer-footer-compact={isComposerFooterCompact ? "true" : "false"}
@@ -7333,7 +7321,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
pendingAction={pendingPrimaryAction}
isRunning={phase === "running"}
canInterrupt={canInterrupt}
- followUpBehavior={settings.followUpBehavior}
+ followUpBehavior={followUpBehavior}
canSteer={!isCompacting}
alternateShortcutLabel={shortcutLabelForCommand(
keybindings,
diff --git a/packages/client-runtime/src/state/threadRequests.test.ts b/packages/client-runtime/src/state/threadRequests.test.ts
index 50a46817baf..1d3db9ce27d 100644
--- a/packages/client-runtime/src/state/threadRequests.test.ts
+++ b/packages/client-runtime/src/state/threadRequests.test.ts
@@ -5,17 +5,75 @@ import {
TurnItemId,
type OrchestrationV2ThreadProjection,
} from "@t3tools/contracts";
-import { describe, expect, it } from "vite-plus/test";
+import { describe, expect, it, vi } from "vite-plus/test";
+import { AsyncResult } from "effect/reactivity";
+import * as Cause from "effect/Cause";
import { v2Now, v2Projection } from "./orchestrationV2TestFixtures.ts";
import {
createQuestionHistoryProjector,
derivePendingThreadRequests,
+ declinePendingApprovals,
seedUserInputDraftAnswers,
+ type ApprovalResponder,
+ type ThreadPendingApproval,
} from "./threadRequests.ts";
const requestId = RuntimeRequestId.make("async-question");
const nodeId = NodeId.make("async-question-node");
+describe("declining approvals before sending", () => {
+ const approval: ThreadPendingApproval = {
+ requestId,
+ requestKind: "command",
+ createdAt: "2026-10-19T00:00:00Z",
+ responseCapability: "live",
+ };
+ const second: ThreadPendingApproval = {
+ ...approval,
+ requestId: RuntimeRequestId.make("second-approval"),
+ };
+
+ it("declines every pending approval before the send continues", async () => {
+ let resolve!: (value: Awaited<ReturnType<ApprovalResponder>>) => void;
+ const firstResponse = new Promise<Awaited<ReturnType<ApprovalResponder>>>((done) => {
+ resolve = done;
+ });
+ const respond = vi.fn<ApprovalResponder>(async (id) =>
+ id === requestId ? firstResponse : AsyncResult.success(undefined),
+ );
+ const send = vi.fn();
+ const submission = (async () => {
+ if (await declinePendingApprovals([approval, second], respond)) send();
+ })();
+ expect(respond).toHaveBeenCalledWith(requestId, "decline");
+ expect(send).not.toHaveBeenCalled();
+ resolve(AsyncResult.success(undefined));
+ await submission;
+ expect(respond).toHaveBeenCalledWith(second.requestId, "decline");
+ expect(send).toHaveBeenCalledOnce();
+ });
+
+ it.each([AsyncResult.failure(Cause.fail("decline failed")), undefined])(
+ "does not send when a decline is unsuccessful: %s",
+ async (response) => {
+ const send = vi.fn();
+ if (await declinePendingApprovals([approval], async () => response)) send();
+ expect(send).not.toHaveBeenCalled();
+ },
+ );
+
+ it("skips approvals the provider can no longer answer", async () => {
+ const respond = vi.fn(async () => AsyncResult.success(undefined));
+ expect(
+ await declinePendingApprovals(
+ [{ ...approval, responseCapability: "not_resumable" }],
+ respond,
+ ),
+ ).toBe(true);
+ expect(respond).not.toHaveBeenCalled();
+ });
+});
+
describe("initial user input drafts", () => {
const questions = [
{ id: "editor", initialAnswer: " Proposed commit\n\n" },
diff --git a/packages/client-runtime/src/state/threadRequests.ts b/packages/client-runtime/src/state/threadRequests.ts
index 20dacefca5b..3735869edb6 100644
--- a/packages/client-runtime/src/state/threadRequests.ts
+++ b/packages/client-runtime/src/state/threadRequests.ts
@@ -3,10 +3,30 @@ import type {
OrchestrationV2RuntimeRequest,
OrchestrationV2UserInputQuestion,
ProviderApprovalOption,
+ ProviderApprovalDecision,
ProviderRequestKind,
RuntimeRequestId,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
+import type { AtomCommandResult } from "./runtime.ts";
+
+export type ApprovalResponder = (
+ requestId: RuntimeRequestId,
+ decision: ProviderApprovalDecision,
+) => Promise<AtomCommandResult<unknown, unknown> | undefined>;
+
+/** Declines every approval a redirect replaces; any one still pending would block the agent. */
+export async function declinePendingApprovals(
+ approvals: ReadonlyArray<ThreadPendingApproval>,
+ respond: ApprovalResponder,
+): Promise<boolean> {
+ for (const approval of approvals) {
+ // A request the provider can no longer answer has nothing to decline.
+ if (approval.responseCapability !== "live") continue;
+ if ((await respond(approval.requestId, "decline"))?._tag !== "Success") return false;
+ }
+ return true;
+}
export interface ThreadPendingApproval {
readonly requestId: RuntimeRequestId;