Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

queued-run-edit.ts

206 lines7.6 KB

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 { stripAttachmentOnlyBootstrapPrompt } from "@t3tools/shared/composerContextReferences";
13import {
14 makeQueuedRunEditStore,
15 resolveQueuedEditExit,
16 type QueuedRunsAtom,
17} from "@t3tools/client-runtime/queued-run-edit";
18​
19import { m } from "../i18n/messages";
20import { uploadedComposerContext } from "../lib/composerContext";
21import { appAtomRegistry } from "./atom-registry";
22import { abortComposerDraftOperations } from "./composerDraftOperations";
23import { queuedEditDraftKey } from "./queued-edit-draft-key";
24import { setThreadComposerError } from "./thread-composer-error";
25import {
26 clearComposerDraft,
27 getComposerDraftSnapshot,
28 mergeComposerDraftContent,
29 setComposerDraftContext,
30 setComposerDraftText,
31 updateComposerDraftSettings,
32} from "./use-composer-drafts";
33​
34export interface QueuedRunEdit {
35 readonly modelSelection?: ModelSelection;
36 readonly followsThreadSelection?: boolean;
37 readonly runId: RunId;
38 readonly messageId: MessageId;
39 readonly originalText: string;
40 readonly existingAttachments: ReadonlyArray<ChatAttachment>;
41 readonly context?: OrchestrationMessageContext;
42 /** Removing a server attachment changes the message even when the draft looks untouched. */
43 readonly removedExistingAttachment?: true;
45​
46const queuedRunEdits = makeQueuedRunEditStore<QueuedRunEdit>({
47 registry: appAtomRegistry,
48 label: "mobile-queued-run-edits",
49});
50​
51export { queuedEditDraftKey } from "./queued-edit-draft-key";
52​
53export const getQueuedRunEdit = queuedRunEdits.get;
54​
55export const isQueuedRunEditSaving = (threadKey: string): boolean =>
56 appAtomRegistry.get(queuedRunEdits.savingAtom)[threadKey] === true;
57​
58/**
59 * The draft a sheet opened for `requestedKey` should edit now: a queued edit's
60 * draft only while that edit is still open, else the thread's own draft.
61 */
62export function activeComposerDraftKey(
63 threadKey: string,
64 requestedKey: string,
65 edit: QueuedRunEdit | null,
66): string {
67 if (requestedKey === threadKey) return threadKey;
68 return edit !== null && queuedEditDraftKey(threadKey, edit.runId) === requestedKey
69 ? requestedKey
70 : threadKey;
72​
73export function useQueuedRunEdit(threadKey: string | null): QueuedRunEdit | null {
74 const edits = useAtomValue(queuedRunEdits.atom);
75 return threadKey === null ? null : (edits[threadKey] ?? null);
77​
78/**
79 * The run started or was cancelled elsewhere. A changed edit goes back into
80 * the thread's composer when that is empty; otherwise it is dropped. Either
81 * way the thread says so, wherever the user is when it happens.
82 */
83function exitQueuedRunEdit(threadKey: string, edit: QueuedRunEdit): void {
84 const editDraftKey = queuedEditDraftKey(threadKey, edit.runId);
85 const editDraft = getComposerDraftSnapshot(editDraftKey);
86 const threadDraft = getComposerDraftSnapshot(threadKey);
87 const editRestorable = editDraft.text.trim().length > 0 || editDraft.attachments.length > 0;
88 const modelChanged =
89 editDraft.modelSelection !== undefined &&
90 !Equal.equals(editDraft.modelSelection, edit.modelSelection);
91 const recovery = resolveQueuedEditExit({
92 editChanged:
93 modelChanged ||
94 editDraft.text !== edit.originalText ||
95 editDraft.attachments.length > 0 ||
96 edit.removedExistingAttachment === true,
97 // A cleared edit has nothing to put back, so it can only be discarded.
98 threadDraftEmpty:
99 editRestorable &&
100 threadDraft.text.trim().length === 0 &&
101 threadDraft.attachments.length === 0,
102 });
103 if (recovery === "kept") {
104 if (modelChanged)
105 updateComposerDraftSettings(threadKey, { modelSelection: editDraft.modelSelection });
106 // The merge publishes the draft before writing it, so a failed write only delays persistence to the next one.
107 mergeComposerDraftContent(threadKey, {
108 text: editDraft.text,
109 attachments: editDraft.attachments,
110 ...(editDraft.context ? { context: editDraft.context } : {}),
111 }).catch((error: unknown) => {
112 console.warn("[queued-run-edit] could not persist the recovered edit", error);
113 });
114 }
115 clearComposerDraft(editDraftKey, { deferAttachmentCleanup: recovery === "kept" });
116 if (recovery === "clean") return;
117 setThreadComposerError(
118 threadKey,
119 recovery === "kept"
120 ? m(msg("That message already started. Your edit is back in the composer."))
121 : m(msg("That message already started, so the edit was discarded.")),
122 );
124​
125/** `runs` is the thread's runs; the edit ends when its run leaves the queue. */
126export function beginQueuedRunEdit(
127 threadKey: string,
128 edit: QueuedRunEdit,
129 runs: QueuedRunsAtom,
130): void {
131 const previous = getQueuedRunEdit(threadKey);
132 if (previous !== null && previous.runId !== edit.runId) {
133 clearComposerDraft(queuedEditDraftKey(threadKey, previous.runId));
134 }
135 // The composer moves off the thread draft, so a paste or pick still running for it is dropped.
136 abortComposerDraftOperations(threadKey);
137 const draftKey = queuedEditDraftKey(threadKey, edit.runId);
138 const originalText = stripAttachmentOnlyBootstrapPrompt(edit.originalText);
139 clearComposerDraft(draftKey);
140 setComposerDraftText(draftKey, originalText);
141 if (edit.modelSelection && !edit.followsThreadSelection)
142 updateComposerDraftSettings(draftKey, { modelSelection: edit.modelSelection });
143 setComposerDraftContext(draftKey, edit.context);
144 queuedRunEdits.begin(
145 threadKey,
146 { ...edit, originalText },
147 { runs, onRunLeftQueue: exitQueuedRunEdit },
148 );
150​
151export function removeQueuedRunEditAttachment(threadKey: string, attachmentId: string): void {
152 queuedRunEdits.update(threadKey, (edit) => ({
153 ...edit,
154 removedExistingAttachment: true,
155 existingAttachments: edit.existingAttachments.filter(
156 (attachment) => attachment.id !== attachmentId,
157 ),
158 }));
160​
161export function endQueuedRunEdit(
162 threadKey: string,
163 options?: { readonly deferAttachmentCleanup?: boolean },
164): void {
165 const edit = getQueuedRunEdit(threadKey);
166 if (edit === null) return;
167 clearComposerDraft(queuedEditDraftKey(threadKey, edit.runId), options);
168 queuedRunEdits.end(threadKey);
170​
171/**
172 * Claims the open edit for a save; while it runs, the save's result decides the
173 * edit's fate. Null when there is no edit or a save is already in flight.
174 */
175export const startQueuedRunEditSave = queuedRunEdits.startSave;
176​
177/** Attachments replace wholesale; resend kept server attachments with uploads in composer order. */
178export function resolveQueuedEditPayload(input: {
179 readonly edit: QueuedRunEdit;
180 readonly draftContext: OrchestrationMessageContext | undefined;
181 readonly draftAttachments: ReadonlyArray<{ readonly id: string }>;
182 readonly uploaded: ReadonlyArray<ChatAttachment | UploadChatAttachment>;
183}): {
184 readonly attachments: ReadonlyArray<ChatAttachment | UploadChatAttachment>;
185 readonly context: OrchestrationMessageContext | undefined;
186} {
187 const attachments = [...input.edit.existingAttachments, ...input.uploaded];
188 const rebound = uploadedComposerContext(
189 input.draftContext,
190 input.draftAttachments,
191 input.uploaded,
192 );
193 if (rebound === undefined) return { attachments, context: undefined };
194 const liveIds = new Set(
195 attachments.flatMap((attachment) =>
196 "id" in attachment && attachment.id ? [attachment.id] : [],
197 ),
198 );
199 const records = rebound.records.filter(
200 (record) => !("attachmentId" in record) || liveIds.has(record.attachmentId),
201 );
202 return {
203 attachments,
204 context: records.length > 0 ? { version: 1, records } : undefined,
205 };