The best way to control Claude Code, Codex and more from any computer or phone

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