Skip to content

Commit a93b03c

Browse files
authored
feat(web): composer stays usable during approvals, and sending declines and redirects (#21503)
1 parent 6a6c84f commit a93b03c

9 files changed

Lines changed: 391 additions & 136 deletions

File tree

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

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,11 @@ export interface ThreadComposerProps {
178178
readonly onStopThread: () => void;
179179
/** Present while the thread's queue is held. */
180180
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>;
182186
readonly onShowUsageLimits: (report: UsageLimitsReport | null) => void;
183187
readonly canSwitchProvider: boolean;
184188
readonly onUpdateModelSelection: (modelSelection: ModelSelection) => void;
@@ -356,6 +360,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
356360
const inputRef = props.editorRef ?? fallbackInputRef;
357361
const [isFocused, setIsFocused] = useState(false);
358362
const pendingPastedTextAttachmentCountRef = useRef(0);
363+
const pendingNativeImagePasteCountRef = useRef(0);
359364
const [pendingPastedTextAttachmentCount, setPendingPastedTextAttachmentCount] = useState(0);
360365
const settingsSheetPresentation = useThreadSettingsSheetPresentation({
361366
editorRef: inputRef,
@@ -599,15 +604,33 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
599604
setComposerEditing(false);
600605
};
601606
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;
603613
if (usageLimitsOffered && isUsageLimitsCommand(draftMessage) && draftAttachments.length === 0) {
604614
if (openUsageLimits()) onChangeDraftMessage("");
605615
return;
606616
}
607617
const threadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
608618
if (inFlightThreadIdsRef.current.has(threadKey)) return;
609619
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));
611634
inFlightThreadIdsRef.current.delete(threadKey);
612635
if (AsyncResult.isFailure(sent)) {
613636
// The composer state already surfaces send errors; only the lock needed releasing.
@@ -915,7 +938,11 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
915938
}}
916939
onSelectionChange={composerMenu.onSelectionChange}
917940
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+
});
919946
}}
920947
onPasteText={(paste) => {
921948
if (isSubmissionLocked) return;

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

Lines changed: 49 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,6 @@ import type {
3939
EnvironmentId,
4040
MessageId,
4141
ModelSelection,
42-
ProviderApprovalDecision,
4342
ProviderInteractionMode,
4443
RuntimeMode,
4544
RuntimeRequestId,
@@ -52,7 +51,11 @@ import {
5251
appendCodexArtifactTemplateUsePrompt,
5352
type CodexArtifactTemplate,
5453
} 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";
5659
import {
5760
presentPendingBackgroundWork,
5861
presentProviderGoal,
@@ -199,6 +202,7 @@ export interface ThreadDetailScreenProps {
199202
| { readonly kind: "failed"; readonly reason: string; readonly onEditTask: () => void }
200203
| null;
201204
readonly activePendingApproval: PendingApproval | null;
205+
readonly activePendingApprovals: ReadonlyArray<PendingApproval>;
202206
readonly respondingApprovalId: RuntimeRequestId | null;
203207
readonly activePendingUserInput: PendingUserInput | null;
204208
readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
@@ -236,16 +240,16 @@ export interface ThreadDetailScreenProps {
236240
readonly onStopThread: () => void;
237241
/** Present while the thread's queue is held. */
238242
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>;
240247
readonly onReconnectEnvironment: () => void;
241248
readonly canSwitchThreadProvider: boolean;
242249
readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => void;
243250
readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
244251
readonly onUpdateThreadInteractionMode: (interactionMode: ProviderInteractionMode) => void;
245-
readonly onRespondToApproval: (
246-
requestId: RuntimeRequestId,
247-
decision: ProviderApprovalDecision,
248-
) => Promise<unknown>;
252+
readonly onRespondToApproval: ApprovalResponder;
249253
readonly onSelectUserInputOption: (
250254
requestId: RuntimeRequestId,
251255
question: ThreadUserInputQuestion,
@@ -1152,12 +1156,37 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
11521156
selectedThreadKey,
11531157
]);
11541158

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+
) => {
11561167
const targetThreadKey = selectedThreadKey;
11571168
const hasUserMessage = selectedThreadFeed.some(
11581169
(entry) => entry.type === "message" && entry.message.role === "user",
11591170
);
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);
11611190
if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
11621191
return messageId;
11631192
}
@@ -1568,7 +1597,11 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
15681597
canOperateThread={props.canOperateThread}
15691598
reportedModelSelection={reportedModelSelection}
15701599
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+
}
15721605
contentMaxWidth={contentMaxWidth}
15731606
connectionState={props.connectionStateLabel}
15741607
environmentLabel={props.environmentLabel}
@@ -1592,7 +1625,12 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
15921625
: null
15931626
}
15941627
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+
}
15961634
canSteerActiveTurn={props.canSteerActiveTurn}
15971635
hidden={composerSlotHidden}
15981636
queuedEdit={

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -932,6 +932,7 @@ function ThreadRouteContent(
932932
: null
933933
}
934934
activePendingApproval={requests.activePendingApproval}
935+
activePendingApprovals={requests.activePendingApprovals}
935936
respondingApprovalId={requests.respondingApprovalId}
936937
activePendingUserInput={requests.activePendingUserInput}
937938
activePendingUserInputDrafts={requests.activePendingUserInputDrafts}

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -371,6 +371,7 @@ export function useSelectedThreadRequests() {
371371

372372
return {
373373
activePendingApproval,
374+
activePendingApprovals,
374375
activePendingUserInput,
375376
activePendingUserInputDrafts,
376377
activePendingUserInputAnswers,

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

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -528,7 +528,10 @@ export function useThreadComposerState() {
528528
scheduleUnusedComposerAttachmentCleanup(draft.attachments);
529529
};
530530

531-
const onSendMessage = async (followUpOverride?: ActiveTurnComposerAction) => {
531+
const onSendMessage = async (
532+
followUpOverride?: ActiveTurnComposerAction,
533+
beforeDispatch?: () => Promise<boolean>,
534+
) => {
532535
if (
533536
selectedThreadShell &&
534537
selectedEnvironmentRuntime?.connectionState === "connected" &&
@@ -645,15 +648,35 @@ export function useThreadComposerState() {
645648
return null;
646649
}
647650

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+
648669
// Resolved here rather than at drain time: the outbox can deliver minutes
649670
// later, and the choice belongs to the moment the user pressed send.
650671
// Steering travels as "auto" so a turn that ends in the meantime degrades
651672
// to a queued run on the server instead of failing the delivery and
652673
// 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;
653676
const followUpAction = resolveComposerDispatchMode({
654677
running: activeThreadBusy && canSteerActiveTurn,
655-
alternateModifier: followUpOverride !== undefined && followUpOverride !== followUpBehavior,
656-
activeTurnDefault: followUpBehavior,
678+
alternateModifier: followUpOverride !== undefined && followUpOverride !== activeTurnDefault,
679+
activeTurnDefault,
657680
});
658681
const setupRunning = [selectedThreadActivityRun?.status, selectedThreadRuntime?.status].some(
659682
(status) => status === "preparing" || status === "starting",

‎apps/web/src/components/ChatView.tsx‎

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,7 @@ import {
9191
import { readPastedComposerContext } from "./composerInlineTokenPaste";
9292
import { isPasteAsTextShortcut } from "@t3tools/client-runtime/text-paste";
9393
import { effectiveSnoozed, threadWokeAt } from "@t3tools/client-runtime/state/thread-settled";
94+
import { declinePendingApprovals } from "@t3tools/client-runtime/state/thread-requests";
9495
import { presentThreadShell } from "@t3tools/client-runtime/state/shell";
9596
import { childThreadInputsTitle } from "@t3tools/client-runtime/state/threads";
9697
import { useAcknowledgeThreadWoke, useThreadActions } from "../hooks/useThreadActions";
@@ -2542,6 +2543,13 @@ export default function ChatView(props: ChatViewProps) {
25422543
composerRef,
25432544
setThreadError,
25442545
});
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]);
25452553
const activeProposedPlan = (() => {
25462554
if (!latestRunSettled) {
25472555
return null;
@@ -6213,6 +6221,9 @@ export default function ChatView(props: ChatViewProps) {
62136221
},
62146222
) => {
62156223
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;
62166227
if (
62176228
usageLimitsOffered &&
62186229
usageLimitsKey !== null &&
@@ -6787,6 +6798,94 @@ export default function ChatView(props: ChatViewProps) {
67876798
);
67886799
return;
67896800
}
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+
}
67906889
if (sendQueuesBehindSetup) {
67916890
setSetupQueueSendThreadKey(activeThreadKey);
67926891
} else {

0 commit comments

Comments
 (0)