Open History to see the last commit
1import type {
2 ChatAttachment,
3 MessageId,
4 ModelSelection,
5 OrchestrationMessageContext,
6 RunId,
7 UploadChatAttachment,
8} from "@t3tools/contracts";
9import * as Equal from "effect/Equal";
10import { useAtomValue } from "@effect/atom-react";
11import { msg } from "gt-react-native";
12import {
13 replaceComposerContextReferences,
14 stripAttachmentOnlyBootstrapPrompt,
15} from "@t3tools/shared/composerContextReferences";
16import {
17 collectComposerInlineTokens,
18 restoreTrailingTokenSpace,
19} from "@t3tools/shared/composerInlineTokens";
20import { markdownMathRanges } from "@t3tools/shared/markdownMath";
21import { collectComposerModelMentions } from "@t3tools/client-runtime/composer-model-mentions";
22import {
23 makeQueuedRunEditStore,
24 resolveQueuedEditExit,
25 type QueuedRunsAtom,
26} from "@t3tools/client-runtime/queued-run-edit";
27
28import { m } from "../i18n/messages";
29import { referencedComposerContext, uploadedComposerContext } from "../lib/composerContext";
30import { appAtomRegistry } from "./atom-registry";
31import { abortComposerDraftOperations } from "./composerDraftOperations";
32import { queuedEditDraftKey } from "./queued-edit-draft-key";
33import { setThreadComposerError } from "./thread-composer-error";
34import {
35 clearComposerDraft,
36 getComposerDraftSnapshot,
37 mergeComposerDraftContent,
38 removeComposerDraftAttachment,
39 setComposerDraftContext,
40 setComposerDraftText,
41 updateComposerDraftSettings,
42} from "./use-composer-drafts";
43
44export interface QueuedRunEdit {
45 readonly modelSelection?: ModelSelection;
46 readonly followsThreadSelection?: boolean;
47 readonly runId: RunId;
48 readonly messageId: MessageId;
49 readonly originalText: string;
50 /** Includes files whose chips the user deleted; read `keptQueuedEditAttachments` instead. */
51 readonly existingAttachments: ReadonlyArray<ChatAttachment>;
52 readonly context?: OrchestrationMessageContext;
53 /** Removing a server attachment changes the message even when the draft looks untouched. */
54 readonly removedExistingAttachment?: true;
55}
56
57const queuedRunEdits = makeQueuedRunEditStore<QueuedRunEdit>({
58 registry: appAtomRegistry,
59 label: "mobile-queued-run-edits",
60});
61
62export { queuedEditDraftKey } from "./queued-edit-draft-key";
63
64export const getQueuedRunEdit = queuedRunEdits.get;
65
66/** A paste into an edit reuses these instead of copying them, so a failed copy cannot lose one. */
67export function queuedEditAttachmentIds(draftKey: string): ReadonlySet<string> {
68 for (const [threadKey, edit] of Object.entries(appAtomRegistry.get(queuedRunEdits.atom))) {
69 if (queuedEditDraftKey(threadKey, edit.runId) === draftKey)
70 return new Set(edit.existingAttachments.map((attachment) => attachment.id));
71 }
72 return new Set();
73}
74
75export const isQueuedRunEditSaving = (threadKey: string): boolean =>
76 appAtomRegistry.get(queuedRunEdits.savingAtom)[threadKey] === true;
77
78/**
79 * The draft a sheet opened for `requestedKey` should edit now: a queued edit's
80 * draft only while that edit is still open, else the thread's own draft.
81 */
82export function activeComposerDraftKey(
83 threadKey: string,
84 requestedKey: string,
85 edit: QueuedRunEdit | null,
86): string {
87 if (requestedKey === threadKey) return threadKey;
88 return edit !== null && queuedEditDraftKey(threadKey, edit.runId) === requestedKey
89 ? requestedKey
90 : threadKey;
91}
92
93export function useQueuedRunEdit(threadKey: string | null): QueuedRunEdit | null {
94 const edits = useAtomValue(queuedRunEdits.atom);
95 return threadKey === null ? null : (edits[threadKey] ?? null);
96}
97
98/**
99 * The run started or was cancelled elsewhere. A changed edit goes back into
100 * the thread's composer when that is empty; otherwise it is dropped. Either
101 * way the thread says so, wherever the user is when it happens.
102 */
103function exitQueuedRunEdit(threadKey: string, edit: QueuedRunEdit): void {
104 const editDraftKey = queuedEditDraftKey(threadKey, edit.runId);
105 const editDraft = getComposerDraftSnapshot(editDraftKey);
106 const threadDraft = getComposerDraftSnapshot(threadKey);
107 // The started message keeps its own attachments, so their chips must not follow the edit back.
108 const startedIds = new Set(
109 edit.context?.records.flatMap((record) => ("attachmentId" in record ? [record.contextId] : [])),
110 );
111 const recoveredText = replaceComposerContextReferences(editDraft.text, (ref) =>
112 startedIds.has(ref.contextId) ? "" : ref.source,
113 );
114 const editRestorable = recoveredText.trim().length > 0 || editDraft.attachments.length > 0;
115 const modelChanged =
116 editDraft.modelSelection !== undefined &&
117 !Equal.equals(editDraft.modelSelection, edit.modelSelection);
118 const recovery = resolveQueuedEditExit({
119 editChanged:
120 modelChanged ||
121 editDraft.text !== edit.originalText ||
122 editDraft.attachments.length > 0 ||
123 edit.removedExistingAttachment === true,
124 // A cleared edit has nothing to put back, so it can only be discarded.
125 threadDraftEmpty:
126 editRestorable &&
127 threadDraft.text.trim().length === 0 &&
128 threadDraft.attachments.length === 0,
129 });
130 if (recovery === "kept") {
131 if (modelChanged)
132 updateComposerDraftSettings(threadKey, { modelSelection: editDraft.modelSelection });
133 // The merge publishes the draft before writing it, so a failed write only delays persistence to the next one.
134 mergeComposerDraftContent(threadKey, {
135 text: recoveredText,
136 attachments: editDraft.attachments,
137 ...(editDraft.context ? { context: editDraft.context } : {}),
138 }).catch((error: unknown) => {
139 console.warn("[queued-run-edit] could not persist the recovered edit", error);
140 });
141 }
142 clearComposerDraft(editDraftKey, { deferAttachmentCleanup: recovery === "kept" });
143 if (recovery === "clean") return;
144 setThreadComposerError(
145 threadKey,
146 recovery === "kept"
147 ? m(msg("That message already started. Your edit is back in the composer."))
148 : m(msg("That message already started, so the edit was discarded.")),
149 );
150}
151
152/** `runs` is the thread's runs; the edit ends when its run leaves the queue. */
153export function beginQueuedRunEdit(
154 threadKey: string,
155 edit: QueuedRunEdit,
156 runs: QueuedRunsAtom,
157): void {
158 const previous = getQueuedRunEdit(threadKey);
159 if (previous !== null && previous.runId !== edit.runId) {
160 clearComposerDraft(queuedEditDraftKey(threadKey, previous.runId));
161 }
162 // The composer moves off the thread draft, so a paste or pick still running for it is dropped.
163 abortComposerDraftOperations(threadKey);
164 const draftKey = queuedEditDraftKey(threadKey, edit.runId);
165 const originalText = restoreTrailingTokenSpace(
166 stripAttachmentOnlyBootstrapPrompt(edit.originalText),
167 (text) => [
168 ...collectComposerInlineTokens(text, { findMath: markdownMathRanges }),
169 ...collectComposerModelMentions(text).filter((mention) =>
170 /\s/u.test(text[mention.end] ?? ""),
171 ),
172 ],
173 );
174 clearComposerDraft(draftKey);
175 setComposerDraftText(draftKey, originalText);
176 if (edit.modelSelection && !edit.followsThreadSelection)
177 updateComposerDraftSettings(draftKey, { modelSelection: edit.modelSelection });
178 setComposerDraftContext(draftKey, edit.context);
179 queuedRunEdits.begin(
180 threadKey,
181 { ...edit, originalText },
182 { runs, onRunLeftQueue: exitQueuedRunEdit },
183 );
184}
185
186export function removeQueuedRunEditAttachment(threadKey: string, attachmentId: string): void {
187 const edit = getQueuedRunEdit(threadKey);
188 if (edit === null) return;
189 // Its chip goes too, or the saved message keeps a reference to an attachment it no longer has.
190 removeComposerDraftAttachment(queuedEditDraftKey(threadKey, edit.runId), attachmentId);
191 queuedRunEdits.update(threadKey, (edit) => ({
192 ...edit,
193 removedExistingAttachment: true,
194 existingAttachments: edit.existingAttachments.filter(
195 (attachment) => attachment.id !== attachmentId,
196 ),
197 }));
198}
199
200export function endQueuedRunEdit(
201 threadKey: string,
202 options?: { readonly deferAttachmentCleanup?: boolean },
203): void {
204 const edit = getQueuedRunEdit(threadKey);
205 if (edit === null) return;
206 clearComposerDraft(queuedEditDraftKey(threadKey, edit.runId), options);
207 queuedRunEdits.end(threadKey);
208}
209
210/**
211 * Claims the open edit for a save; while it runs, the save's result decides the
212 * edit's fate. Null when there is no edit or a save is already in flight.
213 */
214export const startQueuedRunEditSave = queuedRunEdits.startSave;
215
216const attachmentIdsInContext = (context: OrchestrationMessageContext | undefined) =>
217 new Set(
218 context?.records.flatMap((record) => ("attachmentId" in record ? [record.attachmentId] : [])),
219 );
220
221// The composer reads the kept list on every keystroke; the edit's own text never changes.
222const startedChipIds = new WeakMap<QueuedRunEdit, ReadonlySet<string>>();
223
224/**
225 * A server file that had a chip in the original text is dropped while the draft's context holds
226 * no record for it, as a draft drops its own files, and kept again once such a record is back.
227 * Images outlive their chips, as in a draft and on web.
228 */
229export function keptQueuedEditAttachments(
230 edit: QueuedRunEdit,
231 draftContext: OrchestrationMessageContext | undefined,
232): ReadonlyArray<ChatAttachment> {
233 let started = startedChipIds.get(edit);
234 if (started === undefined) {
235 started = attachmentIdsInContext(referencedComposerContext(edit.originalText, edit.context));
236 startedChipIds.set(edit, started);
237 }
238 const live = attachmentIdsInContext(draftContext);
239 const kept = edit.existingAttachments.filter(
240 (attachment) =>
241 attachment.type !== "file" || !started.has(attachment.id) || live.has(attachment.id),
242 );
243 // Keep the array identity while nothing is dropped so the strip sees no change.
244 return kept.length === edit.existingAttachments.length ? edit.existingAttachments : kept;
245}
246
247/** Attachments replace wholesale; resend kept server attachments with uploads in composer order. */
248export function resolveQueuedEditPayload(input: {
249 readonly edit: QueuedRunEdit;
250 readonly draftContext: OrchestrationMessageContext | undefined;
251 readonly draftAttachments: ReadonlyArray<{ readonly id: string }>;
252 readonly uploaded: ReadonlyArray<ChatAttachment | UploadChatAttachment>;
253}): {
254 readonly attachments: ReadonlyArray<ChatAttachment | UploadChatAttachment>;
255 readonly context: OrchestrationMessageContext | undefined;
256} {
257 const attachments = [
258 ...keptQueuedEditAttachments(input.edit, input.draftContext),
259 ...input.uploaded,
260 ];
261 const rebound = uploadedComposerContext(
262 input.draftContext,
263 input.draftAttachments,
264 input.uploaded,
265 );
266 if (rebound === undefined) return { attachments, context: undefined };
267 const liveIds = new Set(
268 attachments.flatMap((attachment) =>
269 "id" in attachment && attachment.id ? [attachment.id] : [],
270 ),
271 );
272 const records = rebound.records.filter(
273 (record) => !("attachmentId" in record) || liveIds.has(record.attachmentId),
274 );
275 return {
276 attachments,
277 context: records.length > 0 ? { version: 1, records } : undefined,
278 };
279}