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

queued-run-edit.ts

182 lines6.6 KB

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