TypeScript
fix(client): drafts for answered questions are cleared even when their thread is not open (#25457)
Julius Marminged5a791b94041
diff --git a/apps/mobile/src/lib/scopedEntities.ts b/apps/mobile/src/lib/scopedEntities.tsindex 6464b356191..2f8dde6e571 100644--- a/apps/mobile/src/lib/scopedEntities.ts+++ b/apps/mobile/src/lib/scopedEntities.ts@@ -1,4 +1,4 @@-import { EnvironmentId, ProjectId, RuntimeRequestId, ThreadId } from "@t3tools/contracts";+import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";export function scopedProjectKey(environmentId: EnvironmentId, projectId: ProjectId): string {return `${environmentId}:${projectId}`;@@ -7,10 +7,3 @@ export function scopedProjectKey(environmentId: EnvironmentId, projectId: Projecexport function scopedThreadKey(environmentId: EnvironmentId, threadId: ThreadId): string {return `${environmentId}:${threadId}`;}--export function scopedRequestKey(- environmentId: EnvironmentId,- requestId: RuntimeRequestId,-): string {- return `${environmentId}:${requestId}`;-}diff --git a/apps/mobile/src/state/thread-task-permissions.test.ts b/apps/mobile/src/state/thread-task-permissions.test.tsindex 4c962cf5be6..5697ca63e5e 100644--- a/apps/mobile/src/state/thread-task-permissions.test.ts+++ b/apps/mobile/src/state/thread-task-permissions.test.ts@@ -113,6 +113,7 @@ vi.mock("./threads", async () => {environmentThreadDetails: {queueWorkflowAtom: () => Atom.make(null),checkpointSummariesAtom: () => Atom.make([]),+ pendingRequestsAtom: () => Atom.make(state.pendingRequests),},threadEnvironment: {respondToApproval: state.approve,diff --git a/apps/mobile/src/state/use-selected-thread-requests.ts b/apps/mobile/src/state/use-selected-thread-requests.tsindex 1371b520604..462c4d6f076 100644--- a/apps/mobile/src/state/use-selected-thread-requests.ts+++ b/apps/mobile/src/state/use-selected-thread-requests.ts@@ -16,19 +16,27 @@ import {composerAttachmentsStillUploading,} from "./composer-attachment-uploads";import { useAtomValue } from "@effect/atom-react";-import { useCallback, useEffect, useRef, useState } from "react";+import { useCallback, useRef, useState } from "react";-import { type ProviderApprovalDecision, type RuntimeRequestId } from "@t3tools/contracts";+import {+ type EnvironmentId,+ type ProviderApprovalDecision,+ type RuntimeRequestId,+ type ThreadId,+} from "@t3tools/contracts";import {type PendingThreadRequests,type ThreadUserInputQuestion,+ onThreadRequestsResolved,+ pruneResolvedUserInputDrafts,+ resolvedQuestionDraftKeys,seedUserInputDraftAnswers,+ userInputDraftKey,} from "@t3tools/client-runtime/state/thread-requests";import { AuthOrchestrationOperateScope } from "@t3tools/contracts";import { Atom } from "effect/reactivity";-import { threadEnvironment } from "../state/threads";-import { scopedRequestKey } from "../lib/scopedEntities";+import { environmentThreadDetails, threadEnvironment } from "../state/threads";import {buildPendingUserInputAnswers,setPendingUserInputCustomAnswer,@@ -47,6 +55,14 @@ const userInputDraftsByRequestKeyAtom = Atom.make<Record<string, Record<string, PendingUserInputDraftAnswer>>>({}).pipe(Atom.keepAlive, Atom.withLabel("mobile:user-input-drafts"));+// Writes start from the suggested answer the user was looking at.+function seededDraft(+ drafts: Record<string, PendingUserInputDraftAnswer> | undefined,+ question: ThreadUserInputQuestion,+): PendingUserInputDraftAnswer | undefined {+ return seedUserInputDraftAnswers([question], drafts ?? {})[question.id];+}+function setUserInputDraftOption(requestKey: string,question: ThreadUserInputQuestion,@@ -59,7 +75,7 @@ function setUserInputDraftOption(...current[requestKey],[question.id]: togglePendingUserInputOptionSelection(question,- current[requestKey]?.[question.id],+ seededDraft(current[requestKey], question),value,),},@@ -78,13 +94,75 @@ function setUserInputDraftCustomAnswer(...current[requestKey],[question.id]: setPendingUserInputCustomAnswer(question,- current[requestKey]?.[question.id],+ seededDraft(current[requestKey], question),customAnswer,),},});}+/** Drops a thread's answer and attachment drafts for every request outside `pendingRequestIds`. */+function pruneResolvedRequestDrafts(+ environmentId: EnvironmentId,+ threadId: ThreadId,+ pendingRequestIds: ReadonlyArray<RuntimeRequestId>,+): void {+ const drafts = appAtomRegistry.get(userInputDraftsByRequestKeyAtom);+ const prunedDrafts = pruneResolvedUserInputDrafts(+ drafts,+ environmentId,+ threadId,+ pendingRequestIds,+ );+ if (prunedDrafts !== drafts) appAtomRegistry.set(userInputDraftsByRequestKeyAtom, prunedDrafts);++ const prefix = questionAttachmentDraftPrefix(environmentId, threadId);+ const attachmentDrafts = appAtomRegistry.get(questionAttachmentDraftsAtom(prefix));+ const counts = { ...appAtomRegistry.get(questionAttachmentPreparationAtom) };+ let changed = false;+ for (const key of resolvedQuestionDraftKeys(+ new Set([...Object.keys(attachmentDrafts), ...Object.keys(counts)]),+ prefix,+ pendingRequestIds,+ )) {+ if (attachmentDrafts[key]) clearComposerDraft(key);+ if (key in counts) {+ delete counts[key];+ changed = true;+ }+ }+ if (changed) appAtomRegistry.set(questionAttachmentPreparationAtom, counts);+}++// Resolution can come from anywhere: another device, an interrupt, the turn+// ending, or a reload over drafts for requests that resolved meanwhile.+onThreadRequestsResolved(({ environmentId, threadId, pendingRequestIds }) =>+ pruneResolvedRequestDrafts(environmentId, threadId, pendingRequestIds),+);++/**+ * Drops `answeredRequestId`'s drafts as soon as the server accepts the+ * response, before the projection push that resolves it lands.+ */+function collectAnsweredRequestDrafts(+ environmentId: EnvironmentId,+ threadId: ThreadId,+ answeredRequestId: RuntimeRequestId,+) {+ const current = appAtomRegistry.get(+ environmentThreadDetails.pendingRequestsAtom({ environmentId, threadId }),+ );+ // Missing detail is not resolution.+ if (current === null) return;+ pruneResolvedRequestDrafts(+ environmentId,+ threadId,+ [...current.approvals, ...current.userInputs]+ .map((request) => request.requestId)+ .filter((requestId) => requestId !== answeredRequestId),+ );+}+export function useSelectedThreadRequests() {const respondToApproval = useAtomCommand(threadEnvironment.respondToApproval,@@ -109,19 +187,6 @@ export function useSelectedThreadRequests() {const activePendingApproval = activePendingApprovals[0] ?? null;const activePendingUserInputs = pendingRequests?.userInputs ?? EMPTY_PENDING_REQUESTS.userInputs;const activePendingUserInput = activePendingUserInputs[0] ?? null;- useEffect(() => {- if (!activePendingUserInput || !selectedThreadShell) return;- const requestKey = scopedRequestKey(- selectedThreadShell.environmentId,- activePendingUserInput.requestId,- );- const existing = appAtomRegistry.get(userInputDraftsByRequestKeyAtom);- const drafts = existing[requestKey] ?? {};- const seeded = seedUserInputDraftAnswers(activePendingUserInput.questions, drafts);- if (seeded !== drafts) {- appAtomRegistry.set(userInputDraftsByRequestKeyAtom, { ...existing, [requestKey]: seeded });- }- }, [activePendingUserInput, selectedThreadShell]);const questionServerConfigs = useServerConfigs();const attachmentDrafts = useAtomValue(questionAttachmentDraftsAtom(@@ -132,36 +197,20 @@ export function useSelectedThreadRequests() {);const preparationCounts = useAtomValue(questionAttachmentPreparationAtom);const uploadStates = useAtomValue(composerAttachmentUploadsAtom);- useEffect(() => {- if (!selectedThreadShell || !pendingRequests) return;- const prefix = questionAttachmentDraftPrefix(- selectedThreadShell.environmentId,- selectedThreadShell.id,- );- const retained = new Set(- activePendingUserInputs.flatMap((request) =>- request.questions.map((question) =>- questionAttachmentDraftKey(- selectedThreadShell.environmentId,- selectedThreadShell.id,- request.requestId,- question.id,- ),- ),- ),- );- const counts = { ...appAtomRegistry.get(questionAttachmentPreparationAtom) };- let changed = false;- for (const key of new Set([...Object.keys(attachmentDrafts), ...Object.keys(counts)])) {- if (!key.startsWith(prefix) || retained.has(key)) continue;- if (attachmentDrafts[key]) clearComposerDraft(key);- if (key in counts) {- delete counts[key];- changed = true;- }- }- if (changed) appAtomRegistry.set(questionAttachmentPreparationAtom, counts);- }, [activePendingUserInputs, attachmentDrafts, pendingRequests, selectedThreadShell]);+ // Suggested answers are shown until the user edits them; only edits are stored.+ const activePendingUserInputAnswerDrafts =+ activePendingUserInput && selectedThreadShell+ ? seedUserInputDraftAnswers(+ activePendingUserInput.questions,+ userInputDraftsByRequestKey[+ userInputDraftKey(+ selectedThreadShell.environmentId,+ selectedThreadShell.id,+ activePendingUserInput.requestId,+ )+ ] ?? {},+ )+ : {};const activePendingUserInputDrafts =activePendingUserInput && selectedThreadShell? Object.fromEntries(@@ -182,12 +231,7 @@ export function useSelectedThreadRequests() {return [question.id,{- ...userInputDraftsByRequestKey[- scopedRequestKey(- selectedThreadShell.environmentId,- activePendingUserInput.requestId,- )- ]?.[question.id],+ ...activePendingUserInputAnswerDrafts[question.id],attachmentCount: attachments.length,attachmentsBlocked:(attachments.length > 0 &&@@ -214,7 +258,11 @@ export function useSelectedThreadRequests() {return;}- const requestKey = scopedRequestKey(selectedThreadShell.environmentId, requestId);+ const requestKey = userInputDraftKey(+ selectedThreadShell.environmentId,+ selectedThreadShell.id,+ requestId,+ );setUserInputDraftOption(requestKey, question, value);},[selectedThreadShell],@@ -229,7 +277,11 @@ export function useSelectedThreadRequests() {return;}- const requestKey = scopedRequestKey(selectedThreadShell.environmentId, requestId);+ const requestKey = userInputDraftKey(+ selectedThreadShell.environmentId,+ selectedThreadShell.id,+ requestId,+ );setUserInputDraftCustomAnswer(requestKey, question, customAnswer);},[activePendingUserInputs, selectedThreadShell],@@ -339,6 +391,13 @@ export function useSelectedThreadRequests() {setRespondingUserInputId((current) =>current === activePendingUserInput.requestId ? null : current,);+ if (result._tag === "Success") {+ collectAnsweredRequestDrafts(+ selectedThreadShell.environmentId,+ selectedThreadShell.id,+ activePendingUserInput.requestId,+ );+ }return result;}, [activePendingUserInput,@@ -367,6 +426,13 @@ export function useSelectedThreadRequests() {setRespondingUserInputId((current) =>current === activePendingUserInput.requestId ? null : current,);+ if (result._tag === "Success") {+ collectAnsweredRequestDrafts(+ selectedThreadShell.environmentId,+ selectedThreadShell.id,+ activePendingUserInput.requestId,+ );+ }return result;}, [activePendingUserInput, dismissUserInput, selectedThreadShell]);diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex 587bd706ccb..72ad50679d6 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -1272,7 +1272,6 @@ export default function ChatView(props: ChatViewProps) {} = usePendingThreadRequests({environmentId,activeThreadId,- activeThread,serverProjection,supportsQuestionAttachments,composerDraftTarget,diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.navigation.browser.test.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.navigation.browser.test.tsxindex e6eecd6ad6f..52800d94a8b 100644--- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.navigation.browser.test.tsx+++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.navigation.browser.test.tsx@@ -6,6 +6,7 @@ import {TurnItemId,type OrchestrationV2ThreadProjection,} from "@t3tools/contracts";+import { makeThreadRequestsResolvedAnnouncer } from "@t3tools/client-runtime/state/thread-requests";import { useLayoutEffect, useRef, type ComponentProps } from "react";import { expect, it, vi } from "vite-plus/test";@@ -88,7 +89,6 @@ function PendingRequestsProbe({const state = usePendingThreadRequests({environmentId,activeThreadId: projection.thread.id,- activeThread: projection.thread,serverProjection: loading ? null : projection,supportsQuestionAttachments: false,composerDraftTarget: { environmentId, threadId: projection.thread.id },@@ -161,6 +161,7 @@ it("isolates drafts by environment, thread and request and discards only resolveawait act(() => requests.onAdvanceActivePendingUserInput());}+ // "first" was answered on another device.await show({environmentId,projection: {@@ -173,6 +174,12 @@ it("isolates drafts by environment, thread and request and discards only resolve},});expect(requests.activePendingUserInput?.requestId).toBe("second");+ await act(() =>+ makeThreadRequestsResolvedAnnouncer(+ environmentId,+ threadRef.threadId,+ )([RuntimeRequestId.make("second")]),+ );for (const [index, scope] of scopes.entries()) {await show(scope);expect(requests.activePendingQuestionIndex).toBe(index === 0 ? 0 : 1);diff --git a/apps/web/src/components/chat/usePendingThreadRequests.ts b/apps/web/src/components/chat/usePendingThreadRequests.tsindex 3f87eeffa57..35e4cc5f085 100644--- a/apps/web/src/components/chat/usePendingThreadRequests.ts+++ b/apps/web/src/components/chat/usePendingThreadRequests.ts@@ -10,23 +10,19 @@ import {} from "@t3tools/contracts";import {derivePendingThreadRequests,+ onThreadRequestsResolved,+ pruneResolvedUserInputDrafts,seedUserInputDraftAnswers,+ userInputDraftKey,} from "@t3tools/client-runtime/state/thread-requests";import {isAtomCommandInterrupted,squashAtomCommandFailure,} from "@t3tools/client-runtime/state/runtime";import { create } from "zustand";-import {- useLayoutEffect,- useEffect,- useRef,- useState,- type RefObject,- type SetStateAction,-} from "react";+import { useRef, useState, type RefObject, type SetStateAction } from "react";import { useShallow } from "zustand/react/shallow";-import { DraftId, useComposerDraftStore } from "../../composerDraftStore";+import { type DraftId, useComposerDraftStore } from "../../composerDraftStore";import { useStableCallback } from "../../hooks/useStableCallback";import { getUploadedAttachments, useAttachmentUploadStore } from "../../lib/attachmentUploadQueue";import {@@ -34,17 +30,13 @@ import {carryDisplacedCustomAnswerIntoPrompt,derivePendingUserInputProgress,projectPendingUserInputAnswer,- pendingUserInputRequestKey,- pruneResolvedUserInputDrafts,setPendingUserInputCustomAnswer,threadContextsReferencedByAnswer,togglePendingUserInputOptionSelection,type PendingUserInputDraftAnswer,} from "../../pendingUserInput";import {- clearQuestionAttachmentDraft,questionAttachmentDraftId,- questionAttachmentDraftPrefix,useQuestionAttachmentPreparation,} from "../../questionAttachments";import {@@ -67,6 +59,22 @@ const NO_PENDING_REQUESTS = { approvals: [], userInputs: [] } as const;const NO_PENDING_APPROVALS: ReturnType<typeof derivePendingApprovals> = [];const NO_PENDING_USER_INPUTS: ReturnType<typeof derivePendingUserInputs> = [];+// Resolution can come from anywhere: another device, an interrupt, the turn+// ending, or a thread that is not open. Question attachment drafts are pruned+// by questionAttachments.ts, which owns them.+onThreadRequestsResolved(({ environmentId, threadId, pendingRequestIds }) => {+ usePendingUserInputAnswers.setState(+ (existing) =>+ pruneResolvedUserInputDrafts(existing, environmentId, threadId, pendingRequestIds),+ true,+ );+ usePendingUserInputQuestionIndex.setState(+ (existing) =>+ pruneResolvedUserInputDrafts(existing, environmentId, threadId, pendingRequestIds),+ true,+ );+});+function makePendingCustomAnswerSetter(input: {readonly activePendingUserInput: PendingUserInput | null;readonly activePendingRequestKey: string;@@ -103,7 +111,6 @@ function makePendingCustomAnswerSetter(input: {export function usePendingThreadRequests(input: {readonly environmentId: EnvironmentId;readonly activeThreadId: ThreadId | null;- readonly activeThread: { readonly id: ThreadId } | undefined;readonly serverProjection: ThreadStructure | null;readonly supportsQuestionAttachments: boolean;readonly composerDraftTarget: ScopedThreadRef | DraftId;@@ -115,7 +122,6 @@ export function usePendingThreadRequests(input: {const {environmentId,activeThreadId,- activeThread,serverProjection,supportsQuestionAttachments,composerDraftTarget,@@ -140,7 +146,6 @@ export function usePendingThreadRequests(input: {>([]);const setPendingUserInputAnswersByRequestId = usePendingUserInputAnswers.setState;const setPendingUserInputQuestionIndexByRequestId = usePendingUserInputQuestionIndex.setState;- const projectedThreadId = serverProjection?.thread.id;const pendingRequests =serverProjection !== null && serverProjection.thread.id === activeThreadId? derivePendingThreadRequests(serverProjection)@@ -156,25 +161,22 @@ export function usePendingThreadRequests(input: {? NO_PENDING_USER_INPUTS: derivePendingUserInputs(pendingRequests.userInputs);const activePendingUserInput = pendingUserInputs[0] ?? null;- const activePendingRequestKey = pendingUserInputRequestKey(+ const activePendingRequestKey = userInputDraftKey(environmentId,activeThreadId,activePendingUserInput?.requestId,);- const activePendingAnswerDrafts = usePendingUserInputAnswers(+ const storedPendingAnswerDrafts = usePendingUserInputAnswers((state) => state[activePendingRequestKey] ?? EMPTY_PENDING_USER_INPUT_ANSWERS,);+ // Suggested answers are shown until the user edits them; only edits are stored.+ const activePendingAnswerDrafts: Record<string, PendingUserInputDraftAnswer> =+ activePendingUserInput+ ? seedUserInputDraftAnswers(activePendingUserInput.questions, storedPendingAnswerDrafts)+ : storedPendingAnswerDrafts;const activePendingQuestionIndex = usePendingUserInputQuestionIndex((state) => state[activePendingRequestKey] ?? 0,);- useLayoutEffect(() => {- if (!activePendingUserInput) return;- usePendingUserInputAnswers.setState((existing) => {- const drafts = existing[activePendingRequestKey] ?? EMPTY_PENDING_USER_INPUT_ANSWERS;- const seeded = seedUserInputDraftAnswers(activePendingUserInput.questions, drafts);- return seeded === drafts ? existing : { ...existing, [activePendingRequestKey]: seeded };- });- }, [activePendingRequestKey, activePendingUserInput]);const pendingQuestionDraftKeys = activeThreadId? pendingUserInputs.flatMap((request) =>request.questions.map((question) =>@@ -211,44 +213,6 @@ export function usePendingThreadRequests(input: {Object.fromEntries(pendingQuestionDraftKeys.map((key) => [key, state.counts[key] ?? 0])),),);- useEffect(() => {- // A thread shell can arrive before its requests; missing detail is not resolution.- if (!activeThread || projectedThreadId !== activeThread.id) return;- const questionThread = activeThread;- const currentRequests = pendingUserInputs;- const pendingRequestIds = currentRequests.map((request) => request.requestId);- usePendingUserInputAnswers.setState(- (existing) =>- pruneResolvedUserInputDrafts(existing, environmentId, questionThread.id, pendingRequestIds),- true,- );- usePendingUserInputQuestionIndex.setState(- (existing) =>- pruneResolvedUserInputDrafts(existing, environmentId, questionThread.id, pendingRequestIds),- true,- );- const prefix = questionAttachmentDraftPrefix(environmentId, questionThread.id);- const retained = new Set(- currentRequests.flatMap((request) =>- request.questions.map((question) =>- questionAttachmentDraftId(- environmentId,- questionThread.id,- request.requestId,- question.id,- ),- ),- ),- );- const keys = new Set([- ...Object.keys(useComposerDraftStore.getState().draftsByThreadKey),- ...Object.keys(useQuestionAttachmentPreparation.getState().counts),- ]);- for (const key of keys) {- if (key.startsWith(prefix) && !retained.has(DraftId.make(key)))- clearQuestionAttachmentDraft(DraftId.make(key));- }- }, [environmentId, activeThread, projectedThreadId, pendingUserInputs]);const activePendingDraftAnswers =!activePendingUserInput || !activeThreadId? EMPTY_PENDING_USER_INPUT_ANSWERSdiff --git a/apps/web/src/pendingUserInput.ts b/apps/web/src/pendingUserInput.tsindex 22d5521f5e7..38cd335bb49 100644--- a/apps/web/src/pendingUserInput.ts+++ b/apps/web/src/pendingUserInput.ts@@ -112,35 +112,6 @@ export function setPendingUserInputCustomAnswer(};}-export function pendingUserInputRequestKey(- environmentId: string,- threadId: string | null,- requestId: string | undefined,-): string {- return JSON.stringify([environmentId, threadId, requestId]);-}--/** Drops a thread's drafts for requests that are no longer pending. Unchanged input is returned as is. */-export function pruneResolvedUserInputDrafts<T>(- draftsByRequestKey: Record<string, T>,- environmentId: string,- threadId: string,- pendingRequestIds: ReadonlyArray<string>,-): Record<string, T> {- const threadPrefix = JSON.stringify([environmentId, threadId]).slice(0, -1);- const pendingKeys = new Set(- pendingRequestIds.map((requestId) =>- pendingUserInputRequestKey(environmentId, threadId, requestId),- ),- );- const retained = Object.entries(draftsByRequestKey).filter(- ([key]) => !key.startsWith(threadPrefix) || pendingKeys.has(key),- );- return retained.length === Object.keys(draftsByRequestKey).length- ? draftsByRequestKey- : Object.fromEntries(retained);-}-const DISPLACED_ANSWER_SEPARATOR = "\n\n";export function carryDisplacedCustomAnswerIntoPrompt(diff --git a/apps/web/src/questionAttachments.test.ts b/apps/web/src/questionAttachments.test.tsindex 808f02a4c5a..2b1120f23df 100644--- a/apps/web/src/questionAttachments.test.ts+++ b/apps/web/src/questionAttachments.test.ts@@ -1,4 +1,5 @@-import { ApprovalRequestId, EnvironmentId, ThreadId } from "@t3tools/contracts";+import { makeThreadRequestsResolvedAnnouncer } from "@t3tools/client-runtime/state/thread-requests";+import { ApprovalRequestId, EnvironmentId, RuntimeRequestId, ThreadId } from "@t3tools/contracts";import { beforeEach, expect, it, vi } from "vite-plus/test";import { useComposerDraftStore } from "./composerDraftStore";import {@@ -114,3 +115,24 @@ it("counts files, images, and pending preparation across the shared question budchangeQuestionAttachmentPreparation(second, -1);expect(countQuestionAttachments([first, second])).toBe(7);});++it("clears attachment drafts for requests the thread resolved, wherever they were answered", () => {+ const store = useComposerDraftStore.getState();+ const pending = RuntimeRequestId.make("pending");+ const resolved = RuntimeRequestId.make("resolved");+ const otherThread = ThreadId.make("thread-2");+ const keep = questionAttachmentDraftId(environmentId, threadId, pending, "first");+ const drop = questionAttachmentDraftId(environmentId, threadId, resolved, "first");+ const elsewhere = questionAttachmentDraftId(environmentId, otherThread, resolved, "first");+ for (const key of [keep, drop, elsewhere]) store.setPrompt(key, "Answer context");+ changeQuestionAttachmentPreparation(drop, 1);++ // The thread's projection synchronizes with only `pending` left, e.g. after+ // `resolved` was answered on another device while no composer showed it.+ makeThreadRequestsResolvedAnnouncer(environmentId, threadId)([pending]);++ expect(store.getComposerDraft(keep)?.prompt).toBe("Answer context");+ expect(store.getComposerDraft(drop)).toBeNull();+ expect(store.getComposerDraft(elsewhere)?.prompt).toBe("Answer context");+ expect(useQuestionAttachmentPreparation.getState().counts[drop]).toBeUndefined();+});diff --git a/apps/web/src/questionAttachments.ts b/apps/web/src/questionAttachments.tsindex 28472c0599a..8305bb679bf 100644--- a/apps/web/src/questionAttachments.ts+++ b/apps/web/src/questionAttachments.ts@@ -1,4 +1,8 @@import { scopedThreadKey } from "@t3tools/client-runtime/environment";+import {+ onThreadRequestsResolved,+ resolvedQuestionDraftKeys,+} from "@t3tools/client-runtime/state/thread-requests";import type { EnvironmentId, ScopedThreadRef, ThreadId } from "@t3tools/contracts";import { create } from "zustand";import { DraftId, useComposerDraftStore } from "./composerDraftStore";@@ -92,3 +96,25 @@ export function clearQuestionAttachmentDraft(key: DraftId): void {return { counts: next };});}++/** Clears the thread's question attachment drafts for every request outside `pendingRequestIds`. */+function pruneResolvedQuestionAttachmentDrafts(+ environmentId: EnvironmentId,+ threadId: ThreadId,+ pendingRequestIds: ReadonlyArray<string>,+): void {+ const keys = new Set([+ ...Object.keys(useComposerDraftStore.getState().draftsByThreadKey),+ ...Object.keys(useQuestionAttachmentPreparation.getState().counts),+ ]);+ const prefix = questionAttachmentDraftPrefix(environmentId, threadId);+ for (const key of resolvedQuestionDraftKeys(keys, prefix, pendingRequestIds)) {+ clearQuestionAttachmentDraft(DraftId.make(key));+ }+}++// Attachment drafts persist across reloads, so a request resolved while this+// client was away is pruned when its thread's projection first synchronizes.+onThreadRequestsResolved(({ environmentId, threadId, pendingRequestIds }) =>+ pruneResolvedQuestionAttachmentDrafts(environmentId, threadId, pendingRequestIds),+);diff --git a/packages/client-runtime/src/state/threadRequests.test.ts b/packages/client-runtime/src/state/threadRequests.test.tsindex b4a6447c2fc..d5d2c4ec16d 100644--- a/packages/client-runtime/src/state/threadRequests.test.ts+++ b/packages/client-runtime/src/state/threadRequests.test.ts@@ -1,4 +1,5 @@import {+ EnvironmentId,NodeId,ProviderSessionId,RuntimeRequestId,@@ -14,8 +15,14 @@ import {derivePendingThreadRequests,declinePendingApprovals,sendApprovalFeedback,+ makeThreadRequestsResolvedAnnouncer,+ onThreadRequestsResolved,+ pruneResolvedUserInputDrafts,+ resolvedQuestionDraftKeys,seedUserInputDraftAnswers,+ userInputDraftKey,type ApprovalResponder,+ type ThreadRequestsResolved,type ThreadPendingApproval,} from "./threadRequests.ts";@@ -117,6 +124,81 @@ describe("declining approvals before sending", () => {});});+describe("pruning resolved user input drafts", () => {+ const answered = userInputDraftKey("env", "thread", "answered");+ const pending = userInputDraftKey("env", "thread", "pending");+ const otherThread = userInputDraftKey("env", "thread-2", "answered");+ const otherEnvironment = userInputDraftKey("env-2", "thread", "answered");+ const drafts = {+ [answered]: 1,+ [pending]: 2,+ [otherThread]: 3,+ [otherEnvironment]: 4,+ };++ it("drops only the thread's requests that are no longer pending", () => {+ expect(pruneResolvedUserInputDrafts(drafts, "env", "thread", ["pending"])).toEqual({+ [pending]: 2,+ [otherThread]: 3,+ [otherEnvironment]: 4,+ });+ });++ it("returns the same record when nothing resolved", () => {+ expect(pruneResolvedUserInputDrafts(drafts, "env", "thread", ["answered", "pending"])).toBe(+ drafts,+ );+ });+});++describe("resolved question draft keys", () => {+ const prefix = "env:question-thread-";+ const key = (request: string, question: string) =>+ `${prefix}${encodeURIComponent(JSON.stringify([request, question]))}`;++ it("returns the thread's keys for requests that are no longer pending", () => {+ const keys = [+ key("pending", "first"),+ key("pending", "second"),+ key("pending-2", "first"),+ key("answered", "first"),+ "env:question-other-thread-x",+ ];+ expect(resolvedQuestionDraftKeys(keys, prefix, [RuntimeRequestId.make("pending")])).toEqual([+ key("pending-2", "first"),+ key("answered", "first"),+ ]);+ });+});++describe("announcing resolved thread requests", () => {+ const environmentId = EnvironmentId.make("env");+ const threadId = v2Projection.thread.id;+ const first = RuntimeRequestId.make("first");+ const second = RuntimeRequestId.make("second");++ function record() {+ const events: ThreadRequestsResolved[] = [];+ const unsubscribe = onThreadRequestsResolved((event) => events.push(event));+ return { events, [Symbol.dispose]: unsubscribe };+ }++ it("announces the first projection, then only when a request leaves pending", () => {+ using recorder = record();+ const announce = makeThreadRequestsResolvedAnnouncer(environmentId, threadId);++ announce([first]);+ announce([first, second]);+ announce([first, second]);+ announce([second]);++ expect(recorder.events).toEqual([+ { environmentId, threadId, pendingRequestIds: [first] },+ { environmentId, threadId, pendingRequestIds: [second] },+ ]);+ });+});+describe("initial user input drafts", () => {const questions = [{ id: "editor", initialAnswer: " Proposed commit\n\n" },diff --git a/packages/client-runtime/src/state/threadRequests.ts b/packages/client-runtime/src/state/threadRequests.tsindex e14f5471571..e089eb36d08 100644--- a/packages/client-runtime/src/state/threadRequests.ts+++ b/packages/client-runtime/src/state/threadRequests.ts@@ -1,4 +1,6 @@import type {+ EnvironmentId,+ ThreadId,OrchestrationV2ThreadProjection,OrchestrationV2RuntimeRequest,OrchestrationV2UserInputQuestion,@@ -106,6 +108,119 @@ export function seedUserInputDraftAnswers<Draft extends { readonly customAnswer?return seeded;}+/** Keys a user-input draft by thread so a thread's resolved requests can be pruned together. */+export function userInputDraftKey(+ environmentId: string,+ threadId: string | null,+ requestId: string | undefined,+): string {+ return JSON.stringify([environmentId, threadId, requestId]);+}++/**+ * Drops the thread's drafts for requests outside `pendingRequestIds`, leaving+ * other threads alone. Returns the input itself when nothing is dropped.+ */+export function pruneResolvedUserInputDrafts<T>(+ draftsByRequestKey: Record<string, T>,+ environmentId: string,+ threadId: string,+ pendingRequestIds: ReadonlyArray<string>,+): Record<string, T> {+ const threadPrefix = JSON.stringify([environmentId, threadId]).slice(0, -1);+ const pendingKeys = new Set(+ pendingRequestIds.map((requestId) => userInputDraftKey(environmentId, threadId, requestId)),+ );+ const retained = Object.entries(draftsByRequestKey).filter(+ ([key]) => !key.startsWith(threadPrefix) || pendingKeys.has(key),+ );+ return retained.length === Object.keys(draftsByRequestKey).length+ ? draftsByRequestKey+ : Object.fromEntries(retained);+}++/**+ * Question attachment drafts are keyed `<thread prefix><encoded [requestId, questionId]>`.+ * Returns the keys under `threadPrefix` whose request is outside `pendingRequestIds`.+ */+export function resolvedQuestionDraftKeys(+ keys: Iterable<string>,+ threadPrefix: string,+ pendingRequestIds: ReadonlyArray<string>,+): string[] {+ // encodeURIComponent is per character, so an encoded JSON prefix prefixes the encoded key.+ const pendingPrefixes = pendingRequestIds.map(+ (requestId) =>+ `${threadPrefix}${encodeURIComponent(`${JSON.stringify([requestId]).slice(0, -1)},`)}`,+ );+ const resolved: string[] = [];+ for (const key of keys) {+ if (key.startsWith(threadPrefix) && !pendingPrefixes.some((prefix) => key.startsWith(prefix)))+ resolved.push(key);+ }+ return resolved;+}++export interface ThreadRequestsResolved {+ readonly environmentId: EnvironmentId;+ readonly threadId: ThreadId;+ /** Every request the thread still waits on; drafts for any other request are stale. */+ readonly pendingRequestIds: ReadonlyArray<RuntimeRequestId>;+}++const threadRequestsResolvedListeners = new Set<(event: ThreadRequestsResolved) => void>();++/**+ * Clients register draft pruners once at module level. Thread state announces+ * when its synchronized projection first lands and whenever a request leaves+ * pending, wherever the resolution came from (another device, interrupt, turn end).+ */+export function onThreadRequestsResolved(+ listener: (event: ThreadRequestsResolved) => void,+): () => void {+ threadRequestsResolvedListeners.add(listener);+ return () => threadRequestsResolvedListeners.delete(listener);+}++function notifyThreadRequestsResolved(event: ThreadRequestsResolved): void {+ for (const listener of threadRequestsResolvedListeners) {+ try {+ listener(event);+ } catch (error) {+ // A failing pruner must neither stop the others nor break thread sync.+ queueMicrotask(() => {+ throw error;+ });+ }+ }+}++/**+ * Tracks one thread's announced pending requests. Feed it the pending ids of+ * each authoritative projection; it notifies on the first one and whenever an+ * announced request is no longer pending. New requests alone stay quiet.+ */+export function makeThreadRequestsResolvedAnnouncer(+ environmentId: EnvironmentId,+ threadId: ThreadId,+) {+ let announced: ReadonlySet<RuntimeRequestId> | null = null;+ return (pendingRequestIds: ReadonlyArray<RuntimeRequestId>) => {+ const pending = new Set(pendingRequestIds);+ const resolvedSome = announced === null || [...announced].some((id) => !pending.has(id));+ announced = pending;+ if (resolvedSome) notifyThreadRequestsResolved({ environmentId, threadId, pendingRequestIds });+ };+}++export function pendingRuntimeRequestIds(+ projection: Pick<OrchestrationV2ThreadProjection, "runtimeRequests">,+): RuntimeRequestId[] {+ return projection.runtimeRequests.flatMap((request) =>+ request.status === "pending" ? [request.id] : [],+ );+}+export function derivePendingThreadRequests(projection: Pick<ThreadStructure, "runtimeRequests" | "turnItems">,): PendingThreadRequests {diff --git a/packages/client-runtime/src/state/threads-sync.test.ts b/packages/client-runtime/src/state/threads-sync.test.tsindex 9095f48da7d..93bee9f46dd 100644--- a/packages/client-runtime/src/state/threads-sync.test.ts+++ b/packages/client-runtime/src/state/threads-sync.test.ts@@ -2,7 +2,9 @@ import {EnvironmentId,EventId,MessageId,+ NodeId,ORCHESTRATION_V2_WS_METHODS,+ RuntimeRequestId,ThreadId,TurnItemId,type OrchestrationV2ThreadDetailSnapshot,@@ -43,7 +45,8 @@ import {decodeOrDiscardOrchestrationCache,} from "../platform/orchestrationCache.ts";import * as RpcSession from "../rpc/session.ts";-import { v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts";+import { v2Now, v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts";+import { onThreadRequestsResolved, type ThreadRequestsResolved } from "./threadRequests.ts";import { EMPTY_THREAD_HISTORY_META } from "./threadHistoryMerge.ts";import * as ThreadHistoryController from "./threadHistoryController.ts";import {@@ -303,6 +306,30 @@ const snapshot = (const synchronized = (): OrchestrationV2ThreadStreamItem => ({ kind: "synchronized" });+const PENDING_QUESTION = {+ id: RuntimeRequestId.make("question"),+ nodeId: NodeId.make("question-node"),+ providerTurnId: null,+ nativeRequestRef: null,+ kind: "user_input" as const,+ status: "pending" as const,+ responseCapability: { type: "message" as const },+ createdAt: v2Now,+ resolvedAt: null,+};++const questionResolved = (sequence: number): OrchestrationV2ThreadStreamItem => ({+ kind: "event",+ sequence,+ event: {+ id: EventId.make("event-request"),+ type: "runtime-request.updated",+ threadId: THREAD_ID,+ occurredAt: v2Now,+ payload: { ...PENDING_QUESTION, status: "resolved", resolvedAt: v2Now },+ },+});+const titleUpdated = (title: string, sequence = 2): OrchestrationV2ThreadStreamItem => {const occurredAt = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");return {@@ -520,6 +547,11 @@ describe("EnvironmentThreads", () => {it.effect("prevents an old scope from replacing its successor's cached data", () =>Effect.gen(function* () {+ const announced: ThreadRequestsResolved[] = [];+ yield* Effect.acquireRelease(+ Effect.sync(() => onThreadRequestsResolved((event) => announced.push(event))),+ (unsubscribe) => Effect.sync(unsubscribe),+ );const resumeCache: NonNullable<Parameters<typeof makeEnvironmentThreadState>[1]> = {snapshot: undefined,owner: undefined,@@ -527,24 +559,28 @@ describe("EnvironmentThreads", () => {const oldScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>Scope.close(scope, Exit.void),);- const old = yield* makeHarness({ cached: BASE_PROJECTION, resumeCache }).pipe(- Effect.provideService(Scope.Scope, oldScope),- );+ const old = yield* makeHarness({+ cached: { ...BASE_PROJECTION, runtimeRequests: [PENDING_QUESTION] },+ resumeCache,+ }).pipe(Effect.provideService(Scope.Scope, oldScope));yield* awaitThreadState(old.observed, (value) => value.status === "live");const successor = yield* makeHarness({ resumeCache });- yield* Queue.offer(successor.inputs, titleUpdated("Successor title", 9));+ yield* Queue.offer(successor.inputs, titleUpdated("Successor title", 10));yield* awaitThreadState(successor.observed,(value) => Option.getOrNull(value.data)?.thread.title === "Successor title",);- yield* Queue.offer(old.inputs, titleUpdated("Old scope title", 8));+ announced.length = 0;+ yield* Queue.offerAll(old.inputs, [questionResolved(8), titleUpdated("Old scope title", 9)]);yield* awaitThreadState(old.observed,(value) => Option.getOrNull(value.data)?.thread.title === "Old scope title",);yield* Scope.close(oldScope, Exit.void);- expect(resumeCache.snapshot?.sequence).toBe(9);+ // Draft pruners would delete the answer the successor still waits on.+ expect(announced).toEqual([]);+ expect(resumeCache.snapshot?.sequence).toBe(10);expect(Option.getOrThrow(resumeCache.snapshot!.state.data).thread.title).toBe("Successor title",);@@ -1797,6 +1833,37 @@ describe("EnvironmentThreads", () => {}),);+ it.effect("announces request resolution only from a synchronized projection", () =>+ Effect.gen(function* () {+ const announced = yield* Queue.unbounded<ThreadRequestsResolved>();+ yield* Effect.acquireRelease(+ Effect.sync(() => onThreadRequestsResolved((event) => Queue.offerUnsafe(announced, event))),+ (unsubscribe) => Effect.sync(unsubscribe),+ );+ const harness = yield* makeHarness({+ cached: { ...BASE_PROJECTION, runtimeRequests: [PENDING_QUESTION] },+ completionMarker: true,+ });+ yield* awaitThreadState(+ harness.observed,+ (value) => value.status === "synchronizing" && Option.isSome(value.data),+ );++ // Answered on another device while this client was away.+ yield* Queue.offerAll(harness.inputs, [+ questionResolved(CACHED_SNAPSHOT_SEQUENCE + 1),+ synchronized(),+ ]);++ expect(yield* Queue.take(announced)).toEqual({+ environmentId: TARGET.environmentId,+ threadId: THREAD_ID,+ pendingRequestIds: [],+ });+ expect(yield* Queue.size(announced)).toBe(0);+ }),+ );+it.effect("skips an unknown event type and resumes after it", () =>Effect.gen(function* () {const harness = yield* makeHarness({ cached: BASE_PROJECTION, completionMarker: true });diff --git a/packages/client-runtime/src/state/threads.ts b/packages/client-runtime/src/state/threads.tsindex e5519373c92..693af5329fe 100644--- a/packages/client-runtime/src/state/threads.ts+++ b/packages/client-runtime/src/state/threads.ts@@ -48,6 +48,7 @@ import {type ThreadHistoryMeta,} from "./threadHistoryMerge.ts";import * as ThreadSnapshotLoader from "./threadSnapshotHttp.ts";+import { makeThreadRequestsResolvedAnnouncer, pendingRuntimeRequestIds } from "./threadRequests.ts";import {EMPTY_ENVIRONMENT_THREAD_STATE,type EnvironmentThreadState,@@ -254,9 +255,17 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.makeconst applyLock = yield* Semaphore.make(1);// Save only completed data/cursor updates. A canceled scope must not cache// a cursor whose event has not reached the data yet.+ const announceRequests = makeThreadRequestsResolvedAnnouncer(environmentId, threadId);const remember = Effect.gen(function* () {const current = yield* SubscriptionRef.get(state);const sequence = yield* SubscriptionRef.get(lastSequence);+ // Only a synchronized projection from the scope that owns the thread is+ // authoritative: a cached one can predate a request the user already has+ // drafts for, and a superseded scope can lag its successor.+ const owns = resumeCache === undefined || resumeCache.owner === owner;+ if (owns && current.status === "deleted") announceRequests([]);+ else if (owns && current.status === "live" && Option.isSome(current.data))+ announceRequests(pendingRuntimeRequestIds(current.data.value));committed = {state: current,sequence,