Skip to content

Commit 47e0c14

Browse files
fix(client): drafts for answered questions are cleared even when their thread is not open
Answer drafts, question positions and question attachment drafts were pruned by an effect in the open composer (web) and only for attachments (mobile), so a question answered on another device, interrupted, or ended with the turn left its drafts behind until that thread was opened again. Question attachment drafts persist across reloads, so they could linger indefinitely. Mobile never pruned answer drafts at all. Suggested answers were also copied into the draft store by a layout effect, costing an extra render. Thread state in client-runtime now announces when a thread's synchronized projection first lands and whenever a request leaves pending (only from the scope that owns the thread). Web and mobile register their draft pruners once at module level. Suggested answers are seeded at read time; only edits are stored. Mobile also prunes the answered request's drafts once the server accepts the response. Effects: usePendingThreadRequests.ts 2 -> 0, use-selected-thread-requests.ts 2 -> 0. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 0712398 commit 47e0c14

12 files changed

Lines changed: 489 additions & 168 deletions
Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { EnvironmentId, ProjectId, RuntimeRequestId, ThreadId } from "@t3tools/contracts";
1+
import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
22

33
export function scopedProjectKey(environmentId: EnvironmentId, projectId: ProjectId): string {
44
return `${environmentId}:${projectId}`;
@@ -7,10 +7,3 @@ export function scopedProjectKey(environmentId: EnvironmentId, projectId: Projec
77
export function scopedThreadKey(environmentId: EnvironmentId, threadId: ThreadId): string {
88
return `${environmentId}:${threadId}`;
99
}
10-
11-
export function scopedRequestKey(
12-
environmentId: EnvironmentId,
13-
requestId: RuntimeRequestId,
14-
): string {
15-
return `${environmentId}:${requestId}`;
16-
}

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

Lines changed: 123 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -16,19 +16,27 @@ import {
1616
composerAttachmentsStillUploading,
1717
} from "./composer-attachment-uploads";
1818
import { useAtomValue } from "@effect/atom-react";
19-
import { useCallback, useEffect, useRef, useState } from "react";
19+
import { useCallback, useRef, useState } from "react";
2020

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";
2227
import {
2328
type PendingThreadRequests,
2429
type ThreadUserInputQuestion,
30+
onThreadRequestsResolved,
31+
pruneResolvedUserInputDrafts,
32+
resolvedQuestionDraftKeys,
2533
seedUserInputDraftAnswers,
34+
userInputDraftKey,
2635
} from "@t3tools/client-runtime/state/thread-requests";
2736
import { AuthOrchestrationOperateScope } from "@t3tools/contracts";
2837
import { Atom } from "effect/reactivity";
2938

30-
import { threadEnvironment } from "../state/threads";
31-
import { scopedRequestKey } from "../lib/scopedEntities";
39+
import { environmentThreadDetails, threadEnvironment } from "../state/threads";
3240
import {
3341
buildPendingUserInputAnswers,
3442
setPendingUserInputCustomAnswer,
@@ -47,6 +55,14 @@ const userInputDraftsByRequestKeyAtom = Atom.make<
4755
Record<string, Record<string, PendingUserInputDraftAnswer>>
4856
>({}).pipe(Atom.keepAlive, Atom.withLabel("mobile:user-input-drafts"));
4957

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+
5066
function setUserInputDraftOption(
5167
requestKey: string,
5268
question: ThreadUserInputQuestion,
@@ -59,7 +75,7 @@ function setUserInputDraftOption(
5975
...current[requestKey],
6076
[question.id]: togglePendingUserInputOptionSelection(
6177
question,
62-
current[requestKey]?.[question.id],
78+
seededDraft(current[requestKey], question),
6379
value,
6480
),
6581
},
@@ -78,13 +94,75 @@ function setUserInputDraftCustomAnswer(
7894
...current[requestKey],
7995
[question.id]: setPendingUserInputCustomAnswer(
8096
question,
81-
current[requestKey]?.[question.id],
97+
seededDraft(current[requestKey], question),
8298
customAnswer,
8399
),
84100
},
85101
});
86102
}
87103

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+
88166
export function useSelectedThreadRequests() {
89167
const respondToApproval = useAtomCommand(
90168
threadEnvironment.respondToApproval,
@@ -109,19 +187,6 @@ export function useSelectedThreadRequests() {
109187
const activePendingApproval = activePendingApprovals[0] ?? null;
110188
const activePendingUserInputs = pendingRequests?.userInputs ?? EMPTY_PENDING_REQUESTS.userInputs;
111189
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]);
125190
const questionServerConfigs = useServerConfigs();
126191
const attachmentDrafts = useAtomValue(
127192
questionAttachmentDraftsAtom(
@@ -132,36 +197,20 @@ export function useSelectedThreadRequests() {
132197
);
133198
const preparationCounts = useAtomValue(questionAttachmentPreparationAtom);
134199
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+
: {};
165214
const activePendingUserInputDrafts =
166215
activePendingUserInput && selectedThreadShell
167216
? Object.fromEntries(
@@ -182,12 +231,7 @@ export function useSelectedThreadRequests() {
182231
return [
183232
question.id,
184233
{
185-
...userInputDraftsByRequestKey[
186-
scopedRequestKey(
187-
selectedThreadShell.environmentId,
188-
activePendingUserInput.requestId,
189-
)
190-
]?.[question.id],
234+
...activePendingUserInputAnswerDrafts[question.id],
191235
attachmentCount: attachments.length,
192236
attachmentsBlocked:
193237
(attachments.length > 0 &&
@@ -214,7 +258,11 @@ export function useSelectedThreadRequests() {
214258
return;
215259
}
216260

217-
const requestKey = scopedRequestKey(selectedThreadShell.environmentId, requestId);
261+
const requestKey = userInputDraftKey(
262+
selectedThreadShell.environmentId,
263+
selectedThreadShell.id,
264+
requestId,
265+
);
218266
setUserInputDraftOption(requestKey, question, value);
219267
},
220268
[selectedThreadShell],
@@ -229,7 +277,11 @@ export function useSelectedThreadRequests() {
229277
return;
230278
}
231279

232-
const requestKey = scopedRequestKey(selectedThreadShell.environmentId, requestId);
280+
const requestKey = userInputDraftKey(
281+
selectedThreadShell.environmentId,
282+
selectedThreadShell.id,
283+
requestId,
284+
);
233285
setUserInputDraftCustomAnswer(requestKey, question, customAnswer);
234286
},
235287
[activePendingUserInputs, selectedThreadShell],
@@ -339,6 +391,13 @@ export function useSelectedThreadRequests() {
339391
setRespondingUserInputId((current) =>
340392
current === activePendingUserInput.requestId ? null : current,
341393
);
394+
if (result._tag === "Success") {
395+
collectAnsweredRequestDrafts(
396+
selectedThreadShell.environmentId,
397+
selectedThreadShell.id,
398+
activePendingUserInput.requestId,
399+
);
400+
}
342401
return result;
343402
}, [
344403
activePendingUserInput,
@@ -367,6 +426,13 @@ export function useSelectedThreadRequests() {
367426
setRespondingUserInputId((current) =>
368427
current === activePendingUserInput.requestId ? null : current,
369428
);
429+
if (result._tag === "Success") {
430+
collectAnsweredRequestDrafts(
431+
selectedThreadShell.environmentId,
432+
selectedThreadShell.id,
433+
activePendingUserInput.requestId,
434+
);
435+
}
370436
return result;
371437
}, [activePendingUserInput, dismissUserInput, selectedThreadShell]);
372438

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

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1272,7 +1272,6 @@ export default function ChatView(props: ChatViewProps) {
12721272
} = usePendingThreadRequests({
12731273
environmentId,
12741274
activeThreadId,
1275-
activeThread,
12761275
serverProjection,
12771276
supportsQuestionAttachments,
12781277
composerDraftTarget,

‎apps/web/src/components/chat/ComposerPendingUserInputPanel.navigation.browser.test.tsx‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
TurnItemId,
77
type OrchestrationV2ThreadProjection,
88
} from "@t3tools/contracts";
9+
import { makeThreadRequestsResolvedAnnouncer } from "@t3tools/client-runtime/state/thread-requests";
910
import { useLayoutEffect, useRef, type ComponentProps } from "react";
1011
import { expect, it, vi } from "vite-plus/test";
1112

@@ -88,7 +89,6 @@ function PendingRequestsProbe({
8889
const state = usePendingThreadRequests({
8990
environmentId,
9091
activeThreadId: projection.thread.id,
91-
activeThread: projection.thread,
9292
serverProjection: loading ? null : projection,
9393
supportsQuestionAttachments: false,
9494
composerDraftTarget: { environmentId, threadId: projection.thread.id },
@@ -161,6 +161,7 @@ it("isolates drafts by environment, thread and request and discards only resolve
161161
await act(() => requests.onAdvanceActivePendingUserInput());
162162
}
163163

164+
// "first" was answered on another device.
164165
await show({
165166
environmentId,
166167
projection: {
@@ -173,6 +174,12 @@ it("isolates drafts by environment, thread and request and discards only resolve
173174
},
174175
});
175176
expect(requests.activePendingUserInput?.requestId).toBe("second");
177+
await act(() =>
178+
makeThreadRequestsResolvedAnnouncer(
179+
environmentId,
180+
threadRef.threadId,
181+
)([RuntimeRequestId.make("second")]),
182+
);
176183
for (const [index, scope] of scopes.entries()) {
177184
await show(scope);
178185
expect(requests.activePendingQuestionIndex).toBe(index === 0 ? 0 : 1);

0 commit comments

Comments
 (0)