The best way to control Claude Code, Codex and more from any computer or phone
fix(web): keep a typed question answer when you open a new thread (#13865)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
Guillermo Casanova committed
Oct 19, 2026 at 15:12 UTC
b177a16b690954d5446e28ad835578691b2a64d7
3 files changed
+241
-29
apps/web/src/components/chat/ComposerPendingUserInputPanel.navigation.browser.test.tsx
+163
-2
@@ -1,5 +1,12 @@
1
-import { EnvironmentId, RuntimeRequestId, ThreadId } from "@t3tools/contracts";
2
-import { act, useState } from "react";
1
+import {
2
+ EnvironmentId,
3
+ NodeId,
4
+ RuntimeRequestId,
5
+ ThreadId,
6
+ TurnItemId,
7
+ type OrchestrationV2ThreadProjection,
8
+} from "@t3tools/contracts";
9
+import { act, useLayoutEffect, useRef, useState, type ComponentProps } from "react";
10
import { createRoot, type Root } from "react-dom/client";
11
import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
12
@@ -13,7 +20,9 @@ vi.mock(import("../ChatMarkdown"), async (importOriginal) => ({
20
default: (({ text }: { text: string }) => <p>{text}</p>) as never,
21
}));
22
23
+import { makeThreadProjectionFixture } from "../../test-fixtures";
24
import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel";
25
+import { usePendingThreadRequests } from "./usePendingThreadRequests";
26
27
const threadRef = { environmentId: EnvironmentId.make("env"), threadId: ThreadId.make("thread") };
28
@@ -131,3 +140,155 @@ it("still auto-advances once after the answer draft rerenders the same question"
140
await act(async () => vi.advanceTimersByTime(200));
141
expect(activeIndex()).toBe("1");
142
});
143
+
144
+function questionProjection(threadId: ThreadId, requestIds = ["first", "second"]) {
145
+ const projection = makeThreadProjectionFixture();
146
+ return {
147
+ ...projection,
148
+ thread: { ...projection.thread, id: threadId },
149
+ runtimeRequests: requestIds.map((id) => ({
150
+ id: RuntimeRequestId.make(id),
151
+ nodeId: NodeId.make(id),
152
+ providerTurnId: null,
153
+ nativeRequestRef: null,
154
+ kind: "user_input" as const,
155
+ status: "pending" as const,
156
+ responseCapability: { type: "message" as const },
157
+ createdAt: projection.updatedAt,
158
+ resolvedAt: null,
159
+ })),
160
+ turnItems: requestIds.map((id, ordinal) => ({
161
+ id: TurnItemId.make(id),
162
+ threadId,
163
+ runId: null,
164
+ nodeId: NodeId.make(id),
165
+ providerThreadId: null,
166
+ providerTurnId: null,
167
+ nativeItemRef: null,
168
+ parentItemId: null,
169
+ ordinal,
170
+ status: "completed" as const,
171
+ title: null,
172
+ startedAt: projection.updatedAt,
173
+ completedAt: projection.updatedAt,
174
+ updatedAt: projection.updatedAt,
175
+ type: "user_input_request" as const,
176
+ requestId: RuntimeRequestId.make(id),
177
+ questions: prompt.questions,
178
+ })),
179
+ } satisfies OrchestrationV2ThreadProjection;
180
+}
181
+
182
+let requests: ReturnType<typeof usePendingThreadRequests>;
183
+
184
+function PendingRequestsProbe({
185
+ environmentId,
186
+ projection,
187
+ loading = false,
188
+}: {
189
+ environmentId: EnvironmentId;
190
+ projection: OrchestrationV2ThreadProjection;
191
+ loading?: boolean;
192
+}) {
193
+ const promptRef = useRef("");
194
+ const composerRef = useRef(null);
195
+ const state = usePendingThreadRequests({
196
+ environmentId,
197
+ activeThreadId: projection.thread.id,
198
+ activeThread: projection.thread,
199
+ serverProjection: loading ? null : projection,
200
+ supportsQuestionAttachments: false,
201
+ composerDraftTarget: { environmentId, threadId: projection.thread.id },
202
+ setComposerDraftPrompt: () => {},
203
+ promptRef,
204
+ composerRef,
205
+ setThreadError: () => {},
206
+ });
207
+ useLayoutEffect(() => {
208
+ requests = state;
209
+ });
210
+ return null;
211
+}
212
+
213
+it("retains answers, selections and question position after leaving chat, including while the projection reloads", async () => {
214
+ const environmentId = EnvironmentId.make("remount-environment");
215
+ const projection = questionProjection(threadRef.threadId);
216
+ const render = (loading = false) =>
217
+ act(() =>
218
+ root.render(
219
+ <PendingRequestsProbe
220
+ environmentId={environmentId}
221
+ projection={projection}
222
+ loading={loading}
223
+ />,
224
+ ),
225
+ );
226
+ await render();
227
+ await act(() =>
228
+ requests.onChangeActivePendingUserInputCustomAnswer("question-0", "Keep my text"),
229
+ );
230
+ await act(() => requests.onAdvanceActivePendingUserInput());
231
+ await act(() => requests.onSelectActivePendingUserInputOption("question-1", "Incremental"));
232
+ await act(() => requests.onAdvanceActivePendingUserInput());
233
+ const expected = {
234
+ activePendingQuestionIndex: 2,
235
+ activePendingDraftAnswers: {
236
+ "question-0": { customAnswer: "Keep my text" },
237
+ "question-1": { selectedOptionValues: ["Incremental"] },
238
+ },
239
+ };
240
+ expect(requests).toMatchObject(expected);
241
+
242
+ // New thread and Settings both unmount the chat that owns this hook.
243
+ await act(() => root.render(null));
244
+ await render();
245
+ expect(requests).toMatchObject(expected);
246
+
247
+ await act(() => root.render(null));
248
+ await render(true);
249
+ expect(requests.activePendingUserInput).toBeNull();
250
+ await render();
251
+ expect(requests).toMatchObject(expected);
252
+});
253
+
254
+it("isolates drafts by environment, thread and request and discards only resolved requests", async () => {
255
+ const environmentId = EnvironmentId.make("scope-environment");
256
+ const projection = questionProjection(threadRef.threadId);
257
+ const scopes = [
258
+ { environmentId, projection },
259
+ { environmentId: EnvironmentId.make("other-environment"), projection },
260
+ { environmentId, projection: questionProjection(ThreadId.make("other-thread")) },
261
+ { environmentId, projection: questionProjection(threadRef.threadId, ["second", "first"]) },
262
+ ];
263
+ const show = (scope: ComponentProps<typeof PendingRequestsProbe>) =>
264
+ act(() => root.render(<PendingRequestsProbe {...scope} />));
265
+ for (const [index, scope] of scopes.entries()) {
266
+ await show(scope);
267
+ expect(requests.activePendingQuestionIndex).toBe(0);
268
+ expect(requests.activePendingDraftAnswers["question-0"]?.customAnswer).toBeUndefined();
269
+ await act(() =>
270
+ requests.onChangeActivePendingUserInputCustomAnswer("question-0", `Answer ${index}`),
271
+ );
272
+ await act(() => requests.onAdvanceActivePendingUserInput());
273
+ }
274
+
275
+ await show({
276
+ environmentId,
277
+ projection: {
278
+ ...projection,
279
+ runtimeRequests: projection.runtimeRequests.map((request) =>
280
+ request.id === "first"
281
+ ? { ...request, status: "resolved", resolvedAt: projection.updatedAt }
282
+ : request,
283
+ ),
284
+ },
285
+ });
286
+ expect(requests.activePendingUserInput?.requestId).toBe("second");
287
+ for (const [index, scope] of scopes.entries()) {
288
+ await show(scope);
289
+ expect(requests.activePendingQuestionIndex).toBe(index === 0 ? 0 : 1);
290
+ expect(requests.activePendingDraftAnswers["question-0"]?.customAnswer).toBe(
291
+ index === 0 ? undefined : `Answer ${index}`,
292
+ );
293
+ }
294
+});
apps/web/src/components/chat/usePendingThreadRequests.ts
+49
-27
@@ -16,7 +16,15 @@ import {
16
isAtomCommandInterrupted,
17
squashAtomCommandFailure,
18
} from "@t3tools/client-runtime/state/runtime";
19
-import { useEffect, useRef, useState, type RefObject, type SetStateAction } from "react";
19
+import { create } from "zustand";
20
+import {
21
+ useLayoutEffect,
22
+ useEffect,
23
+ useRef,
24
+ useState,
25
+ type RefObject,
26
+ type SetStateAction,
27
+} from "react";
28
import { useShallow } from "zustand/react/shallow";
29
import { DraftId, useComposerDraftStore } from "../../composerDraftStore";
30
import { useStableCallback } from "../../hooks/useStableCallback";
@@ -26,6 +34,8 @@ import {
34
carryDisplacedCustomAnswerIntoPrompt,
35
derivePendingUserInputProgress,
36
projectPendingUserInputAnswer,
37
+ pendingUserInputRequestKey,
38
+ pruneResolvedUserInputDrafts,
39
setPendingUserInputCustomAnswer,
40
togglePendingUserInputOptionSelection,
41
type PendingUserInputDraftAnswer,
@@ -48,6 +58,10 @@ import { useOrchestrationCommand } from "../../state/use-orchestration-command";
58
import type { ChatComposerHandle } from "./ChatComposer";
59
60
const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnswer> = {};
61
+const usePendingUserInputAnswers = create<
62
+ Record<string, Record<string, PendingUserInputDraftAnswer>>
63
+>(() => ({}));
64
+const usePendingUserInputQuestionIndex = create<Record<string, number>>(() => ({}));
65
const NO_PENDING_REQUESTS = { approvals: [], userInputs: [] } as const;
66
const NO_PENDING_APPROVALS: ReturnType<typeof derivePendingApprovals> = [];
67
const NO_PENDING_USER_INPUTS: ReturnType<typeof derivePendingUserInputs> = [];
@@ -94,7 +108,6 @@ function makePendingCustomAnswerSetter(input: {
108
export function usePendingThreadRequests(input: {
109
readonly environmentId: EnvironmentId;
110
readonly activeThreadId: ThreadId | null;
97
- // The effect that prunes stale question drafts re-runs when this object changes.
111
readonly activeThread: { readonly id: ThreadId } | undefined;
112
readonly serverProjection: OrchestrationV2ThreadProjection | null;
113
readonly supportsQuestionAttachments: boolean;
@@ -130,13 +143,13 @@ export function usePendingThreadRequests(input: {
143
const [respondingUserInputRequestIds, setRespondingUserInputRequestIds] = useState<
144
RuntimeRequestId[]
145
>([]);
133
- const [pendingUserInputAnswersByRequestId, setPendingUserInputAnswersByRequestId] = useState<
134
- Record<string, Record<string, PendingUserInputDraftAnswer>>
135
- >({});
136
- const [pendingUserInputQuestionIndexByRequestId, setPendingUserInputQuestionIndexByRequestId] =
137
- useState<Record<string, number>>({});
146
+ const setPendingUserInputAnswersByRequestId = usePendingUserInputAnswers.setState;
147
+ const setPendingUserInputQuestionIndexByRequestId = usePendingUserInputQuestionIndex.setState;
148
+ const projectedThreadId = serverProjection?.thread.id;
149
const pendingRequests =
139
- serverProjection === null ? NO_PENDING_REQUESTS : derivePendingThreadRequests(serverProjection);
150
+ serverProjection !== null && serverProjection.thread.id === activeThreadId
151
+ ? derivePendingThreadRequests(serverProjection)
152
+ : NO_PENDING_REQUESTS;
153
// The projection changes on every streamed event, so shared empties keep the
154
// composer and approval panel from re-rendering while nothing is pending.
155
const pendingApprovals =
@@ -148,24 +161,25 @@ export function usePendingThreadRequests(input: {
161
? NO_PENDING_USER_INPUTS
162
: derivePendingUserInputs(pendingRequests.userInputs);
163
const activePendingUserInput = pendingUserInputs[0] ?? null;
151
- const activePendingRequestKey = JSON.stringify([
164
+ const activePendingRequestKey = pendingUserInputRequestKey(
165
environmentId,
166
activeThreadId,
167
activePendingUserInput?.requestId,
155
- ]);
156
- const activePendingAnswerDrafts =
157
- pendingUserInputAnswersByRequestId[activePendingRequestKey] ?? EMPTY_PENDING_USER_INPUT_ANSWERS;
158
- if (
159
- activePendingUserInput &&
160
- seedUserInputDraftAnswers(activePendingUserInput.questions, activePendingAnswerDrafts) !==
161
- activePendingAnswerDrafts
162
- ) {
163
- setPendingUserInputAnswersByRequestId((existing) => {
168
+ );
169
+ const activePendingAnswerDrafts = usePendingUserInputAnswers(
170
+ (state) => state[activePendingRequestKey] ?? EMPTY_PENDING_USER_INPUT_ANSWERS,
171
+ );
172
+ const activePendingQuestionIndex = usePendingUserInputQuestionIndex(
173
+ (state) => state[activePendingRequestKey] ?? 0,
174
+ );
175
+ useLayoutEffect(() => {
176
+ if (!activePendingUserInput) return;
177
+ usePendingUserInputAnswers.setState((existing) => {
178
const drafts = existing[activePendingRequestKey] ?? EMPTY_PENDING_USER_INPUT_ANSWERS;
179
const seeded = seedUserInputDraftAnswers(activePendingUserInput.questions, drafts);
180
return seeded === drafts ? existing : { ...existing, [activePendingRequestKey]: seeded };
181
});
168
- }
182
+ }, [activePendingRequestKey, activePendingUserInput]);
183
const pendingQuestionDraftKeys = activeThreadId
184
? pendingUserInputs.flatMap((request) =>
185
request.questions.map((question) =>
@@ -203,9 +217,21 @@ export function usePendingThreadRequests(input: {
217
),
218
);
219
useEffect(() => {
206
- if (!activeThread) return;
220
+ // A thread shell can arrive before its requests; missing detail is not resolution.
221
+ if (!activeThread || projectedThreadId !== activeThread.id) return;
222
const questionThread = activeThread;
223
const currentRequests = pendingUserInputs;
224
+ const pendingRequestIds = currentRequests.map((request) => request.requestId);
225
+ usePendingUserInputAnswers.setState(
226
+ (existing) =>
227
+ pruneResolvedUserInputDrafts(existing, environmentId, questionThread.id, pendingRequestIds),
228
+ true,
229
+ );
230
+ usePendingUserInputQuestionIndex.setState(
231
+ (existing) =>
232
+ pruneResolvedUserInputDrafts(existing, environmentId, questionThread.id, pendingRequestIds),
233
+ true,
234
+ );
235
const prefix = questionAttachmentDraftPrefix(environmentId, questionThread.id);
236
const retained = new Set(
237
currentRequests.flatMap((request) =>
@@ -227,7 +253,7 @@ export function usePendingThreadRequests(input: {
253
if (key.startsWith(prefix) && !retained.has(DraftId.make(key)))
254
clearQuestionAttachmentDraft(DraftId.make(key));
255
}
230
- }, [environmentId, activeThread, pendingUserInputs]);
256
+ }, [environmentId, activeThread, projectedThreadId, pendingUserInputs]);
257
const activePendingDraftAnswers =
258
!activePendingUserInput || !activeThreadId
259
? EMPTY_PENDING_USER_INPUT_ANSWERS
@@ -244,7 +270,7 @@ export function usePendingThreadRequests(input: {
270
return [
271
question.id,
272
{
247
- ...pendingUserInputAnswersByRequestId[activePendingRequestKey]?.[question.id],
273
+ ...activePendingAnswerDrafts[question.id],
274
attachmentCount: attachments.length,
275
attachmentsBlocked:
276
(attachments.length > 0 && !supportsQuestionAttachments) ||
@@ -254,9 +280,6 @@ export function usePendingThreadRequests(input: {
280
];
281
}),
282
);
257
- const activePendingQuestionIndex = activePendingUserInput
258
- ? (pendingUserInputQuestionIndexByRequestId[activePendingRequestKey] ?? 0)
259
- : 0;
283
const activePendingProgress = activePendingUserInput
284
? derivePendingUserInputProgress(
285
activePendingUserInput.questions,
@@ -413,8 +436,7 @@ export function usePendingThreadRequests(input: {
436
}
437
// The option replaces the custom answer. Anything typed there is the
438
// user's text, so it goes back to the thread draft instead of vanishing.
416
- const displacedAnswer =
417
- pendingUserInputAnswersByRequestId[activePendingRequestKey]?.[questionId]?.customAnswer;
439
+ const displacedAnswer = activePendingAnswerDrafts[questionId]?.customAnswer;
440
const currentPrompt =
441
useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.prompt ?? "";
442
const nextPrompt = carryDisplacedCustomAnswerIntoPrompt(currentPrompt, displacedAnswer);
apps/web/src/pendingUserInput.ts
+29
@@ -101,6 +101,35 @@ export function setPendingUserInputCustomAnswer(
101
};
102
}
103
104
+export function pendingUserInputRequestKey(
105
+ environmentId: string,
106
+ threadId: string | null,
107
+ requestId: string | undefined,
108
+): string {
109
+ return JSON.stringify([environmentId, threadId, requestId]);
110
+}
111
+
112
+/** Drops a thread's drafts for requests that are no longer pending. Unchanged input is returned as is. */
113
+export function pruneResolvedUserInputDrafts<T>(
114
+ draftsByRequestKey: Record<string, T>,
115
+ environmentId: string,
116
+ threadId: string,
117
+ pendingRequestIds: ReadonlyArray<string>,
118
+): Record<string, T> {
119
+ const threadPrefix = JSON.stringify([environmentId, threadId]).slice(0, -1);
120
+ const pendingKeys = new Set(
121
+ pendingRequestIds.map((requestId) =>
122
+ pendingUserInputRequestKey(environmentId, threadId, requestId),
123
+ ),
124
+ );
125
+ const retained = Object.entries(draftsByRequestKey).filter(
126
+ ([key]) => !key.startsWith(threadPrefix) || pendingKeys.has(key),
127
+ );
128
+ return retained.length === Object.keys(draftsByRequestKey).length
129
+ ? draftsByRequestKey
130
+ : Object.fromEntries(retained);
131
+}
132
+
133
const DISPLACED_ANSWER_SEPARATOR = "\n\n";
134
135
export function carryDisplacedCustomAnswerIntoPrompt(