Open History to see the last commit
1import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
2import type { PendingUserInputDraftAnswer } from "@t3tools/client-runtime/state/pending-user-input";
3import {
4 onThreadRequestsResolved,
5 pruneResolvedUserInputDrafts,
6 resolvedQuestionDraftKeys,
7 userInputDraftKey,
8} from "@t3tools/client-runtime/state/thread-requests";
9import type {
10 EnvironmentId,
11 RuntimeRequestId,
12 ScopedThreadRef,
13 ThreadContextRecord,
14 ThreadId,
15} from "@t3tools/contracts";
16import { create } from "zustand";
17import { DraftId, useComposerDraftStore } from "./composerDraftStore";
18import { releaseDraftAttachments } from "./lib/attachmentUploadQueue";
19import {
20 carryDisplacedCustomAnswerIntoPrompt,
21 threadContextsReferencedByAnswer,
22} from "./pendingUserInput";
23
24/** Edited question answers, keyed by `userInputDraftKey`; suggested answers are not stored. */
25export const usePendingUserInputAnswers = create<
26 Record<string, Record<string, PendingUserInputDraftAnswer>>
27>(() => ({}));
28export const usePendingUserInputQuestionIndex = create<Record<string, number>>(() => ({}));
29
30export function questionAttachmentDraftPrefix(
31 environmentId: EnvironmentId,
32 threadId: ThreadId,
33): string {
34 return `${encodeURIComponent(JSON.stringify(environmentId))}:question-${encodeURIComponent(JSON.stringify(threadId))}-`;
35}
36
37export function questionAttachmentDraftId(
38 environmentId: EnvironmentId,
39 threadId: ThreadId,
40 requestId: string,
41 questionId: string,
42): DraftId {
43 return DraftId.make(
44 `${questionAttachmentDraftPrefix(environmentId, threadId)}${encodeURIComponent(JSON.stringify([requestId, questionId]))}`,
45 );
46}
47
48type OpenQuestionAttachmentDraft = {
49 readonly draftId: DraftId;
50 readonly requestKeys: ReadonlyArray<DraftId>;
51};
52
53const openQuestionDrafts = new Map<string, OpenQuestionAttachmentDraft>();
54
55export function openQuestionAttachmentDraft(
56 threadRef: ScopedThreadRef,
57): OpenQuestionAttachmentDraft | null {
58 return openQuestionDrafts.get(scopedThreadKey(threadRef)) ?? null;
59}
60
61export function countQuestionRequestAttachments(draftId: DraftId): number | null {
62 for (const draft of openQuestionDrafts.values()) {
63 if (draft.draftId === draftId) return countQuestionAttachments(draft.requestKeys);
64 }
65 return null;
66}
67
68export function trackOpenQuestionAttachmentDraft(
69 threadRef: ScopedThreadRef,
70 draft: OpenQuestionAttachmentDraft,
71): () => void {
72 const key = scopedThreadKey(threadRef);
73 openQuestionDrafts.set(key, draft);
74 return () => {
75 if (openQuestionDrafts.get(key) === draft) openQuestionDrafts.delete(key);
76 };
77}
78
79export const useQuestionAttachmentPreparation = create<{ counts: Record<string, number> }>(() => ({
80 counts: {},
81}));
82
83export function countQuestionAttachments(keys: ReadonlyArray<DraftId>): number {
84 const store = useComposerDraftStore.getState();
85 const { counts } = useQuestionAttachmentPreparation.getState();
86 return keys.reduce((total, key) => {
87 const draft = store.getComposerDraft(key);
88 return total + (draft?.images.length ?? 0) + (draft?.files.length ?? 0) + (counts[key] ?? 0);
89 }, 0);
90}
91
92export function changeQuestionAttachmentPreparation(key: DraftId, delta: number): void {
93 useQuestionAttachmentPreparation.setState((state) =>
94 delta < 0 && !(key in state.counts)
95 ? state
96 : {
97 counts: { ...state.counts, [key]: Math.max(0, (state.counts[key] ?? 0) + delta) },
98 },
99 );
100}
101
102/** Releases the draft's attachments except `keepIds`, which have moved to another draft. */
103export function clearQuestionAttachmentDraft(
104 key: DraftId,
105 keepIds: ReadonlySet<string> = new Set(),
106): void {
107 const store = useComposerDraftStore.getState();
108 const draft = store.getComposerDraft(key);
109 if (draft) {
110 releaseDraftAttachments([...draft.images, ...draft.files].filter(({ id }) => !keepIds.has(id)));
111 for (const image of draft.images) {
112 if (!keepIds.has(image.id) && image.previewUrl.startsWith("blob:")) {
113 URL.revokeObjectURL(image.previewUrl);
114 }
115 }
116 }
117 store.clearComposerContent(key);
118 useQuestionAttachmentPreparation.setState(({ counts }) => {
119 const next = { ...counts };
120 delete next[key];
121 return { counts: next };
122 });
123}
124
125/** Clears the thread's question attachment drafts for every request outside `pendingRequestIds`. */
126function pruneResolvedQuestionAttachmentDrafts(
127 environmentId: EnvironmentId,
128 threadId: ThreadId,
129 pendingRequestIds: ReadonlyArray<string>,
130): void {
131 const keys = new Set([
132 ...Object.keys(useComposerDraftStore.getState().draftsByThreadKey),
133 ...Object.keys(useQuestionAttachmentPreparation.getState().counts),
134 ]);
135 const prefix = questionAttachmentDraftPrefix(environmentId, threadId);
136 for (const key of resolvedQuestionDraftKeys(keys, prefix, pendingRequestIds)) {
137 clearQuestionAttachmentDraft(DraftId.make(key));
138 }
139}
140
141/**
142 * Stop cancels an open question and a provider timeout expires it; neither sent
143 * the typed answers, so they move to the thread's own draft (not a queued-message
144 * edit the composer may be showing) with the thread chips they reference and
145 * every file or image attached to them.
146 */
147function returnUnsentAnswersToThreadDraft(
148 environmentId: EnvironmentId,
149 threadId: ThreadId,
150 unansweredRequestIds: ReadonlyArray<RuntimeRequestId>,
151): void {
152 const answers = usePendingUserInputAnswers.getState();
153 const store = useComposerDraftStore.getState();
154 const target = scopeThreadRef(environmentId, threadId);
155 const currentPrompt = store.getComposerDraft(target)?.prompt ?? "";
156 let prompt = currentPrompt;
157 const threadContexts: ThreadContextRecord[] = [];
158 for (const requestId of unansweredRequestIds) {
159 const drafts = answers[userInputDraftKey(environmentId, threadId, requestId)] ?? {};
160 for (const [questionId, { customAnswer }] of Object.entries(drafts)) {
161 const nextPrompt = carryDisplacedCustomAnswerIntoPrompt(prompt, customAnswer);
162 if (nextPrompt === prompt) continue;
163 prompt = nextPrompt;
164 const questionDraft = store.getComposerDraft(
165 questionAttachmentDraftId(environmentId, threadId, requestId, questionId),
166 );
167 threadContexts.push(
168 ...threadContextsReferencedByAnswer(
169 customAnswer ?? "",
170 questionDraft?.threadContexts ?? [],
171 ),
172 );
173 }
174 }
175 if (prompt !== currentPrompt) {
176 store.setPrompt(target, prompt);
177 store.addThreadContexts(target, threadContexts, { appendReference: false });
178 }
179
180 const threadPrefix = questionAttachmentDraftPrefix(environmentId, threadId);
181 const requestPrefixes = unansweredRequestIds.map(
182 (requestId) =>
183 `${threadPrefix}${encodeURIComponent(`${JSON.stringify([requestId]).slice(0, -1)},`)}`,
184 );
185 const questionDrafts = Object.entries(store.draftsByThreadKey).filter(([key]) =>
186 requestPrefixes.some((requestPrefix) => key.startsWith(requestPrefix)),
187 );
188 const images = questionDrafts.flatMap(([, draft]) => draft.images);
189 const files = questionDrafts.flatMap(([, draft]) => draft.files);
190 if (images.length === 0 && files.length === 0) return;
191 store.addImages(target, images);
192 store.addFiles(target, files);
193 const moved = useComposerDraftStore.getState().getComposerDraft(target);
194 const movedIds = new Set([...(moved?.images ?? []), ...(moved?.files ?? [])].map(({ id }) => id));
195 // Only a mounted composer re-serializes images, so carry their saved copies for a reload.
196 const persisted = moved?.persistedAttachments ?? [];
197 const persistedIds = new Set(persisted.map(({ id }) => id));
198 const movedPersisted = questionDrafts
199 .flatMap(([, draft]) => draft.persistedAttachments)
200 .filter(({ id }) => movedIds.has(id) && !persistedIds.has(id));
201 if (movedPersisted.length > 0) {
202 void store.syncPersistedAttachments(target, [...persisted, ...movedPersisted]);
203 }
204 for (const [key] of questionDrafts) clearQuestionAttachmentDraft(DraftId.make(key), movedIds);
205}
206
207// Resolution can come from anywhere: another device, an interrupt, the turn
208// ending, or a reload over drafts for requests resolved meanwhile. One listener,
209// so unsent answers and their chips are read before their drafts are pruned.
210onThreadRequestsResolved(({ environmentId, threadId, pendingRequestIds, unansweredRequestIds }) => {
211 returnUnsentAnswersToThreadDraft(environmentId, threadId, unansweredRequestIds);
212 usePendingUserInputAnswers.setState(
213 (existing) =>
214 pruneResolvedUserInputDrafts(existing, environmentId, threadId, pendingRequestIds),
215 true,
216 );
217 usePendingUserInputQuestionIndex.setState(
218 (existing) =>
219 pruneResolvedUserInputDrafts(existing, environmentId, threadId, pendingRequestIds),
220 true,
221 );
222 pruneResolvedQuestionAttachmentDrafts(environmentId, threadId, pendingRequestIds);
223});