@devries-cameron20 / t3code Mirror · read-only / commits / d5a791b940
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 15:45 UTC

fix(client): drafts for answered questions are cleared even when their thread is not open (#25457)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 26, 2026 at 05:56 UTC d5a791b94041555dc9a47f0dac9369c9cab7ef06
13 files changed +490 -168
apps/mobile/src/lib/scopedEntities.ts
+1 -8
@@ -1,4 +1,4 @@
1 -import { EnvironmentId, ProjectId, RuntimeRequestId, ThreadId } from "@t3tools/contracts";
1 +import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
2
3 export function scopedProjectKey(environmentId: EnvironmentId, projectId: ProjectId): string {
4 return `${environmentId}:${projectId}`;
@@ -7,10 +7,3 @@ export function scopedProjectKey(environmentId: EnvironmentId, projectId: Projec
7 export function scopedThreadKey(environmentId: EnvironmentId, threadId: ThreadId): string {
8 return `${environmentId}:${threadId}`;
9 }
10 -
11 -export function scopedRequestKey(
12 - environmentId: EnvironmentId,
13 - requestId: RuntimeRequestId,
14 -): string {
15 - return `${environmentId}:${requestId}`;
16 -}
apps/mobile/src/state/thread-task-permissions.test.ts
+1
@@ -113,6 +113,7 @@ vi.mock("./threads", async () => {
113 environmentThreadDetails: {
114 queueWorkflowAtom: () => Atom.make(null),
115 checkpointSummariesAtom: () => Atom.make([]),
116 + pendingRequestsAtom: () => Atom.make(state.pendingRequests),
117 },
118 threadEnvironment: {
119 respondToApproval: state.approve,
apps/mobile/src/state/use-selected-thread-requests.ts
+123 -57
@@ -16,19 +16,27 @@ import {
16 composerAttachmentsStillUploading,
17 } from "./composer-attachment-uploads";
18 import { useAtomValue } from "@effect/atom-react";
19 -import { useCallback, useEffect, useRef, useState } from "react";
19 +import { useCallback, useRef, useState } from "react";
20
21 -import { type ProviderApprovalDecision, type RuntimeRequestId } from "@t3tools/contracts";
21 +import {
22 + type EnvironmentId,
23 + type ProviderApprovalDecision,
24 + type RuntimeRequestId,
25 + type ThreadId,
26 +} from "@t3tools/contracts";
27 import {
28 type PendingThreadRequests,
29 type ThreadUserInputQuestion,
30 + onThreadRequestsResolved,
31 + pruneResolvedUserInputDrafts,
32 + resolvedQuestionDraftKeys,
33 seedUserInputDraftAnswers,
34 + userInputDraftKey,
35 } from "@t3tools/client-runtime/state/thread-requests";
36 import { AuthOrchestrationOperateScope } from "@t3tools/contracts";
37 import { Atom } from "effect/reactivity";
38
30 -import { threadEnvironment } from "../state/threads";
31 -import { scopedRequestKey } from "../lib/scopedEntities";
39 +import { environmentThreadDetails, threadEnvironment } from "../state/threads";
40 import {
41 buildPendingUserInputAnswers,
42 setPendingUserInputCustomAnswer,
@@ -47,6 +55,14 @@ const userInputDraftsByRequestKeyAtom = Atom.make<
55 Record<string, Record<string, PendingUserInputDraftAnswer>>
56 >({}).pipe(Atom.keepAlive, Atom.withLabel("mobile:user-input-drafts"));
57
58 +// Writes start from the suggested answer the user was looking at.
59 +function seededDraft(
60 + drafts: Record<string, PendingUserInputDraftAnswer> | undefined,
61 + question: ThreadUserInputQuestion,
62 +): PendingUserInputDraftAnswer | undefined {
63 + return seedUserInputDraftAnswers([question], drafts ?? {})[question.id];
64 +}
65 +
66 function setUserInputDraftOption(
67 requestKey: string,
68 question: ThreadUserInputQuestion,
@@ -59,7 +75,7 @@ function setUserInputDraftOption(
75 ...current[requestKey],
76 [question.id]: togglePendingUserInputOptionSelection(
77 question,
62 - current[requestKey]?.[question.id],
78 + seededDraft(current[requestKey], question),
79 value,
80 ),
81 },
@@ -78,13 +94,75 @@ function setUserInputDraftCustomAnswer(
94 ...current[requestKey],
95 [question.id]: setPendingUserInputCustomAnswer(
96 question,
81 - current[requestKey]?.[question.id],
97 + seededDraft(current[requestKey], question),
98 customAnswer,
99 ),
100 },
101 });
102 }
103
104 +/** Drops a thread's answer and attachment drafts for every request outside `pendingRequestIds`. */
105 +function pruneResolvedRequestDrafts(
106 + environmentId: EnvironmentId,
107 + threadId: ThreadId,
108 + pendingRequestIds: ReadonlyArray<RuntimeRequestId>,
109 +): void {
110 + const drafts = appAtomRegistry.get(userInputDraftsByRequestKeyAtom);
111 + const prunedDrafts = pruneResolvedUserInputDrafts(
112 + drafts,
113 + environmentId,
114 + threadId,
115 + pendingRequestIds,
116 + );
117 + if (prunedDrafts !== drafts) appAtomRegistry.set(userInputDraftsByRequestKeyAtom, prunedDrafts);
118 +
119 + const prefix = questionAttachmentDraftPrefix(environmentId, threadId);
120 + const attachmentDrafts = appAtomRegistry.get(questionAttachmentDraftsAtom(prefix));
121 + const counts = { ...appAtomRegistry.get(questionAttachmentPreparationAtom) };
122 + let changed = false;
123 + for (const key of resolvedQuestionDraftKeys(
124 + new Set([...Object.keys(attachmentDrafts), ...Object.keys(counts)]),
125 + prefix,
126 + pendingRequestIds,
127 + )) {
128 + if (attachmentDrafts[key]) clearComposerDraft(key);
129 + if (key in counts) {
130 + delete counts[key];
131 + changed = true;
132 + }
133 + }
134 + if (changed) appAtomRegistry.set(questionAttachmentPreparationAtom, counts);
135 +}
136 +
137 +// Resolution can come from anywhere: another device, an interrupt, the turn
138 +// ending, or a reload over drafts for requests that resolved meanwhile.
139 +onThreadRequestsResolved(({ environmentId, threadId, pendingRequestIds }) =>
140 + pruneResolvedRequestDrafts(environmentId, threadId, pendingRequestIds),
141 +);
142 +
143 +/**
144 + * Drops `answeredRequestId`'s drafts as soon as the server accepts the
145 + * response, before the projection push that resolves it lands.
146 + */
147 +function collectAnsweredRequestDrafts(
148 + environmentId: EnvironmentId,
149 + threadId: ThreadId,
150 + answeredRequestId: RuntimeRequestId,
151 +) {
152 + const current = appAtomRegistry.get(
153 + environmentThreadDetails.pendingRequestsAtom({ environmentId, threadId }),
154 + );
155 + // Missing detail is not resolution.
156 + if (current === null) return;
157 + pruneResolvedRequestDrafts(
158 + environmentId,
159 + threadId,
160 + [...current.approvals, ...current.userInputs]
161 + .map((request) => request.requestId)
162 + .filter((requestId) => requestId !== answeredRequestId),
163 + );
164 +}
165 +
166 export function useSelectedThreadRequests() {
167 const respondToApproval = useAtomCommand(
168 threadEnvironment.respondToApproval,
@@ -109,19 +187,6 @@ export function useSelectedThreadRequests() {
187 const activePendingApproval = activePendingApprovals[0] ?? null;
188 const activePendingUserInputs = pendingRequests?.userInputs ?? EMPTY_PENDING_REQUESTS.userInputs;
189 const activePendingUserInput = activePendingUserInputs[0] ?? null;
112 - useEffect(() => {
113 - if (!activePendingUserInput || !selectedThreadShell) return;
114 - const requestKey = scopedRequestKey(
115 - selectedThreadShell.environmentId,
116 - activePendingUserInput.requestId,
117 - );
118 - const existing = appAtomRegistry.get(userInputDraftsByRequestKeyAtom);
119 - const drafts = existing[requestKey] ?? {};
120 - const seeded = seedUserInputDraftAnswers(activePendingUserInput.questions, drafts);
121 - if (seeded !== drafts) {
122 - appAtomRegistry.set(userInputDraftsByRequestKeyAtom, { ...existing, [requestKey]: seeded });
123 - }
124 - }, [activePendingUserInput, selectedThreadShell]);
190 const questionServerConfigs = useServerConfigs();
191 const attachmentDrafts = useAtomValue(
192 questionAttachmentDraftsAtom(
@@ -132,36 +197,20 @@ export function useSelectedThreadRequests() {
197 );
198 const preparationCounts = useAtomValue(questionAttachmentPreparationAtom);
199 const uploadStates = useAtomValue(composerAttachmentUploadsAtom);
135 - useEffect(() => {
136 - if (!selectedThreadShell || !pendingRequests) return;
137 - const prefix = questionAttachmentDraftPrefix(
138 - selectedThreadShell.environmentId,
139 - selectedThreadShell.id,
140 - );
141 - const retained = new Set(
142 - activePendingUserInputs.flatMap((request) =>
143 - request.questions.map((question) =>
144 - questionAttachmentDraftKey(
145 - selectedThreadShell.environmentId,
146 - selectedThreadShell.id,
147 - request.requestId,
148 - question.id,
149 - ),
150 - ),
151 - ),
152 - );
153 - const counts = { ...appAtomRegistry.get(questionAttachmentPreparationAtom) };
154 - let changed = false;
155 - for (const key of new Set([...Object.keys(attachmentDrafts), ...Object.keys(counts)])) {
156 - if (!key.startsWith(prefix) || retained.has(key)) continue;
157 - if (attachmentDrafts[key]) clearComposerDraft(key);
158 - if (key in counts) {
159 - delete counts[key];
160 - changed = true;
161 - }
162 - }
163 - if (changed) appAtomRegistry.set(questionAttachmentPreparationAtom, counts);
164 - }, [activePendingUserInputs, attachmentDrafts, pendingRequests, selectedThreadShell]);
200 + // Suggested answers are shown until the user edits them; only edits are stored.
201 + const activePendingUserInputAnswerDrafts =
202 + activePendingUserInput && selectedThreadShell
203 + ? seedUserInputDraftAnswers(
204 + activePendingUserInput.questions,
205 + userInputDraftsByRequestKey[
206 + userInputDraftKey(
207 + selectedThreadShell.environmentId,
208 + selectedThreadShell.id,
209 + activePendingUserInput.requestId,
210 + )
211 + ] ?? {},
212 + )
213 + : {};
214 const activePendingUserInputDrafts =
215 activePendingUserInput && selectedThreadShell
216 ? Object.fromEntries(
@@ -182,12 +231,7 @@ export function useSelectedThreadRequests() {
231 return [
232 question.id,
233 {
185 - ...userInputDraftsByRequestKey[
186 - scopedRequestKey(
187 - selectedThreadShell.environmentId,
188 - activePendingUserInput.requestId,
189 - )
190 - ]?.[question.id],
234 + ...activePendingUserInputAnswerDrafts[question.id],
235 attachmentCount: attachments.length,
236 attachmentsBlocked:
237 (attachments.length > 0 &&
@@ -214,7 +258,11 @@ export function useSelectedThreadRequests() {
258 return;
259 }
260
217 - const requestKey = scopedRequestKey(selectedThreadShell.environmentId, requestId);
261 + const requestKey = userInputDraftKey(
262 + selectedThreadShell.environmentId,
263 + selectedThreadShell.id,
264 + requestId,
265 + );
266 setUserInputDraftOption(requestKey, question, value);
267 },
268 [selectedThreadShell],
@@ -229,7 +277,11 @@ export function useSelectedThreadRequests() {
277 return;
278 }
279
232 - const requestKey = scopedRequestKey(selectedThreadShell.environmentId, requestId);
280 + const requestKey = userInputDraftKey(
281 + selectedThreadShell.environmentId,
282 + selectedThreadShell.id,
283 + requestId,
284 + );
285 setUserInputDraftCustomAnswer(requestKey, question, customAnswer);
286 },
287 [activePendingUserInputs, selectedThreadShell],
@@ -339,6 +391,13 @@ export function useSelectedThreadRequests() {
391 setRespondingUserInputId((current) =>
392 current === activePendingUserInput.requestId ? null : current,
393 );
394 + if (result._tag === "Success") {
395 + collectAnsweredRequestDrafts(
396 + selectedThreadShell.environmentId,
397 + selectedThreadShell.id,
398 + activePendingUserInput.requestId,
399 + );
400 + }
401 return result;
402 }, [
403 activePendingUserInput,
@@ -367,6 +426,13 @@ export function useSelectedThreadRequests() {
426 setRespondingUserInputId((current) =>
427 current === activePendingUserInput.requestId ? null : current,
428 );
429 + if (result._tag === "Success") {
430 + collectAnsweredRequestDrafts(
431 + selectedThreadShell.environmentId,
432 + selectedThreadShell.id,
433 + activePendingUserInput.requestId,
434 + );
435 + }
436 return result;
437 }, [activePendingUserInput, dismissUserInput, selectedThreadShell]);
438
apps/web/src/components/ChatView.tsx
-1
@@ -1272,7 +1272,6 @@ export default function ChatView(props: ChatViewProps) {
1272 } = usePendingThreadRequests({
1273 environmentId,
1274 activeThreadId,
1275 - activeThread,
1275 serverProjection,
1276 supportsQuestionAttachments,
1277 composerDraftTarget,
apps/web/src/components/chat/ComposerPendingUserInputPanel.navigation.browser.test.tsx
+8 -1
@@ -6,6 +6,7 @@ import {
6 TurnItemId,
7 type OrchestrationV2ThreadProjection,
8 } from "@t3tools/contracts";
9 +import { makeThreadRequestsResolvedAnnouncer } from "@t3tools/client-runtime/state/thread-requests";
10 import { useLayoutEffect, useRef, type ComponentProps } from "react";
11 import { expect, it, vi } from "vite-plus/test";
12
@@ -88,7 +89,6 @@ function PendingRequestsProbe({
89 const state = usePendingThreadRequests({
90 environmentId,
91 activeThreadId: projection.thread.id,
91 - activeThread: projection.thread,
92 serverProjection: loading ? null : projection,
93 supportsQuestionAttachments: false,
94 composerDraftTarget: { environmentId, threadId: projection.thread.id },
@@ -161,6 +161,7 @@ it("isolates drafts by environment, thread and request and discards only resolve
161 await act(() => requests.onAdvanceActivePendingUserInput());
162 }
163
164 + // "first" was answered on another device.
165 await show({
166 environmentId,
167 projection: {
@@ -173,6 +174,12 @@ it("isolates drafts by environment, thread and request and discards only resolve
174 },
175 });
176 expect(requests.activePendingUserInput?.requestId).toBe("second");
177 + await act(() =>
178 + makeThreadRequestsResolvedAnnouncer(
179 + environmentId,
180 + threadRef.threadId,
181 + )([RuntimeRequestId.make("second")]),
182 + );
183 for (const [index, scope] of scopes.entries()) {
184 await show(scope);
185 expect(requests.activePendingQuestionIndex).toBe(index === 0 ? 0 : 1);
apps/web/src/components/chat/usePendingThreadRequests.ts
+28 -64
@@ -10,23 +10,19 @@ import {
10 } from "@t3tools/contracts";
11 import {
12 derivePendingThreadRequests,
13 + onThreadRequestsResolved,
14 + pruneResolvedUserInputDrafts,
15 seedUserInputDraftAnswers,
16 + userInputDraftKey,
17 } from "@t3tools/client-runtime/state/thread-requests";
18 import {
19 isAtomCommandInterrupted,
20 squashAtomCommandFailure,
21 } from "@t3tools/client-runtime/state/runtime";
22 import { create } from "zustand";
20 -import {
21 - useLayoutEffect,
22 - useEffect,
23 - useRef,
24 - useState,
25 - type RefObject,
26 - type SetStateAction,
27 -} from "react";
23 +import { useRef, useState, type RefObject, type SetStateAction } from "react";
24 import { useShallow } from "zustand/react/shallow";
29 -import { DraftId, useComposerDraftStore } from "../../composerDraftStore";
25 +import { type DraftId, useComposerDraftStore } from "../../composerDraftStore";
26 import { useStableCallback } from "../../hooks/useStableCallback";
27 import { getUploadedAttachments, useAttachmentUploadStore } from "../../lib/attachmentUploadQueue";
28 import {
@@ -34,17 +30,13 @@ import {
30 carryDisplacedCustomAnswerIntoPrompt,
31 derivePendingUserInputProgress,
32 projectPendingUserInputAnswer,
37 - pendingUserInputRequestKey,
38 - pruneResolvedUserInputDrafts,
33 setPendingUserInputCustomAnswer,
34 threadContextsReferencedByAnswer,
35 togglePendingUserInputOptionSelection,
36 type PendingUserInputDraftAnswer,
37 } from "../../pendingUserInput";
38 import {
45 - clearQuestionAttachmentDraft,
39 questionAttachmentDraftId,
47 - questionAttachmentDraftPrefix,
40 useQuestionAttachmentPreparation,
41 } from "../../questionAttachments";
42 import {
@@ -67,6 +59,22 @@ const NO_PENDING_REQUESTS = { approvals: [], userInputs: [] } as const;
59 const NO_PENDING_APPROVALS: ReturnType<typeof derivePendingApprovals> = [];
60 const NO_PENDING_USER_INPUTS: ReturnType<typeof derivePendingUserInputs> = [];
61
62 +// Resolution can come from anywhere: another device, an interrupt, the turn
63 +// ending, or a thread that is not open. Question attachment drafts are pruned
64 +// by questionAttachments.ts, which owns them.
65 +onThreadRequestsResolved(({ environmentId, threadId, pendingRequestIds }) => {
66 + usePendingUserInputAnswers.setState(
67 + (existing) =>
68 + pruneResolvedUserInputDrafts(existing, environmentId, threadId, pendingRequestIds),
69 + true,
70 + );
71 + usePendingUserInputQuestionIndex.setState(
72 + (existing) =>
73 + pruneResolvedUserInputDrafts(existing, environmentId, threadId, pendingRequestIds),
74 + true,
75 + );
76 +});
77 +
78 function makePendingCustomAnswerSetter(input: {
79 readonly activePendingUserInput: PendingUserInput | null;
80 readonly activePendingRequestKey: string;
@@ -103,7 +111,6 @@ function makePendingCustomAnswerSetter(input: {
111 export function usePendingThreadRequests(input: {
112 readonly environmentId: EnvironmentId;
113 readonly activeThreadId: ThreadId | null;
106 - readonly activeThread: { readonly id: ThreadId } | undefined;
114 readonly serverProjection: ThreadStructure | null;
115 readonly supportsQuestionAttachments: boolean;
116 readonly composerDraftTarget: ScopedThreadRef | DraftId;
@@ -115,7 +122,6 @@ export function usePendingThreadRequests(input: {
122 const {
123 environmentId,
124 activeThreadId,
118 - activeThread,
125 serverProjection,
126 supportsQuestionAttachments,
127 composerDraftTarget,
@@ -140,7 +146,6 @@ export function usePendingThreadRequests(input: {
146 >([]);
147 const setPendingUserInputAnswersByRequestId = usePendingUserInputAnswers.setState;
148 const setPendingUserInputQuestionIndexByRequestId = usePendingUserInputQuestionIndex.setState;
143 - const projectedThreadId = serverProjection?.thread.id;
149 const pendingRequests =
150 serverProjection !== null && serverProjection.thread.id === activeThreadId
151 ? derivePendingThreadRequests(serverProjection)
@@ -156,25 +161,22 @@ export function usePendingThreadRequests(input: {
161 ? NO_PENDING_USER_INPUTS
162 : derivePendingUserInputs(pendingRequests.userInputs);
163 const activePendingUserInput = pendingUserInputs[0] ?? null;
159 - const activePendingRequestKey = pendingUserInputRequestKey(
164 + const activePendingRequestKey = userInputDraftKey(
165 environmentId,
166 activeThreadId,
167 activePendingUserInput?.requestId,
168 );
164 - const activePendingAnswerDrafts = usePendingUserInputAnswers(
169 + const storedPendingAnswerDrafts = usePendingUserInputAnswers(
170 (state) => state[activePendingRequestKey] ?? EMPTY_PENDING_USER_INPUT_ANSWERS,
171 );
172 + // Suggested answers are shown until the user edits them; only edits are stored.
173 + const activePendingAnswerDrafts: Record<string, PendingUserInputDraftAnswer> =
174 + activePendingUserInput
175 + ? seedUserInputDraftAnswers(activePendingUserInput.questions, storedPendingAnswerDrafts)
176 + : storedPendingAnswerDrafts;
177 const activePendingQuestionIndex = usePendingUserInputQuestionIndex(
178 (state) => state[activePendingRequestKey] ?? 0,
179 );
170 - useLayoutEffect(() => {
171 - if (!activePendingUserInput) return;
172 - usePendingUserInputAnswers.setState((existing) => {
173 - const drafts = existing[activePendingRequestKey] ?? EMPTY_PENDING_USER_INPUT_ANSWERS;
174 - const seeded = seedUserInputDraftAnswers(activePendingUserInput.questions, drafts);
175 - return seeded === drafts ? existing : { ...existing, [activePendingRequestKey]: seeded };
176 - });
177 - }, [activePendingRequestKey, activePendingUserInput]);
180 const pendingQuestionDraftKeys = activeThreadId
181 ? pendingUserInputs.flatMap((request) =>
182 request.questions.map((question) =>
@@ -211,44 +213,6 @@ export function usePendingThreadRequests(input: {
213 Object.fromEntries(pendingQuestionDraftKeys.map((key) => [key, state.counts[key] ?? 0])),
214 ),
215 );
214 - useEffect(() => {
215 - // A thread shell can arrive before its requests; missing detail is not resolution.
216 - if (!activeThread || projectedThreadId !== activeThread.id) return;
217 - const questionThread = activeThread;
218 - const currentRequests = pendingUserInputs;
219 - const pendingRequestIds = currentRequests.map((request) => request.requestId);
220 - usePendingUserInputAnswers.setState(
221 - (existing) =>
222 - pruneResolvedUserInputDrafts(existing, environmentId, questionThread.id, pendingRequestIds),
223 - true,
224 - );
225 - usePendingUserInputQuestionIndex.setState(
226 - (existing) =>
227 - pruneResolvedUserInputDrafts(existing, environmentId, questionThread.id, pendingRequestIds),
228 - true,
229 - );
230 - const prefix = questionAttachmentDraftPrefix(environmentId, questionThread.id);
231 - const retained = new Set(
232 - currentRequests.flatMap((request) =>
233 - request.questions.map((question) =>
234 - questionAttachmentDraftId(
235 - environmentId,
236 - questionThread.id,
237 - request.requestId,
238 - question.id,
239 - ),
240 - ),
241 - ),
242 - );
243 - const keys = new Set([
244 - ...Object.keys(useComposerDraftStore.getState().draftsByThreadKey),
245 - ...Object.keys(useQuestionAttachmentPreparation.getState().counts),
246 - ]);
247 - for (const key of keys) {
248 - if (key.startsWith(prefix) && !retained.has(DraftId.make(key)))
249 - clearQuestionAttachmentDraft(DraftId.make(key));
250 - }
251 - }, [environmentId, activeThread, projectedThreadId, pendingUserInputs]);
216 const activePendingDraftAnswers =
217 !activePendingUserInput || !activeThreadId
218 ? EMPTY_PENDING_USER_INPUT_ANSWERS
apps/web/src/pendingUserInput.ts
-29
@@ -112,35 +112,6 @@ export function setPendingUserInputCustomAnswer(
112 };
113 }
114
115 -export function pendingUserInputRequestKey(
116 - environmentId: string,
117 - threadId: string | null,
118 - requestId: string | undefined,
119 -): string {
120 - return JSON.stringify([environmentId, threadId, requestId]);
121 -}
122 -
123 -/** Drops a thread's drafts for requests that are no longer pending. Unchanged input is returned as is. */
124 -export function pruneResolvedUserInputDrafts<T>(
125 - draftsByRequestKey: Record<string, T>,
126 - environmentId: string,
127 - threadId: string,
128 - pendingRequestIds: ReadonlyArray<string>,
129 -): Record<string, T> {
130 - const threadPrefix = JSON.stringify([environmentId, threadId]).slice(0, -1);
131 - const pendingKeys = new Set(
132 - pendingRequestIds.map((requestId) =>
133 - pendingUserInputRequestKey(environmentId, threadId, requestId),
134 - ),
135 - );
136 - const retained = Object.entries(draftsByRequestKey).filter(
137 - ([key]) => !key.startsWith(threadPrefix) || pendingKeys.has(key),
138 - );
139 - return retained.length === Object.keys(draftsByRequestKey).length
140 - ? draftsByRequestKey
141 - : Object.fromEntries(retained);
142 -}
143 -
115 const DISPLACED_ANSWER_SEPARATOR = "\n\n";
116
117 export function carryDisplacedCustomAnswerIntoPrompt(
apps/web/src/questionAttachments.test.ts
+23 -1
@@ -1,4 +1,5 @@
1 -import { ApprovalRequestId, EnvironmentId, ThreadId } from "@t3tools/contracts";
1 +import { makeThreadRequestsResolvedAnnouncer } from "@t3tools/client-runtime/state/thread-requests";
2 +import { ApprovalRequestId, EnvironmentId, RuntimeRequestId, ThreadId } from "@t3tools/contracts";
3 import { beforeEach, expect, it, vi } from "vite-plus/test";
4 import { useComposerDraftStore } from "./composerDraftStore";
5 import {
@@ -114,3 +115,24 @@ it("counts files, images, and pending preparation across the shared question bud
115 changeQuestionAttachmentPreparation(second, -1);
116 expect(countQuestionAttachments([first, second])).toBe(7);
117 });
118 +
119 +it("clears attachment drafts for requests the thread resolved, wherever they were answered", () => {
120 + const store = useComposerDraftStore.getState();
121 + const pending = RuntimeRequestId.make("pending");
122 + const resolved = RuntimeRequestId.make("resolved");
123 + const otherThread = ThreadId.make("thread-2");
124 + const keep = questionAttachmentDraftId(environmentId, threadId, pending, "first");
125 + const drop = questionAttachmentDraftId(environmentId, threadId, resolved, "first");
126 + const elsewhere = questionAttachmentDraftId(environmentId, otherThread, resolved, "first");
127 + for (const key of [keep, drop, elsewhere]) store.setPrompt(key, "Answer context");
128 + changeQuestionAttachmentPreparation(drop, 1);
129 +
130 + // The thread's projection synchronizes with only `pending` left, e.g. after
131 + // `resolved` was answered on another device while no composer showed it.
132 + makeThreadRequestsResolvedAnnouncer(environmentId, threadId)([pending]);
133 +
134 + expect(store.getComposerDraft(keep)?.prompt).toBe("Answer context");
135 + expect(store.getComposerDraft(drop)).toBeNull();
136 + expect(store.getComposerDraft(elsewhere)?.prompt).toBe("Answer context");
137 + expect(useQuestionAttachmentPreparation.getState().counts[drop]).toBeUndefined();
138 +});
apps/web/src/questionAttachments.ts
+26
@@ -1,4 +1,8 @@
1 import { scopedThreadKey } from "@t3tools/client-runtime/environment";
2 +import {
3 + onThreadRequestsResolved,
4 + resolvedQuestionDraftKeys,
5 +} from "@t3tools/client-runtime/state/thread-requests";
6 import type { EnvironmentId, ScopedThreadRef, ThreadId } from "@t3tools/contracts";
7 import { create } from "zustand";
8 import { DraftId, useComposerDraftStore } from "./composerDraftStore";
@@ -92,3 +96,25 @@ export function clearQuestionAttachmentDraft(key: DraftId): void {
96 return { counts: next };
97 });
98 }
99 +
100 +/** Clears the thread's question attachment drafts for every request outside `pendingRequestIds`. */
101 +function pruneResolvedQuestionAttachmentDrafts(
102 + environmentId: EnvironmentId,
103 + threadId: ThreadId,
104 + pendingRequestIds: ReadonlyArray<string>,
105 +): void {
106 + const keys = new Set([
107 + ...Object.keys(useComposerDraftStore.getState().draftsByThreadKey),
108 + ...Object.keys(useQuestionAttachmentPreparation.getState().counts),
109 + ]);
110 + const prefix = questionAttachmentDraftPrefix(environmentId, threadId);
111 + for (const key of resolvedQuestionDraftKeys(keys, prefix, pendingRequestIds)) {
112 + clearQuestionAttachmentDraft(DraftId.make(key));
113 + }
114 +}
115 +
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 +);
packages/client-runtime/src/state/threadRequests.test.ts
+82
@@ -1,4 +1,5 @@
1 import {
2 + EnvironmentId,
3 NodeId,
4 ProviderSessionId,
5 RuntimeRequestId,
@@ -14,8 +15,14 @@ import {
15 derivePendingThreadRequests,
16 declinePendingApprovals,
17 sendApprovalFeedback,
18 + makeThreadRequestsResolvedAnnouncer,
19 + onThreadRequestsResolved,
20 + pruneResolvedUserInputDrafts,
21 + resolvedQuestionDraftKeys,
22 seedUserInputDraftAnswers,
23 + userInputDraftKey,
24 type ApprovalResponder,
25 + type ThreadRequestsResolved,
26 type ThreadPendingApproval,
27 } from "./threadRequests.ts";
28
@@ -117,6 +124,81 @@ describe("declining approvals before sending", () => {
124 });
125 });
126
127 +describe("pruning resolved user input drafts", () => {
128 + const answered = userInputDraftKey("env", "thread", "answered");
129 + const pending = userInputDraftKey("env", "thread", "pending");
130 + const otherThread = userInputDraftKey("env", "thread-2", "answered");
131 + const otherEnvironment = userInputDraftKey("env-2", "thread", "answered");
132 + const drafts = {
133 + [answered]: 1,
134 + [pending]: 2,
135 + [otherThread]: 3,
136 + [otherEnvironment]: 4,
137 + };
138 +
139 + it("drops only the thread's requests that are no longer pending", () => {
140 + expect(pruneResolvedUserInputDrafts(drafts, "env", "thread", ["pending"])).toEqual({
141 + [pending]: 2,
142 + [otherThread]: 3,
143 + [otherEnvironment]: 4,
144 + });
145 + });
146 +
147 + it("returns the same record when nothing resolved", () => {
148 + expect(pruneResolvedUserInputDrafts(drafts, "env", "thread", ["answered", "pending"])).toBe(
149 + drafts,
150 + );
151 + });
152 +});
153 +
154 +describe("resolved question draft keys", () => {
155 + const prefix = "env:question-thread-";
156 + const key = (request: string, question: string) =>
157 + `${prefix}${encodeURIComponent(JSON.stringify([request, question]))}`;
158 +
159 + it("returns the thread's keys for requests that are no longer pending", () => {
160 + const keys = [
161 + key("pending", "first"),
162 + key("pending", "second"),
163 + key("pending-2", "first"),
164 + key("answered", "first"),
165 + "env:question-other-thread-x",
166 + ];
167 + expect(resolvedQuestionDraftKeys(keys, prefix, [RuntimeRequestId.make("pending")])).toEqual([
168 + key("pending-2", "first"),
169 + key("answered", "first"),
170 + ]);
171 + });
172 +});
173 +
174 +describe("announcing resolved thread requests", () => {
175 + const environmentId = EnvironmentId.make("env");
176 + const threadId = v2Projection.thread.id;
177 + const first = RuntimeRequestId.make("first");
178 + const second = RuntimeRequestId.make("second");
179 +
180 + function record() {
181 + const events: ThreadRequestsResolved[] = [];
182 + const unsubscribe = onThreadRequestsResolved((event) => events.push(event));
183 + return { events, [Symbol.dispose]: unsubscribe };
184 + }
185 +
186 + it("announces the first projection, then only when a request leaves pending", () => {
187 + using recorder = record();
188 + const announce = makeThreadRequestsResolvedAnnouncer(environmentId, threadId);
189 +
190 + announce([first]);
191 + announce([first, second]);
192 + announce([first, second]);
193 + announce([second]);
194 +
195 + expect(recorder.events).toEqual([
196 + { environmentId, threadId, pendingRequestIds: [first] },
197 + { environmentId, threadId, pendingRequestIds: [second] },
198 + ]);
199 + });
200 +});
201 +
202 describe("initial user input drafts", () => {
203 const questions = [
204 { id: "editor", initialAnswer: " Proposed commit\n\n" },
packages/client-runtime/src/state/threadRequests.ts
+115
@@ -1,4 +1,6 @@
1 import type {
2 + EnvironmentId,
3 + ThreadId,
4 OrchestrationV2ThreadProjection,
5 OrchestrationV2RuntimeRequest,
6 OrchestrationV2UserInputQuestion,
@@ -106,6 +108,119 @@ export function seedUserInputDraftAnswers<Draft extends { readonly customAnswer?
108 return seeded;
109 }
110
111 +/** Keys a user-input draft by thread so a thread's resolved requests can be pruned together. */
112 +export function userInputDraftKey(
113 + environmentId: string,
114 + threadId: string | null,
115 + requestId: string | undefined,
116 +): string {
117 + return JSON.stringify([environmentId, threadId, requestId]);
118 +}
119 +
120 +/**
121 + * Drops the thread's drafts for requests outside `pendingRequestIds`, leaving
122 + * other threads alone. Returns the input itself when nothing is dropped.
123 + */
124 +export function pruneResolvedUserInputDrafts<T>(
125 + draftsByRequestKey: Record<string, T>,
126 + environmentId: string,
127 + threadId: string,
128 + pendingRequestIds: ReadonlyArray<string>,
129 +): Record<string, T> {
130 + const threadPrefix = JSON.stringify([environmentId, threadId]).slice(0, -1);
131 + const pendingKeys = new Set(
132 + pendingRequestIds.map((requestId) => userInputDraftKey(environmentId, threadId, requestId)),
133 + );
134 + const retained = Object.entries(draftsByRequestKey).filter(
135 + ([key]) => !key.startsWith(threadPrefix) || pendingKeys.has(key),
136 + );
137 + return retained.length === Object.keys(draftsByRequestKey).length
138 + ? draftsByRequestKey
139 + : Object.fromEntries(retained);
140 +}
141 +
142 +/**
143 + * Question attachment drafts are keyed `<thread prefix><encoded [requestId, questionId]>`.
144 + * Returns the keys under `threadPrefix` whose request is outside `pendingRequestIds`.
145 + */
146 +export function resolvedQuestionDraftKeys(
147 + keys: Iterable<string>,
148 + threadPrefix: string,
149 + pendingRequestIds: ReadonlyArray<string>,
150 +): string[] {
151 + // encodeURIComponent is per character, so an encoded JSON prefix prefixes the encoded key.
152 + const pendingPrefixes = pendingRequestIds.map(
153 + (requestId) =>
154 + `${threadPrefix}${encodeURIComponent(`${JSON.stringify([requestId]).slice(0, -1)},`)}`,
155 + );
156 + const resolved: string[] = [];
157 + for (const key of keys) {
158 + if (key.startsWith(threadPrefix) && !pendingPrefixes.some((prefix) => key.startsWith(prefix)))
159 + resolved.push(key);
160 + }
161 + return resolved;
162 +}
163 +
164 +export interface ThreadRequestsResolved {
165 + readonly environmentId: EnvironmentId;
166 + readonly threadId: ThreadId;
167 + /** Every request the thread still waits on; drafts for any other request are stale. */
168 + readonly pendingRequestIds: ReadonlyArray<RuntimeRequestId>;
169 +}
170 +
171 +const threadRequestsResolvedListeners = new Set<(event: ThreadRequestsResolved) => void>();
172 +
173 +/**
174 + * Clients register draft pruners once at module level. Thread state announces
175 + * when its synchronized projection first lands and whenever a request leaves
176 + * pending, wherever the resolution came from (another device, interrupt, turn end).
177 + */
178 +export function onThreadRequestsResolved(
179 + listener: (event: ThreadRequestsResolved) => void,
180 +): () => void {
181 + threadRequestsResolvedListeners.add(listener);
182 + return () => threadRequestsResolvedListeners.delete(listener);
183 +}
184 +
185 +function notifyThreadRequestsResolved(event: ThreadRequestsResolved): void {
186 + for (const listener of threadRequestsResolvedListeners) {
187 + try {
188 + listener(event);
189 + } catch (error) {
190 + // A failing pruner must neither stop the others nor break thread sync.
191 + queueMicrotask(() => {
192 + throw error;
193 + });
194 + }
195 + }
196 +}
197 +
198 +/**
199 + * Tracks one thread's announced pending requests. Feed it the pending ids of
200 + * each authoritative projection; it notifies on the first one and whenever an
201 + * announced request is no longer pending. New requests alone stay quiet.
202 + */
203 +export function makeThreadRequestsResolvedAnnouncer(
204 + environmentId: EnvironmentId,
205 + threadId: ThreadId,
206 +) {
207 + let announced: ReadonlySet<RuntimeRequestId> | null = null;
208 + return (pendingRequestIds: ReadonlyArray<RuntimeRequestId>) => {
209 + const pending = new Set(pendingRequestIds);
210 + const resolvedSome = announced === null || [...announced].some((id) => !pending.has(id));
211 + announced = pending;
212 + if (resolvedSome) notifyThreadRequestsResolved({ environmentId, threadId, pendingRequestIds });
213 + };
214 +}
215 +
216 +export function pendingRuntimeRequestIds(
217 + projection: Pick<OrchestrationV2ThreadProjection, "runtimeRequests">,
218 +): RuntimeRequestId[] {
219 + return projection.runtimeRequests.flatMap((request) =>
220 + request.status === "pending" ? [request.id] : [],
221 + );
222 +}
223 +
224 export function derivePendingThreadRequests(
225 projection: Pick<ThreadStructure, "runtimeRequests" | "turnItems">,
226 ): PendingThreadRequests {
packages/client-runtime/src/state/threads-sync.test.ts
+74 -7
@@ -2,7 +2,9 @@ import {
2 EnvironmentId,
3 EventId,
4 MessageId,
5 + NodeId,
6 ORCHESTRATION_V2_WS_METHODS,
7 + RuntimeRequestId,
8 ThreadId,
9 TurnItemId,
10 type OrchestrationV2ThreadDetailSnapshot,
@@ -43,7 +45,8 @@ import {
45 decodeOrDiscardOrchestrationCache,
46 } from "../platform/orchestrationCache.ts";
47 import * as RpcSession from "../rpc/session.ts";
46 -import { v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts";
48 +import { v2Now, v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts";
49 +import { onThreadRequestsResolved, type ThreadRequestsResolved } from "./threadRequests.ts";
50 import { EMPTY_THREAD_HISTORY_META } from "./threadHistoryMerge.ts";
51 import * as ThreadHistoryController from "./threadHistoryController.ts";
52 import {
@@ -303,6 +306,30 @@ const snapshot = (
306
307 const synchronized = (): OrchestrationV2ThreadStreamItem => ({ kind: "synchronized" });
308
309 +const PENDING_QUESTION = {
310 + id: RuntimeRequestId.make("question"),
311 + nodeId: NodeId.make("question-node"),
312 + providerTurnId: null,
313 + nativeRequestRef: null,
314 + kind: "user_input" as const,
315 + status: "pending" as const,
316 + responseCapability: { type: "message" as const },
317 + createdAt: v2Now,
318 + resolvedAt: null,
319 +};
320 +
321 +const questionResolved = (sequence: number): OrchestrationV2ThreadStreamItem => ({
322 + kind: "event",
323 + sequence,
324 + event: {
325 + id: EventId.make("event-request"),
326 + type: "runtime-request.updated",
327 + threadId: THREAD_ID,
328 + occurredAt: v2Now,
329 + payload: { ...PENDING_QUESTION, status: "resolved", resolvedAt: v2Now },
330 + },
331 +});
332 +
333 const titleUpdated = (title: string, sequence = 2): OrchestrationV2ThreadStreamItem => {
334 const occurredAt = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
335 return {
@@ -520,6 +547,11 @@ describe("EnvironmentThreads", () => {
547
548 it.effect("prevents an old scope from replacing its successor's cached data", () =>
549 Effect.gen(function* () {
550 + const announced: ThreadRequestsResolved[] = [];
551 + yield* Effect.acquireRelease(
552 + Effect.sync(() => onThreadRequestsResolved((event) => announced.push(event))),
553 + (unsubscribe) => Effect.sync(unsubscribe),
554 + );
555 const resumeCache: NonNullable<Parameters<typeof makeEnvironmentThreadState>[1]> = {
556 snapshot: undefined,
557 owner: undefined,
@@ -527,24 +559,28 @@ describe("EnvironmentThreads", () => {
559 const oldScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
560 Scope.close(scope, Exit.void),
561 );
530 - const old = yield* makeHarness({ cached: BASE_PROJECTION, resumeCache }).pipe(
531 - Effect.provideService(Scope.Scope, oldScope),
532 - );
562 + const old = yield* makeHarness({
563 + cached: { ...BASE_PROJECTION, runtimeRequests: [PENDING_QUESTION] },
564 + resumeCache,
565 + }).pipe(Effect.provideService(Scope.Scope, oldScope));
566 yield* awaitThreadState(old.observed, (value) => value.status === "live");
567 const successor = yield* makeHarness({ resumeCache });
535 - yield* Queue.offer(successor.inputs, titleUpdated("Successor title", 9));
568 + yield* Queue.offer(successor.inputs, titleUpdated("Successor title", 10));
569 yield* awaitThreadState(
570 successor.observed,
571 (value) => Option.getOrNull(value.data)?.thread.title === "Successor title",
572 );
540 - yield* Queue.offer(old.inputs, titleUpdated("Old scope title", 8));
573 + announced.length = 0;
574 + yield* Queue.offerAll(old.inputs, [questionResolved(8), titleUpdated("Old scope title", 9)]);
575 yield* awaitThreadState(
576 old.observed,
577 (value) => Option.getOrNull(value.data)?.thread.title === "Old scope title",
578 );
579 yield* Scope.close(oldScope, Exit.void);
580
547 - expect(resumeCache.snapshot?.sequence).toBe(9);
581 + // Draft pruners would delete the answer the successor still waits on.
582 + expect(announced).toEqual([]);
583 + expect(resumeCache.snapshot?.sequence).toBe(10);
584 expect(Option.getOrThrow(resumeCache.snapshot!.state.data).thread.title).toBe(
585 "Successor title",
586 );
@@ -1797,6 +1833,37 @@ describe("EnvironmentThreads", () => {
1833 }),
1834 );
1835
1836 + it.effect("announces request resolution only from a synchronized projection", () =>
1837 + Effect.gen(function* () {
1838 + const announced = yield* Queue.unbounded<ThreadRequestsResolved>();
1839 + yield* Effect.acquireRelease(
1840 + Effect.sync(() => onThreadRequestsResolved((event) => Queue.offerUnsafe(announced, event))),
1841 + (unsubscribe) => Effect.sync(unsubscribe),
1842 + );
1843 + const harness = yield* makeHarness({
1844 + cached: { ...BASE_PROJECTION, runtimeRequests: [PENDING_QUESTION] },
1845 + completionMarker: true,
1846 + });
1847 + yield* awaitThreadState(
1848 + harness.observed,
1849 + (value) => value.status === "synchronizing" && Option.isSome(value.data),
1850 + );
1851 +
1852 + // Answered on another device while this client was away.
1853 + yield* Queue.offerAll(harness.inputs, [
1854 + questionResolved(CACHED_SNAPSHOT_SEQUENCE + 1),
1855 + synchronized(),
1856 + ]);
1857 +
1858 + expect(yield* Queue.take(announced)).toEqual({
1859 + environmentId: TARGET.environmentId,
1860 + threadId: THREAD_ID,
1861 + pendingRequestIds: [],
1862 + });
1863 + expect(yield* Queue.size(announced)).toBe(0);
1864 + }),
1865 + );
1866 +
1867 it.effect("skips an unknown event type and resumes after it", () =>
1868 Effect.gen(function* () {
1869 const harness = yield* makeHarness({ cached: BASE_PROJECTION, completionMarker: true });
packages/client-runtime/src/state/threads.ts
+9
@@ -48,6 +48,7 @@ import {
48 type ThreadHistoryMeta,
49 } from "./threadHistoryMerge.ts";
50 import * as ThreadSnapshotLoader from "./threadSnapshotHttp.ts";
51 +import { makeThreadRequestsResolvedAnnouncer, pendingRuntimeRequestIds } from "./threadRequests.ts";
52 import {
53 EMPTY_ENVIRONMENT_THREAD_STATE,
54 type EnvironmentThreadState,
@@ -254,9 +255,17 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
255 const applyLock = yield* Semaphore.make(1);
256 // Save only completed data/cursor updates. A canceled scope must not cache
257 // a cursor whose event has not reached the data yet.
258 + const announceRequests = makeThreadRequestsResolvedAnnouncer(environmentId, threadId);
259 const remember = Effect.gen(function* () {
260 const current = yield* SubscriptionRef.get(state);
261 const sequence = yield* SubscriptionRef.get(lastSequence);
262 + // Only a synchronized projection from the scope that owns the thread is
263 + // authoritative: a cached one can predate a request the user already has
264 + // drafts for, and a superseded scope can lag its successor.
265 + const owns = resumeCache === undefined || resumeCache.owner === owner;
266 + if (owns && current.status === "deleted") announceRequests([]);
267 + else if (owns && current.status === "live" && Option.isSome(current.data))
268 + announceRequests(pendingRuntimeRequestIds(current.data.value));
269 committed = {
270 state: current,
271 sequence,