Skip to content

Commit 4fee7dc

Browse files
committed
fix(web): keep a typed question answer when you open a new thread
1 parent d110f98 commit 4fee7dc

3 files changed

Lines changed: 78 additions & 10 deletions

File tree

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

Lines changed: 26 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitation
106106
import { assistantCitationFromLocation } from "../lib/assistantCitationNavigation";
107107
import { isMacPlatform } from "../lib/utils";
108108
import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
109+
import { create } from "zustand";
109110
import { useShallow } from "zustand/react/shallow";
110111
import {
111112
isAtomCommandInterrupted,
@@ -149,6 +150,8 @@ import {
149150
import {
150151
buildPendingUserInputAnswers,
151152
carryDisplacedCustomAnswerIntoPrompt,
153+
pendingUserInputRequestKey,
154+
pruneResolvedUserInputDrafts,
152155
derivePendingUserInputProgress,
153156
setPendingUserInputCustomAnswer,
154157
togglePendingUserInputOptionSelection,
@@ -539,6 +542,11 @@ const EMPTY_PROVIDERS: ServerProvider[] = [];
539542
const EMPTY_USAGE_LIMIT_SOURCES: UsageLimitSourceSnapshots = [];
540543
const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = [];
541544
const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnswer> = {};
545+
// Question answers outlive ChatView remounts (New thread, Settings) until their request resolves.
546+
const usePendingUserInputAnswers = create<
547+
Record<string, Record<string, PendingUserInputDraftAnswer>>
548+
>(() => ({}));
549+
const usePendingUserInputQuestionIndex = create<Record<string, number>>(() => ({}));
542550
function useDraftHeroLayoutTransition(
543551
isDraftHeroState: boolean,
544552
animationsActive: boolean,
@@ -1752,11 +1760,8 @@ export default function ChatView(props: ChatViewProps) {
17521760
window.addEventListener("dragend", clearWorkspaceFileDrag);
17531761
return () => window.removeEventListener("dragend", clearWorkspaceFileDrag);
17541762
}, [isWorkspaceFileDragActive]);
1755-
const [pendingUserInputAnswersByRequestId, setPendingUserInputAnswersByRequestId] = useState<
1756-
Record<string, Record<string, PendingUserInputDraftAnswer>>
1757-
>({});
1758-
const [pendingUserInputQuestionIndexByRequestId, setPendingUserInputQuestionIndexByRequestId] =
1759-
useState<Record<string, number>>({});
1763+
const pendingUserInputAnswersByRequestId = usePendingUserInputAnswers();
1764+
const pendingUserInputQuestionIndexByRequestId = usePendingUserInputQuestionIndex();
17601765
const shouldUseRightPanelSheet = useMediaQuery(RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY);
17611766
const isMobileViewport = useMediaQuery("max-sm");
17621767
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
@@ -2915,11 +2920,11 @@ export default function ChatView(props: ChatViewProps) {
29152920
[threadActivities],
29162921
);
29172922
const activePendingUserInput = pendingUserInputs[0] ?? null;
2918-
const activePendingRequestKey = JSON.stringify([
2923+
const activePendingRequestKey = pendingUserInputRequestKey(
29192924
environmentId,
29202925
activeThreadId,
29212926
activePendingUserInput?.requestId,
2922-
]);
2927+
);
29232928
const pendingQuestionDraftKeys = useMemo(
29242929
() =>
29252930
activeThreadId
@@ -2969,6 +2974,17 @@ export default function ChatView(props: ChatViewProps) {
29692974
if (routeThreadState.status !== "live" || routeThreadState.data._tag !== "Some") return;
29702975
const questionThread = routeThreadState.data.value;
29712976
const { userInputs: currentRequests } = derivePendingRequests(questionThread.activities);
2977+
const pendingRequestIds = currentRequests.map((request) => request.requestId);
2978+
usePendingUserInputAnswers.setState(
2979+
(existing) =>
2980+
pruneResolvedUserInputDrafts(existing, environmentId, questionThread.id, pendingRequestIds),
2981+
true,
2982+
);
2983+
usePendingUserInputQuestionIndex.setState(
2984+
(existing) =>
2985+
pruneResolvedUserInputDrafts(existing, environmentId, questionThread.id, pendingRequestIds),
2986+
true,
2987+
);
29722988
const prefix = questionAttachmentDraftPrefix(environmentId, questionThread.id);
29732989
const retained = new Set(
29742990
currentRequests.flatMap((request) =>
@@ -8742,7 +8758,7 @@ export default function ChatView(props: ChatViewProps) {
87428758
if (!activePendingUserInput) {
87438759
return;
87448760
}
8745-
setPendingUserInputQuestionIndexByRequestId((existing) => ({
8761+
usePendingUserInputQuestionIndex.setState((existing) => ({
87468762
...existing,
87478763
[activePendingRequestKey]: nextQuestionIndex,
87488764
}));
@@ -8765,7 +8781,7 @@ export default function ChatView(props: ChatViewProps) {
87658781
if (nextPrompt !== currentPrompt) {
87668782
setComposerDraftPrompt(composerDraftTarget, nextPrompt);
87678783
}
8768-
setPendingUserInputAnswersByRequestId((existing) => {
8784+
usePendingUserInputAnswers.setState((existing) => {
87698785
const question =
87708786
(activePendingProgress?.activeQuestion?.id === questionId
87718787
? activePendingProgress.activeQuestion
@@ -8817,7 +8833,7 @@ export default function ChatView(props: ChatViewProps) {
88178833
return;
88188834
}
88198835
promptRef.current = value;
8820-
setPendingUserInputAnswersByRequestId((existing) => ({
8836+
usePendingUserInputAnswers.setState((existing) => ({
88218837
...existing,
88228838
[activePendingRequestKey]: {
88238839
...existing[activePendingRequestKey],

‎apps/web/src/pendingUserInput.test.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import {
55
carryDisplacedCustomAnswerIntoPrompt,
66
countAnsweredPendingUserInputQuestions,
77
derivePendingUserInputProgress,
8+
pendingUserInputRequestKey,
9+
pruneResolvedUserInputDrafts,
810
resolvePendingUserInputAnswer,
911
setPendingUserInputCustomAnswer,
1012
togglePendingUserInputOptionSelection,
@@ -341,3 +343,24 @@ describe("carryDisplacedCustomAnswerIntoPrompt", () => {
341343
);
342344
});
343345
});
346+
347+
describe("pruneResolvedUserInputDrafts", () => {
348+
const open = pendingUserInputRequestKey("env", "thread", "open");
349+
const answered = pendingUserInputRequestKey("env", "thread", "answered");
350+
const similarThread = pendingUserInputRequestKey("env", "thread-2", "other");
351+
const otherEnvironment = pendingUserInputRequestKey("env-2", "thread", "answered");
352+
353+
it("drops only this thread's resolved requests", () => {
354+
const drafts = { [open]: 1, [answered]: 2, [similarThread]: 3, [otherEnvironment]: 4 };
355+
expect(pruneResolvedUserInputDrafts(drafts, "env", "thread", ["open"])).toEqual({
356+
[open]: 1,
357+
[similarThread]: 3,
358+
[otherEnvironment]: 4,
359+
});
360+
});
361+
362+
it("returns the same object when nothing resolved", () => {
363+
const drafts = { [open]: 1, [similarThread]: 3 };
364+
expect(pruneResolvedUserInputDrafts(drafts, "env", "thread", ["open"])).toBe(drafts);
365+
});
366+
});

‎apps/web/src/pendingUserInput.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,35 @@ export function setPendingUserInputCustomAnswer(
8282
};
8383
}
8484

85+
export function pendingUserInputRequestKey(
86+
environmentId: string,
87+
threadId: string | null,
88+
requestId: string | undefined,
89+
): string {
90+
return JSON.stringify([environmentId, threadId, requestId]);
91+
}
92+
93+
/** Drops a thread's drafts for requests that are no longer pending. Unchanged input is returned as is. */
94+
export function pruneResolvedUserInputDrafts<T>(
95+
draftsByRequestKey: Record<string, T>,
96+
environmentId: string,
97+
threadId: string,
98+
pendingRequestIds: ReadonlyArray<string>,
99+
): Record<string, T> {
100+
const threadPrefix = JSON.stringify([environmentId, threadId]).slice(0, -1);
101+
const pendingKeys = new Set(
102+
pendingRequestIds.map((requestId) =>
103+
pendingUserInputRequestKey(environmentId, threadId, requestId),
104+
),
105+
);
106+
const retained = Object.entries(draftsByRequestKey).filter(
107+
([key]) => !key.startsWith(threadPrefix) || pendingKeys.has(key),
108+
);
109+
return retained.length === Object.keys(draftsByRequestKey).length
110+
? draftsByRequestKey
111+
: Object.fromEntries(retained);
112+
}
113+
85114
const DISPLACED_ANSWER_SEPARATOR = "\n\n";
86115

87116
/**

0 commit comments

Comments
 (0)