TypeScript
fix(web): keep a typed question answer when you open a new thread (#13865)
Guillermo Casanovab177a16b6909
diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.navigation.browser.test.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.navigation.browser.test.tsxindex 5b5893b5ad5..b0d14d50472 100644--- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.navigation.browser.test.tsx+++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.navigation.browser.test.tsx@@ -1,5 +1,12 @@-import { EnvironmentId, RuntimeRequestId, ThreadId } from "@t3tools/contracts";-import { act, useState } from "react";+import {+ EnvironmentId,+ NodeId,+ RuntimeRequestId,+ ThreadId,+ TurnItemId,+ type OrchestrationV2ThreadProjection,+} from "@t3tools/contracts";+import { act, useLayoutEffect, useRef, useState, type ComponentProps } from "react";import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";@@ -13,7 +20,9 @@ vi.mock(import("../ChatMarkdown"), async (importOriginal) => ({default: (({ text }: { text: string }) => <p>{text}</p>) as never,}));+import { makeThreadProjectionFixture } from "../../test-fixtures";import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel";+import { usePendingThreadRequests } from "./usePendingThreadRequests";const threadRef = { environmentId: EnvironmentId.make("env"), threadId: ThreadId.make("thread") };@@ -131,3 +140,155 @@ it("still auto-advances once after the answer draft rerenders the same question"await act(async () => vi.advanceTimersByTime(200));expect(activeIndex()).toBe("1");});++function questionProjection(threadId: ThreadId, requestIds = ["first", "second"]) {+ const projection = makeThreadProjectionFixture();+ return {+ ...projection,+ thread: { ...projection.thread, id: threadId },+ runtimeRequests: requestIds.map((id) => ({+ id: RuntimeRequestId.make(id),+ nodeId: NodeId.make(id),+ providerTurnId: null,+ nativeRequestRef: null,+ kind: "user_input" as const,+ status: "pending" as const,+ responseCapability: { type: "message" as const },+ createdAt: projection.updatedAt,+ resolvedAt: null,+ })),+ turnItems: requestIds.map((id, ordinal) => ({+ id: TurnItemId.make(id),+ threadId,+ runId: null,+ nodeId: NodeId.make(id),+ providerThreadId: null,+ providerTurnId: null,+ nativeItemRef: null,+ parentItemId: null,+ ordinal,+ status: "completed" as const,+ title: null,+ startedAt: projection.updatedAt,+ completedAt: projection.updatedAt,+ updatedAt: projection.updatedAt,+ type: "user_input_request" as const,+ requestId: RuntimeRequestId.make(id),+ questions: prompt.questions,+ })),+ } satisfies OrchestrationV2ThreadProjection;+}++let requests: ReturnType<typeof usePendingThreadRequests>;++function PendingRequestsProbe({+ environmentId,+ projection,+ loading = false,+}: {+ environmentId: EnvironmentId;+ projection: OrchestrationV2ThreadProjection;+ loading?: boolean;+}) {+ const promptRef = useRef("");+ const composerRef = useRef(null);+ const state = usePendingThreadRequests({+ environmentId,+ activeThreadId: projection.thread.id,+ activeThread: projection.thread,+ serverProjection: loading ? null : projection,+ supportsQuestionAttachments: false,+ composerDraftTarget: { environmentId, threadId: projection.thread.id },+ setComposerDraftPrompt: () => {},+ promptRef,+ composerRef,+ setThreadError: () => {},+ });+ useLayoutEffect(() => {+ requests = state;+ });+ return null;+}++it("retains answers, selections and question position after leaving chat, including while the projection reloads", async () => {+ const environmentId = EnvironmentId.make("remount-environment");+ const projection = questionProjection(threadRef.threadId);+ const render = (loading = false) =>+ act(() =>+ root.render(+ <PendingRequestsProbe+ environmentId={environmentId}+ projection={projection}+ loading={loading}+ />,+ ),+ );+ await render();+ await act(() =>+ requests.onChangeActivePendingUserInputCustomAnswer("question-0", "Keep my text"),+ );+ await act(() => requests.onAdvanceActivePendingUserInput());+ await act(() => requests.onSelectActivePendingUserInputOption("question-1", "Incremental"));+ await act(() => requests.onAdvanceActivePendingUserInput());+ const expected = {+ activePendingQuestionIndex: 2,+ activePendingDraftAnswers: {+ "question-0": { customAnswer: "Keep my text" },+ "question-1": { selectedOptionValues: ["Incremental"] },+ },+ };+ expect(requests).toMatchObject(expected);++ // New thread and Settings both unmount the chat that owns this hook.+ await act(() => root.render(null));+ await render();+ expect(requests).toMatchObject(expected);++ await act(() => root.render(null));+ await render(true);+ expect(requests.activePendingUserInput).toBeNull();+ await render();+ expect(requests).toMatchObject(expected);+});++it("isolates drafts by environment, thread and request and discards only resolved requests", async () => {+ const environmentId = EnvironmentId.make("scope-environment");+ const projection = questionProjection(threadRef.threadId);+ const scopes = [+ { environmentId, projection },+ { environmentId: EnvironmentId.make("other-environment"), projection },+ { environmentId, projection: questionProjection(ThreadId.make("other-thread")) },+ { environmentId, projection: questionProjection(threadRef.threadId, ["second", "first"]) },+ ];+ const show = (scope: ComponentProps<typeof PendingRequestsProbe>) =>+ act(() => root.render(<PendingRequestsProbe {...scope} />));+ for (const [index, scope] of scopes.entries()) {+ await show(scope);+ expect(requests.activePendingQuestionIndex).toBe(0);+ expect(requests.activePendingDraftAnswers["question-0"]?.customAnswer).toBeUndefined();+ await act(() =>+ requests.onChangeActivePendingUserInputCustomAnswer("question-0", `Answer ${index}`),+ );+ await act(() => requests.onAdvanceActivePendingUserInput());+ }++ await show({+ environmentId,+ projection: {+ ...projection,+ runtimeRequests: projection.runtimeRequests.map((request) =>+ request.id === "first"+ ? { ...request, status: "resolved", resolvedAt: projection.updatedAt }+ : request,+ ),+ },+ });+ expect(requests.activePendingUserInput?.requestId).toBe("second");+ for (const [index, scope] of scopes.entries()) {+ await show(scope);+ expect(requests.activePendingQuestionIndex).toBe(index === 0 ? 0 : 1);+ expect(requests.activePendingDraftAnswers["question-0"]?.customAnswer).toBe(+ index === 0 ? undefined : `Answer ${index}`,+ );+ }+});diff --git a/apps/web/src/components/chat/usePendingThreadRequests.ts b/apps/web/src/components/chat/usePendingThreadRequests.tsindex f1aa3c08141..88e8f82dc0b 100644--- a/apps/web/src/components/chat/usePendingThreadRequests.ts+++ b/apps/web/src/components/chat/usePendingThreadRequests.ts@@ -16,7 +16,15 @@ import {isAtomCommandInterrupted,squashAtomCommandFailure,} from "@t3tools/client-runtime/state/runtime";-import { useEffect, useRef, useState, type RefObject, type SetStateAction } from "react";+import { create } from "zustand";+import {+ useLayoutEffect,+ useEffect,+ useRef,+ useState,+ type RefObject,+ type SetStateAction,+} from "react";import { useShallow } from "zustand/react/shallow";import { DraftId, useComposerDraftStore } from "../../composerDraftStore";import { useStableCallback } from "../../hooks/useStableCallback";@@ -26,6 +34,8 @@ import {carryDisplacedCustomAnswerIntoPrompt,derivePendingUserInputProgress,projectPendingUserInputAnswer,+ pendingUserInputRequestKey,+ pruneResolvedUserInputDrafts,setPendingUserInputCustomAnswer,togglePendingUserInputOptionSelection,type PendingUserInputDraftAnswer,@@ -48,6 +58,10 @@ import { useOrchestrationCommand } from "../../state/use-orchestration-command";import type { ChatComposerHandle } from "./ChatComposer";const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnswer> = {};+const usePendingUserInputAnswers = create<+ Record<string, Record<string, PendingUserInputDraftAnswer>>+>(() => ({}));+const usePendingUserInputQuestionIndex = create<Record<string, number>>(() => ({}));const NO_PENDING_REQUESTS = { approvals: [], userInputs: [] } as const;const NO_PENDING_APPROVALS: ReturnType<typeof derivePendingApprovals> = [];const NO_PENDING_USER_INPUTS: ReturnType<typeof derivePendingUserInputs> = [];@@ -94,7 +108,6 @@ function makePendingCustomAnswerSetter(input: {export function usePendingThreadRequests(input: {readonly environmentId: EnvironmentId;readonly activeThreadId: ThreadId | null;- // The effect that prunes stale question drafts re-runs when this object changes.readonly activeThread: { readonly id: ThreadId } | undefined;readonly serverProjection: OrchestrationV2ThreadProjection | null;readonly supportsQuestionAttachments: boolean;@@ -130,13 +143,13 @@ export function usePendingThreadRequests(input: {const [respondingUserInputRequestIds, setRespondingUserInputRequestIds] = useState<RuntimeRequestId[]>([]);- const [pendingUserInputAnswersByRequestId, setPendingUserInputAnswersByRequestId] = useState<- Record<string, Record<string, PendingUserInputDraftAnswer>>- >({});- const [pendingUserInputQuestionIndexByRequestId, setPendingUserInputQuestionIndexByRequestId] =- useState<Record<string, number>>({});+ const setPendingUserInputAnswersByRequestId = usePendingUserInputAnswers.setState;+ const setPendingUserInputQuestionIndexByRequestId = usePendingUserInputQuestionIndex.setState;+ const projectedThreadId = serverProjection?.thread.id;const pendingRequests =- serverProjection === null ? NO_PENDING_REQUESTS : derivePendingThreadRequests(serverProjection);+ serverProjection !== null && serverProjection.thread.id === activeThreadId+ ? derivePendingThreadRequests(serverProjection)+ : NO_PENDING_REQUESTS;// The projection changes on every streamed event, so shared empties keep the// composer and approval panel from re-rendering while nothing is pending.const pendingApprovals =@@ -148,24 +161,25 @@ export function usePendingThreadRequests(input: {? NO_PENDING_USER_INPUTS: derivePendingUserInputs(pendingRequests.userInputs);const activePendingUserInput = pendingUserInputs[0] ?? null;- const activePendingRequestKey = JSON.stringify([+ const activePendingRequestKey = pendingUserInputRequestKey(environmentId,activeThreadId,activePendingUserInput?.requestId,- ]);- const activePendingAnswerDrafts =- pendingUserInputAnswersByRequestId[activePendingRequestKey] ?? EMPTY_PENDING_USER_INPUT_ANSWERS;- if (- activePendingUserInput &&- seedUserInputDraftAnswers(activePendingUserInput.questions, activePendingAnswerDrafts) !==- activePendingAnswerDrafts- ) {- setPendingUserInputAnswersByRequestId((existing) => {+ );+ const activePendingAnswerDrafts = usePendingUserInputAnswers(+ (state) => state[activePendingRequestKey] ?? EMPTY_PENDING_USER_INPUT_ANSWERS,+ );+ 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) =>@@ -203,9 +217,21 @@ export function usePendingThreadRequests(input: {),);useEffect(() => {- if (!activeThread) return;+ // 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) =>@@ -227,7 +253,7 @@ export function usePendingThreadRequests(input: {if (key.startsWith(prefix) && !retained.has(DraftId.make(key)))clearQuestionAttachmentDraft(DraftId.make(key));}- }, [environmentId, activeThread, pendingUserInputs]);+ }, [environmentId, activeThread, projectedThreadId, pendingUserInputs]);const activePendingDraftAnswers =!activePendingUserInput || !activeThreadId? EMPTY_PENDING_USER_INPUT_ANSWERS@@ -244,7 +270,7 @@ export function usePendingThreadRequests(input: {return [question.id,{- ...pendingUserInputAnswersByRequestId[activePendingRequestKey]?.[question.id],+ ...activePendingAnswerDrafts[question.id],attachmentCount: attachments.length,attachmentsBlocked:(attachments.length > 0 && !supportsQuestionAttachments) ||@@ -254,9 +280,6 @@ export function usePendingThreadRequests(input: {];}),);- const activePendingQuestionIndex = activePendingUserInput- ? (pendingUserInputQuestionIndexByRequestId[activePendingRequestKey] ?? 0)- : 0;const activePendingProgress = activePendingUserInput? derivePendingUserInputProgress(activePendingUserInput.questions,@@ -413,8 +436,7 @@ export function usePendingThreadRequests(input: {}// The option replaces the custom answer. Anything typed there is the// user's text, so it goes back to the thread draft instead of vanishing.- const displacedAnswer =- pendingUserInputAnswersByRequestId[activePendingRequestKey]?.[questionId]?.customAnswer;+ const displacedAnswer = activePendingAnswerDrafts[questionId]?.customAnswer;const currentPrompt =useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.prompt ?? "";const nextPrompt = carryDisplacedCustomAnswerIntoPrompt(currentPrompt, displacedAnswer);diff --git a/apps/web/src/pendingUserInput.ts b/apps/web/src/pendingUserInput.tsindex f62bd74fcad..2b37af07b3e 100644--- a/apps/web/src/pendingUserInput.ts+++ b/apps/web/src/pendingUserInput.ts@@ -101,6 +101,35 @@ 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(