Skip to content

Commit 94f7984

Browse files
fix(web): preserve typed question answers when Stop cancels a turn (#23617)
1 parent cf65084 commit 94f7984

8 files changed

Lines changed: 174 additions & 53 deletions

File tree

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,10 @@ it("isolates drafts by environment, thread and request and discards only resolve
255255
makeThreadRequestsResolvedAnnouncer(
256256
environmentId,
257257
threadRef.threadId,
258-
)([RuntimeRequestId.make("second")]),
258+
)([
259+
{ id: RuntimeRequestId.make("first"), status: "resolved" },
260+
{ id: RuntimeRequestId.make("second"), status: "pending" },
261+
]),
259262
);
260263
for (const [index, scope] of scopes.entries()) {
261264
await show(scope);

‎apps/web/src/components/chat/usePendingThreadRequests.ts‎

Lines changed: 2 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,13 @@ import {
1010
} from "@t3tools/contracts";
1111
import {
1212
derivePendingThreadRequests,
13-
onThreadRequestsResolved,
14-
pruneResolvedUserInputDrafts,
1513
seedUserInputDraftAnswers,
1614
userInputDraftKey,
1715
} from "@t3tools/client-runtime/state/thread-requests";
1816
import {
1917
isAtomCommandInterrupted,
2018
squashAtomCommandFailure,
2119
} from "@t3tools/client-runtime/state/runtime";
22-
import { create } from "zustand";
2320
import { useRef, useState, type RefObject, type SetStateAction } from "react";
2421
import { useShallow } from "zustand/react/shallow";
2522
import { type DraftId, useComposerDraftStore } from "../../composerDraftStore";
@@ -39,6 +36,8 @@ import {
3936
} from "../../pendingUserInput";
4037
import {
4138
questionAttachmentDraftId,
39+
usePendingUserInputAnswers,
40+
usePendingUserInputQuestionIndex,
4241
useQuestionAttachmentPreparation,
4342
} from "../../questionAttachments";
4443
import {
@@ -55,30 +54,10 @@ import { toastManager } from "../ui/toast";
5554
import type { ChatComposerHandle } from "./ChatComposer";
5655

5756
const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnswer> = {};
58-
const usePendingUserInputAnswers = create<
59-
Record<string, Record<string, PendingUserInputDraftAnswer>>
60-
>(() => ({}));
61-
const usePendingUserInputQuestionIndex = create<Record<string, number>>(() => ({}));
6257
const NO_PENDING_REQUESTS = { approvals: [], userInputs: [] } as const;
6358
const NO_PENDING_APPROVALS: ReturnType<typeof derivePendingApprovals> = [];
6459
const NO_PENDING_USER_INPUTS: ReturnType<typeof derivePendingUserInputs> = [];
6560

66-
// Resolution can come from anywhere: another device, an interrupt, the turn
67-
// ending, or a thread that is not open. Question attachment drafts are pruned
68-
// by questionAttachments.ts, which owns them.
69-
onThreadRequestsResolved(({ environmentId, threadId, pendingRequestIds }) => {
70-
usePendingUserInputAnswers.setState(
71-
(existing) =>
72-
pruneResolvedUserInputDrafts(existing, environmentId, threadId, pendingRequestIds),
73-
true,
74-
);
75-
usePendingUserInputQuestionIndex.setState(
76-
(existing) =>
77-
pruneResolvedUserInputDrafts(existing, environmentId, threadId, pendingRequestIds),
78-
true,
79-
);
80-
});
81-
8261
function makePendingCustomAnswerSetter(input: {
8362
readonly activePendingUserInput: PendingUserInput | null;
8463
readonly activePendingRequestKey: string;

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

Lines changed: 55 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,20 @@
1-
import { makeThreadRequestsResolvedAnnouncer } from "@t3tools/client-runtime/state/thread-requests";
1+
import {
2+
makeThreadRequestsResolvedAnnouncer,
3+
userInputDraftKey,
4+
} from "@t3tools/client-runtime/state/thread-requests";
25
import { ApprovalRequestId, EnvironmentId, RuntimeRequestId, ThreadId } from "@t3tools/contracts";
6+
import { threadContextRecord } from "@t3tools/shared/composerContextReferences";
37
import { beforeEach, expect, it, vi } from "vite-plus/test";
48
import { useComposerDraftStore } from "./composerDraftStore";
9+
import { formatInlineContextReference } from "./lib/composerContextReferences";
10+
import { threadContextReference } from "./lib/composerContextRecords";
511
import {
612
questionAttachmentDraftId,
713
countQuestionAttachments,
814
questionAttachmentDraftPrefix,
915
changeQuestionAttachmentPreparation,
1016
clearQuestionAttachmentDraft,
17+
usePendingUserInputAnswers,
1118
useQuestionAttachmentPreparation,
1219
} from "./questionAttachments";
1320

@@ -19,6 +26,7 @@ const requestId = ApprovalRequestId.make("request-1");
1926
beforeEach(() => {
2027
useComposerDraftStore.setState({ draftsByThreadKey: {}, draftThreadsByThreadKey: {} });
2128
useQuestionAttachmentPreparation.setState({ counts: {} });
29+
usePendingUserInputAnswers.setState({}, true);
2230
release.mockClear();
2331
});
2432
it("keeps question files separate from the normal draft and other questions", () => {
@@ -126,13 +134,58 @@ it("clears attachment drafts for requests the thread resolved, wherever they wer
126134
const elsewhere = questionAttachmentDraftId(environmentId, otherThread, resolved, "first");
127135
for (const key of [keep, drop, elsewhere]) store.setPrompt(key, "Answer context");
128136
changeQuestionAttachmentPreparation(drop, 1);
137+
usePendingUserInputAnswers.setState({
138+
[userInputDraftKey(environmentId, threadId, resolved)]: { first: { customAnswer: "Sent" } },
139+
});
129140

130141
// The thread's projection synchronizes with only `pending` left, e.g. after
131142
// `resolved` was answered on another device while no composer showed it.
132-
makeThreadRequestsResolvedAnnouncer(environmentId, threadId)([pending]);
143+
makeThreadRequestsResolvedAnnouncer(
144+
environmentId,
145+
threadId,
146+
)([
147+
{ id: pending, status: "pending" },
148+
{ id: resolved, status: "resolved" },
149+
]);
133150

134151
expect(store.getComposerDraft(keep)?.prompt).toBe("Answer context");
135152
expect(store.getComposerDraft(drop)).toBeNull();
136153
expect(store.getComposerDraft(elsewhere)?.prompt).toBe("Answer context");
137154
expect(useQuestionAttachmentPreparation.getState().counts[drop]).toBeUndefined();
155+
// An answered question's text was sent, so it does not come back as a draft.
156+
expect(store.getComposerDraft({ environmentId, threadId })).toBeNull();
157+
expect(usePendingUserInputAnswers.getState()).toEqual({});
138158
});
159+
160+
// Stop cancels an open question; a provider timeout expires it. Neither sends the answer.
161+
it.each(["cancelled", "expired"] as const)(
162+
"returns typed answers and their thread chips to the thread draft when a question is %s",
163+
(status) => {
164+
const store = useComposerDraftStore.getState();
165+
const request = RuntimeRequestId.make("stopped");
166+
const reference = threadContextRecord(
167+
{ environmentId, threadId: ThreadId.make("reference-thread") },
168+
"Reference work",
169+
);
170+
const answer = `Purple, like ${formatInlineContextReference(threadContextReference(reference))}`;
171+
store.setPrompt({ environmentId, threadId }, "Earlier draft");
172+
store.setThreadContexts(questionAttachmentDraftId(environmentId, threadId, request, "first"), [
173+
reference,
174+
]);
175+
usePendingUserInputAnswers.setState({
176+
[userInputDraftKey(environmentId, threadId, request)]: {
177+
first: { customAnswer: answer },
178+
second: { customAnswer: " " },
179+
third: { customAnswer: "Also this" },
180+
},
181+
});
182+
183+
makeThreadRequestsResolvedAnnouncer(environmentId, threadId)([{ id: request, status }]);
184+
185+
expect(store.getComposerDraft({ environmentId, threadId })).toMatchObject({
186+
prompt: `Earlier draft\n\n${answer}\n\nAlso this`,
187+
threadContexts: [reference],
188+
});
189+
expect(usePendingUserInputAnswers.getState()).toEqual({});
190+
},
191+
);

‎apps/web/src/questionAttachments.ts‎

Lines changed: 76 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,31 @@
1-
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
1+
import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
2+
import type { PendingUserInputDraftAnswer } from "@t3tools/client-runtime/state/pending-user-input";
23
import {
34
onThreadRequestsResolved,
5+
pruneResolvedUserInputDrafts,
46
resolvedQuestionDraftKeys,
7+
userInputDraftKey,
58
} from "@t3tools/client-runtime/state/thread-requests";
6-
import type { EnvironmentId, ScopedThreadRef, ThreadId } from "@t3tools/contracts";
9+
import type {
10+
EnvironmentId,
11+
RuntimeRequestId,
12+
ScopedThreadRef,
13+
ThreadContextRecord,
14+
ThreadId,
15+
} from "@t3tools/contracts";
716
import { create } from "zustand";
817
import { DraftId, useComposerDraftStore } from "./composerDraftStore";
918
import { releaseDraftAttachments } from "./lib/attachmentUploadQueue";
19+
import {
20+
carryDisplacedCustomAnswerIntoPrompt,
21+
threadContextsReferencedByAnswer,
22+
} from "./pendingUserInput";
23+
24+
/** Edited question answers, keyed by `userInputDraftKey`; suggested answers are not stored. */
25+
export const usePendingUserInputAnswers = create<
26+
Record<string, Record<string, PendingUserInputDraftAnswer>>
27+
>(() => ({}));
28+
export const usePendingUserInputQuestionIndex = create<Record<string, number>>(() => ({}));
1029

1130
export function questionAttachmentDraftPrefix(
1231
environmentId: EnvironmentId,
@@ -113,8 +132,58 @@ function pruneResolvedQuestionAttachmentDrafts(
113132
}
114133
}
115134

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-
);
135+
/**
136+
* Stop cancels an open question and a provider timeout expires it; neither sent
137+
* the typed answers, so they move to the thread's own draft (not a queued-message
138+
* edit the composer may be showing) with the thread chips they reference.
139+
*/
140+
function returnUnsentAnswersToThreadDraft(
141+
environmentId: EnvironmentId,
142+
threadId: ThreadId,
143+
unansweredRequestIds: ReadonlyArray<RuntimeRequestId>,
144+
): void {
145+
const answers = usePendingUserInputAnswers.getState();
146+
const store = useComposerDraftStore.getState();
147+
const target = scopeThreadRef(environmentId, threadId);
148+
const currentPrompt = store.getComposerDraft(target)?.prompt ?? "";
149+
let prompt = currentPrompt;
150+
const threadContexts: ThreadContextRecord[] = [];
151+
for (const requestId of unansweredRequestIds) {
152+
const drafts = answers[userInputDraftKey(environmentId, threadId, requestId)] ?? {};
153+
for (const [questionId, { customAnswer }] of Object.entries(drafts)) {
154+
const nextPrompt = carryDisplacedCustomAnswerIntoPrompt(prompt, customAnswer);
155+
if (nextPrompt === prompt) continue;
156+
prompt = nextPrompt;
157+
const questionDraft = store.getComposerDraft(
158+
questionAttachmentDraftId(environmentId, threadId, requestId, questionId),
159+
);
160+
threadContexts.push(
161+
...threadContextsReferencedByAnswer(
162+
customAnswer ?? "",
163+
questionDraft?.threadContexts ?? [],
164+
),
165+
);
166+
}
167+
}
168+
if (prompt === currentPrompt) return;
169+
store.setPrompt(target, prompt);
170+
store.addThreadContexts(target, threadContexts, { appendReference: false });
171+
}
172+
173+
// Resolution can come from anywhere: another device, an interrupt, the turn
174+
// ending, or a reload over drafts for requests resolved meanwhile. One listener,
175+
// so unsent answers and their chips are read before their drafts are pruned.
176+
onThreadRequestsResolved(({ environmentId, threadId, pendingRequestIds, unansweredRequestIds }) => {
177+
returnUnsentAnswersToThreadDraft(environmentId, threadId, unansweredRequestIds);
178+
usePendingUserInputAnswers.setState(
179+
(existing) =>
180+
pruneResolvedUserInputDrafts(existing, environmentId, threadId, pendingRequestIds),
181+
true,
182+
);
183+
usePendingUserInputQuestionIndex.setState(
184+
(existing) =>
185+
pruneResolvedUserInputDrafts(existing, environmentId, threadId, pendingRequestIds),
186+
true,
187+
);
188+
pruneResolvedQuestionAttachmentDrafts(environmentId, threadId, pendingRequestIds);
189+
});

‎packages/client-runtime/src/state/threadRequests.test.ts‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -196,14 +196,20 @@ describe("announcing resolved thread requests", () => {
196196
using recorder = record();
197197
const announce = makeThreadRequestsResolvedAnnouncer(environmentId, threadId);
198198

199-
announce([first]);
200-
announce([first, second]);
201-
announce([first, second]);
202-
announce([second]);
199+
const pending = (id: RuntimeRequestId) => ({ id, status: "pending" as const });
200+
announce([pending(first)]);
201+
announce([pending(first), pending(second)]);
202+
announce([pending(first), pending(second)]);
203+
announce([{ id: first, status: "cancelled" }, pending(second)]);
204+
announce([
205+
{ id: first, status: "cancelled" },
206+
{ id: second, status: "resolved" },
207+
]);
203208

204209
expect(recorder.events).toEqual([
205-
{ environmentId, threadId, pendingRequestIds: [first] },
206-
{ environmentId, threadId, pendingRequestIds: [second] },
210+
{ environmentId, threadId, pendingRequestIds: [first], unansweredRequestIds: [] },
211+
{ environmentId, threadId, pendingRequestIds: [second], unansweredRequestIds: [first] },
212+
{ environmentId, threadId, pendingRequestIds: [], unansweredRequestIds: [first] },
207213
]);
208214
});
209215
});

‎packages/client-runtime/src/state/threadRequests.ts‎

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,8 @@ export interface ThreadRequestsResolved {
168168
readonly threadId: ThreadId;
169169
/** Every request the thread still waits on; drafts for any other request are stale. */
170170
readonly pendingRequestIds: ReadonlyArray<RuntimeRequestId>;
171+
/** Requests that closed without an answer (cancelled or expired), so typed drafts were never sent. */
172+
readonly unansweredRequestIds: ReadonlyArray<RuntimeRequestId>;
171173
}
172174

173175
const threadRequestsResolvedListeners = new Set<(event: ThreadRequestsResolved) => void>();
@@ -198,31 +200,39 @@ function notifyThreadRequestsResolved(event: ThreadRequestsResolved): void {
198200
}
199201

200202
/**
201-
* Tracks one thread's announced pending requests. Feed it the pending ids of
202-
* each authoritative projection; it notifies on the first one and whenever an
203+
* Tracks one thread's announced pending requests. Feed it the runtime requests
204+
* of each authoritative projection; it notifies on the first one and whenever an
203205
* announced request is no longer pending. New requests alone stay quiet.
204206
*/
205207
export function makeThreadRequestsResolvedAnnouncer(
206208
environmentId: EnvironmentId,
207209
threadId: ThreadId,
208210
) {
209211
let announced: ReadonlySet<RuntimeRequestId> | null = null;
210-
return (pendingRequestIds: ReadonlyArray<RuntimeRequestId>) => {
212+
return (
213+
runtimeRequests: ReadonlyArray<
214+
Pick<OrchestrationV2ThreadProjection["runtimeRequests"][number], "id" | "status">
215+
>,
216+
) => {
217+
const pendingRequestIds = runtimeRequests.flatMap((request) =>
218+
request.status === "pending" ? [request.id] : [],
219+
);
211220
const pending = new Set(pendingRequestIds);
212221
const resolvedSome = announced === null || [...announced].some((id) => !pending.has(id));
213222
announced = pending;
214-
if (resolvedSome) notifyThreadRequestsResolved({ environmentId, threadId, pendingRequestIds });
223+
if (!resolvedSome) return;
224+
const unansweredRequestIds = runtimeRequests.flatMap((request) =>
225+
request.status === "cancelled" || request.status === "expired" ? [request.id] : [],
226+
);
227+
notifyThreadRequestsResolved({
228+
environmentId,
229+
threadId,
230+
pendingRequestIds,
231+
unansweredRequestIds,
232+
});
215233
};
216234
}
217235

218-
export function pendingRuntimeRequestIds(
219-
projection: Pick<OrchestrationV2ThreadProjection, "runtimeRequests">,
220-
): RuntimeRequestId[] {
221-
return projection.runtimeRequests.flatMap((request) =>
222-
request.status === "pending" ? [request.id] : [],
223-
);
224-
}
225-
226236
export function derivePendingThreadRequests(
227237
projection: Pick<ThreadStructure, "runtimeRequests" | "turnItems">,
228238
): PendingThreadRequests {

‎packages/client-runtime/src/state/threads-sync.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2500,6 +2500,7 @@ describe("EnvironmentThreads", () => {
25002500
environmentId: TARGET.environmentId,
25012501
threadId: THREAD_ID,
25022502
pendingRequestIds: [],
2503+
unansweredRequestIds: [],
25032504
});
25042505
expect(yield* Queue.size(announced)).toBe(0);
25052506
}),

‎packages/client-runtime/src/state/threads.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ import {
5353
type ThreadHistoryMeta,
5454
} from "./threadHistoryMerge.ts";
5555
import * as ThreadSnapshotLoader from "./threadSnapshotHttp.ts";
56-
import { makeThreadRequestsResolvedAnnouncer, pendingRuntimeRequestIds } from "./threadRequests.ts";
56+
import { makeThreadRequestsResolvedAnnouncer } from "./threadRequests.ts";
5757
import {
5858
EMPTY_ENVIRONMENT_THREAD_STATE,
5959
type EnvironmentThreadState,
@@ -309,7 +309,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
309309
const owns = resumeCache === undefined || resumeCache.owner === owner;
310310
if (owns && current.status === "deleted") announceRequests([]);
311311
else if (owns && current.status === "live" && Option.isSome(current.data))
312-
announceRequests(pendingRuntimeRequestIds(current.data.value));
312+
announceRequests(current.data.value.runtimeRequests);
313313
committed = {
314314
state: current,
315315
sequence,

0 commit comments

Comments
 (0)