The best way to control Claude Code, Codex and more from any computer or phone
fix(web): preserve typed question answers when Stop cancels a turn (#23617)
Julius Marminge committed
Nov 11, 2026 at 16:01 UTC
94f7984d2c06617903dfbcaac00d423cec14e8de
8 files changed
+174
-53
apps/web/src/components/chat/ComposerPendingUserInputPanel.navigation.browser.test.tsx
+4
-1
@@ -255,7 +255,10 @@ it("isolates drafts by environment, thread and request and discards only resolve
255
makeThreadRequestsResolvedAnnouncer(
256
environmentId,
257
threadRef.threadId,
258
- )([RuntimeRequestId.make("second")]),
258
+ )([
259
+ { id: RuntimeRequestId.make("first"), status: "resolved" },
260
+ { id: RuntimeRequestId.make("second"), status: "pending" },
261
+ ]),
262
);
263
for (const [index, scope] of scopes.entries()) {
264
await show(scope);
apps/web/src/components/chat/usePendingThreadRequests.ts
+2
-23
@@ -10,8 +10,6 @@ import {
10
} from "@t3tools/contracts";
11
import {
12
derivePendingThreadRequests,
13
- onThreadRequestsResolved,
14
- pruneResolvedUserInputDrafts,
13
seedUserInputDraftAnswers,
14
userInputDraftKey,
15
} from "@t3tools/client-runtime/state/thread-requests";
@@ -19,7 +17,6 @@ import {
17
isAtomCommandInterrupted,
18
squashAtomCommandFailure,
19
} from "@t3tools/client-runtime/state/runtime";
22
-import { create } from "zustand";
20
import { useRef, useState, type RefObject, type SetStateAction } from "react";
21
import { useShallow } from "zustand/react/shallow";
22
import { type DraftId, useComposerDraftStore } from "../../composerDraftStore";
@@ -39,6 +36,8 @@ import {
36
} from "../../pendingUserInput";
37
import {
38
questionAttachmentDraftId,
39
+ usePendingUserInputAnswers,
40
+ usePendingUserInputQuestionIndex,
41
useQuestionAttachmentPreparation,
42
} from "../../questionAttachments";
43
import {
@@ -55,30 +54,10 @@ import { toastManager } from "../ui/toast";
54
import type { ChatComposerHandle } from "./ChatComposer";
55
56
const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnswer> = {};
58
-const usePendingUserInputAnswers = create<
59
- Record<string, Record<string, PendingUserInputDraftAnswer>>
60
->(() => ({}));
61
-const usePendingUserInputQuestionIndex = create<Record<string, number>>(() => ({}));
57
const NO_PENDING_REQUESTS = { approvals: [], userInputs: [] } as const;
58
const NO_PENDING_APPROVALS: ReturnType<typeof derivePendingApprovals> = [];
59
const NO_PENDING_USER_INPUTS: ReturnType<typeof derivePendingUserInputs> = [];
60
66
-// Resolution can come from anywhere: another device, an interrupt, the turn
67
-// ending, or a thread that is not open. Question attachment drafts are pruned
68
-// by questionAttachments.ts, which owns them.
69
-onThreadRequestsResolved(({ environmentId, threadId, pendingRequestIds }) => {
70
- usePendingUserInputAnswers.setState(
71
- (existing) =>
72
- pruneResolvedUserInputDrafts(existing, environmentId, threadId, pendingRequestIds),
73
- true,
74
- );
75
- usePendingUserInputQuestionIndex.setState(
76
- (existing) =>
77
- pruneResolvedUserInputDrafts(existing, environmentId, threadId, pendingRequestIds),
78
- true,
79
- );
80
-});
81
-
61
function makePendingCustomAnswerSetter(input: {
62
readonly activePendingUserInput: PendingUserInput | null;
63
readonly activePendingRequestKey: string;
apps/web/src/questionAttachments.test.ts
+55
-2
@@ -1,13 +1,20 @@
1
-import { makeThreadRequestsResolvedAnnouncer } from "@t3tools/client-runtime/state/thread-requests";
1
+import {
2
+ makeThreadRequestsResolvedAnnouncer,
3
+ userInputDraftKey,
4
+} from "@t3tools/client-runtime/state/thread-requests";
5
import { ApprovalRequestId, EnvironmentId, RuntimeRequestId, ThreadId } from "@t3tools/contracts";
6
+import { threadContextRecord } from "@t3tools/shared/composerContextReferences";
7
import { beforeEach, expect, it, vi } from "vite-plus/test";
8
import { useComposerDraftStore } from "./composerDraftStore";
9
+import { formatInlineContextReference } from "./lib/composerContextReferences";
10
+import { threadContextReference } from "./lib/composerContextRecords";
11
import {
12
questionAttachmentDraftId,
13
countQuestionAttachments,
14
questionAttachmentDraftPrefix,
15
changeQuestionAttachmentPreparation,
16
clearQuestionAttachmentDraft,
17
+ usePendingUserInputAnswers,
18
useQuestionAttachmentPreparation,
19
} from "./questionAttachments";
20
@@ -19,6 +26,7 @@ const requestId = ApprovalRequestId.make("request-1");
26
beforeEach(() => {
27
useComposerDraftStore.setState({ draftsByThreadKey: {}, draftThreadsByThreadKey: {} });
28
useQuestionAttachmentPreparation.setState({ counts: {} });
29
+ usePendingUserInputAnswers.setState({}, true);
30
release.mockClear();
31
});
32
it("keeps question files separate from the normal draft and other questions", () => {
@@ -126,13 +134,58 @@ it("clears attachment drafts for requests the thread resolved, wherever they wer
134
const elsewhere = questionAttachmentDraftId(environmentId, otherThread, resolved, "first");
135
for (const key of [keep, drop, elsewhere]) store.setPrompt(key, "Answer context");
136
changeQuestionAttachmentPreparation(drop, 1);
137
+ usePendingUserInputAnswers.setState({
138
+ [userInputDraftKey(environmentId, threadId, resolved)]: { first: { customAnswer: "Sent" } },
139
+ });
140
141
// The thread's projection synchronizes with only `pending` left, e.g. after
142
// `resolved` was answered on another device while no composer showed it.
132
- makeThreadRequestsResolvedAnnouncer(environmentId, threadId)([pending]);
143
+ makeThreadRequestsResolvedAnnouncer(
144
+ environmentId,
145
+ threadId,
146
+ )([
147
+ { id: pending, status: "pending" },
148
+ { id: resolved, status: "resolved" },
149
+ ]);
150
151
expect(store.getComposerDraft(keep)?.prompt).toBe("Answer context");
152
expect(store.getComposerDraft(drop)).toBeNull();
153
expect(store.getComposerDraft(elsewhere)?.prompt).toBe("Answer context");
154
expect(useQuestionAttachmentPreparation.getState().counts[drop]).toBeUndefined();
155
+ // An answered question's text was sent, so it does not come back as a draft.
156
+ expect(store.getComposerDraft({ environmentId, threadId })).toBeNull();
157
+ expect(usePendingUserInputAnswers.getState()).toEqual({});
158
});
159
+
160
+// Stop cancels an open question; a provider timeout expires it. Neither sends the answer.
161
+it.each(["cancelled", "expired"] as const)(
162
+ "returns typed answers and their thread chips to the thread draft when a question is %s",
163
+ (status) => {
164
+ const store = useComposerDraftStore.getState();
165
+ const request = RuntimeRequestId.make("stopped");
166
+ const reference = threadContextRecord(
167
+ { environmentId, threadId: ThreadId.make("reference-thread") },
168
+ "Reference work",
169
+ );
170
+ const answer = `Purple, like ${formatInlineContextReference(threadContextReference(reference))}`;
171
+ store.setPrompt({ environmentId, threadId }, "Earlier draft");
172
+ store.setThreadContexts(questionAttachmentDraftId(environmentId, threadId, request, "first"), [
173
+ reference,
174
+ ]);
175
+ usePendingUserInputAnswers.setState({
176
+ [userInputDraftKey(environmentId, threadId, request)]: {
177
+ first: { customAnswer: answer },
178
+ second: { customAnswer: " " },
179
+ third: { customAnswer: "Also this" },
180
+ },
181
+ });
182
+
183
+ makeThreadRequestsResolvedAnnouncer(environmentId, threadId)([{ id: request, status }]);
184
+
185
+ expect(store.getComposerDraft({ environmentId, threadId })).toMatchObject({
186
+ prompt: `Earlier draft\n\n${answer}\n\nAlso this`,
187
+ threadContexts: [reference],
188
+ });
189
+ expect(usePendingUserInputAnswers.getState()).toEqual({});
190
+ },
191
+);
apps/web/src/questionAttachments.ts
+76
-7
@@ -1,12 +1,31 @@
1
-import { scopedThreadKey } from "@t3tools/client-runtime/environment";
1
+import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
2
+import type { PendingUserInputDraftAnswer } from "@t3tools/client-runtime/state/pending-user-input";
3
import {
4
onThreadRequestsResolved,
5
+ pruneResolvedUserInputDrafts,
6
resolvedQuestionDraftKeys,
7
+ userInputDraftKey,
8
} from "@t3tools/client-runtime/state/thread-requests";
6
-import type { EnvironmentId, ScopedThreadRef, ThreadId } from "@t3tools/contracts";
9
+import type {
10
+ EnvironmentId,
11
+ RuntimeRequestId,
12
+ ScopedThreadRef,
13
+ ThreadContextRecord,
14
+ ThreadId,
15
+} from "@t3tools/contracts";
16
import { create } from "zustand";
17
import { DraftId, useComposerDraftStore } from "./composerDraftStore";
18
import { releaseDraftAttachments } from "./lib/attachmentUploadQueue";
19
+import {
20
+ carryDisplacedCustomAnswerIntoPrompt,
21
+ threadContextsReferencedByAnswer,
22
+} from "./pendingUserInput";
23
+
24
+/** Edited question answers, keyed by `userInputDraftKey`; suggested answers are not stored. */
25
+export const usePendingUserInputAnswers = create<
26
+ Record<string, Record<string, PendingUserInputDraftAnswer>>
27
+>(() => ({}));
28
+export const usePendingUserInputQuestionIndex = create<Record<string, number>>(() => ({}));
29
30
export function questionAttachmentDraftPrefix(
31
environmentId: EnvironmentId,
@@ -113,8 +132,58 @@ function pruneResolvedQuestionAttachmentDrafts(
132
}
133
}
134
116
-// Attachment drafts persist across reloads, so a request resolved while this
117
-// client was away is pruned when its thread's projection first synchronizes.
118
-onThreadRequestsResolved(({ environmentId, threadId, pendingRequestIds }) =>
119
- pruneResolvedQuestionAttachmentDrafts(environmentId, threadId, pendingRequestIds),
120
-);
135
+/**
136
+ * Stop cancels an open question and a provider timeout expires it; neither sent
137
+ * the typed answers, so they move to the thread's own draft (not a queued-message
138
+ * edit the composer may be showing) with the thread chips they reference.
139
+ */
140
+function returnUnsentAnswersToThreadDraft(
141
+ environmentId: EnvironmentId,
142
+ threadId: ThreadId,
143
+ unansweredRequestIds: ReadonlyArray<RuntimeRequestId>,
144
+): void {
145
+ const answers = usePendingUserInputAnswers.getState();
146
+ const store = useComposerDraftStore.getState();
147
+ const target = scopeThreadRef(environmentId, threadId);
148
+ const currentPrompt = store.getComposerDraft(target)?.prompt ?? "";
149
+ let prompt = currentPrompt;
150
+ const threadContexts: ThreadContextRecord[] = [];
151
+ for (const requestId of unansweredRequestIds) {
152
+ const drafts = answers[userInputDraftKey(environmentId, threadId, requestId)] ?? {};
153
+ for (const [questionId, { customAnswer }] of Object.entries(drafts)) {
154
+ const nextPrompt = carryDisplacedCustomAnswerIntoPrompt(prompt, customAnswer);
155
+ if (nextPrompt === prompt) continue;
156
+ prompt = nextPrompt;
157
+ const questionDraft = store.getComposerDraft(
158
+ questionAttachmentDraftId(environmentId, threadId, requestId, questionId),
159
+ );
160
+ threadContexts.push(
161
+ ...threadContextsReferencedByAnswer(
162
+ customAnswer ?? "",
163
+ questionDraft?.threadContexts ?? [],
164
+ ),
165
+ );
166
+ }
167
+ }
168
+ if (prompt === currentPrompt) return;
169
+ store.setPrompt(target, prompt);
170
+ store.addThreadContexts(target, threadContexts, { appendReference: false });
171
+}
172
+
173
+// Resolution can come from anywhere: another device, an interrupt, the turn
174
+// ending, or a reload over drafts for requests resolved meanwhile. One listener,
175
+// so unsent answers and their chips are read before their drafts are pruned.
176
+onThreadRequestsResolved(({ environmentId, threadId, pendingRequestIds, unansweredRequestIds }) => {
177
+ returnUnsentAnswersToThreadDraft(environmentId, threadId, unansweredRequestIds);
178
+ usePendingUserInputAnswers.setState(
179
+ (existing) =>
180
+ pruneResolvedUserInputDrafts(existing, environmentId, threadId, pendingRequestIds),
181
+ true,
182
+ );
183
+ usePendingUserInputQuestionIndex.setState(
184
+ (existing) =>
185
+ pruneResolvedUserInputDrafts(existing, environmentId, threadId, pendingRequestIds),
186
+ true,
187
+ );
188
+ pruneResolvedQuestionAttachmentDrafts(environmentId, threadId, pendingRequestIds);
189
+});
packages/client-runtime/src/state/threadRequests.test.ts
+12
-6
@@ -196,14 +196,20 @@ describe("announcing resolved thread requests", () => {
196
using recorder = record();
197
const announce = makeThreadRequestsResolvedAnnouncer(environmentId, threadId);
198
199
- announce([first]);
200
- announce([first, second]);
201
- announce([first, second]);
202
- announce([second]);
199
+ const pending = (id: RuntimeRequestId) => ({ id, status: "pending" as const });
200
+ announce([pending(first)]);
201
+ announce([pending(first), pending(second)]);
202
+ announce([pending(first), pending(second)]);
203
+ announce([{ id: first, status: "cancelled" }, pending(second)]);
204
+ announce([
205
+ { id: first, status: "cancelled" },
206
+ { id: second, status: "resolved" },
207
+ ]);
208
209
expect(recorder.events).toEqual([
205
- { environmentId, threadId, pendingRequestIds: [first] },
206
- { environmentId, threadId, pendingRequestIds: [second] },
210
+ { environmentId, threadId, pendingRequestIds: [first], unansweredRequestIds: [] },
211
+ { environmentId, threadId, pendingRequestIds: [second], unansweredRequestIds: [first] },
212
+ { environmentId, threadId, pendingRequestIds: [], unansweredRequestIds: [first] },
213
]);
214
});
215
});
packages/client-runtime/src/state/threadRequests.ts
+22
-12
@@ -168,6 +168,8 @@ export interface ThreadRequestsResolved {
168
readonly threadId: ThreadId;
169
/** Every request the thread still waits on; drafts for any other request are stale. */
170
readonly pendingRequestIds: ReadonlyArray<RuntimeRequestId>;
171
+ /** Requests that closed without an answer (cancelled or expired), so typed drafts were never sent. */
172
+ readonly unansweredRequestIds: ReadonlyArray<RuntimeRequestId>;
173
}
174
175
const threadRequestsResolvedListeners = new Set<(event: ThreadRequestsResolved) => void>();
@@ -198,8 +200,8 @@ function notifyThreadRequestsResolved(event: ThreadRequestsResolved): void {
200
}
201
202
/**
201
- * Tracks one thread's announced pending requests. Feed it the pending ids of
202
- * each authoritative projection; it notifies on the first one and whenever an
203
+ * Tracks one thread's announced pending requests. Feed it the runtime requests
204
+ * of each authoritative projection; it notifies on the first one and whenever an
205
* announced request is no longer pending. New requests alone stay quiet.
206
*/
207
export function makeThreadRequestsResolvedAnnouncer(
@@ -207,22 +209,30 @@ export function makeThreadRequestsResolvedAnnouncer(
209
threadId: ThreadId,
210
) {
211
let announced: ReadonlySet<RuntimeRequestId> | null = null;
210
- return (pendingRequestIds: ReadonlyArray<RuntimeRequestId>) => {
212
+ return (
213
+ runtimeRequests: ReadonlyArray<
214
+ Pick<OrchestrationV2ThreadProjection["runtimeRequests"][number], "id" | "status">
215
+ >,
216
+ ) => {
217
+ const pendingRequestIds = runtimeRequests.flatMap((request) =>
218
+ request.status === "pending" ? [request.id] : [],
219
+ );
220
const pending = new Set(pendingRequestIds);
221
const resolvedSome = announced === null || [...announced].some((id) => !pending.has(id));
222
announced = pending;
214
- if (resolvedSome) notifyThreadRequestsResolved({ environmentId, threadId, pendingRequestIds });
223
+ if (!resolvedSome) return;
224
+ const unansweredRequestIds = runtimeRequests.flatMap((request) =>
225
+ request.status === "cancelled" || request.status === "expired" ? [request.id] : [],
226
+ );
227
+ notifyThreadRequestsResolved({
228
+ environmentId,
229
+ threadId,
230
+ pendingRequestIds,
231
+ unansweredRequestIds,
232
+ });
233
};
234
}
235
218
-export function pendingRuntimeRequestIds(
219
- projection: Pick<OrchestrationV2ThreadProjection, "runtimeRequests">,
220
-): RuntimeRequestId[] {
221
- return projection.runtimeRequests.flatMap((request) =>
222
- request.status === "pending" ? [request.id] : [],
223
- );
224
-}
225
-
236
export function derivePendingThreadRequests(
237
projection: Pick<ThreadStructure, "runtimeRequests" | "turnItems">,
238
): PendingThreadRequests {
packages/client-runtime/src/state/threads-sync.test.ts
+1
@@ -2500,6 +2500,7 @@ describe("EnvironmentThreads", () => {
2500
environmentId: TARGET.environmentId,
2501
threadId: THREAD_ID,
2502
pendingRequestIds: [],
2503
+ unansweredRequestIds: [],
2504
});
2505
expect(yield* Queue.size(announced)).toBe(0);
2506
}),
packages/client-runtime/src/state/threads.ts
+2
-2
@@ -53,7 +53,7 @@ import {
53
type ThreadHistoryMeta,
54
} from "./threadHistoryMerge.ts";
55
import * as ThreadSnapshotLoader from "./threadSnapshotHttp.ts";
56
-import { makeThreadRequestsResolvedAnnouncer, pendingRuntimeRequestIds } from "./threadRequests.ts";
56
+import { makeThreadRequestsResolvedAnnouncer } from "./threadRequests.ts";
57
import {
58
EMPTY_ENVIRONMENT_THREAD_STATE,
59
type EnvironmentThreadState,
@@ -309,7 +309,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
309
const owns = resumeCache === undefined || resumeCache.owner === owner;
310
if (owns && current.status === "deleted") announceRequests([]);
311
else if (owns && current.status === "live" && Option.isSome(current.data))
312
- announceRequests(pendingRuntimeRequestIds(current.data.value));
312
+ announceRequests(current.data.value.runtimeRequests);
313
committed = {
314
state: current,
315
sequence,