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

main
ts 223 lines 7.62 KB
Raw
1 import { mFallback, msg } from "gt-i18n";
2 import type { MFunctionType } from "gt-i18n/types";
3 /**
4 * A queued-message edit ends on save, cancel, or when its run leaves the queue.
5 * The store owns one watcher per edit, so "run left the queue" is handled exactly
6 * once, when the projection reports it, wherever the user is in the app. It also
7 * owns the edit's save, because a save outlives the view that started it.
8 */
9 import type { RunId } from "@t3tools/contracts";
10 import { Atom, type AtomRegistry } from "effect/reactivity";
11
12 export interface QueuedRunStatus {
13 readonly id: RunId;
14 readonly status: string;
15 }
16
17 /** The thread's runs, or null while they are unknown (detail not loaded yet). */
18 export type QueuedRunsAtom = Atom.Atom<ReadonlyArray<QueuedRunStatus> | null>;
19
20 interface ShellThreadPresence {
21 readonly id: string;
22 readonly deletedAt: unknown;
23 }
24
25 /**
26 * The edited thread's runs. A deleted thread (shell `deletedAt` or detail status
27 * `deleted`) reads as no runs, so its edit ends. Absence from the shell is not
28 * deletion: archived threads are dropped there but keep an editable queue, so
29 * everything else reads the detail's runs, unknown until it loads.
30 */
31 export function makeQueuedRunsAtom(input: {
32 readonly threadId: string;
33 readonly snapshot: Atom.Atom<{ readonly threads: ReadonlyArray<ShellThreadPresence> } | null>;
34 readonly detailStatus: Atom.Atom<string>;
35 readonly runs: Atom.Atom<ReadonlyArray<QueuedRunStatus> | null>;
36 }): QueuedRunsAtom {
37 return Atom.make((get) => {
38 const shellThread = get(input.snapshot)?.threads.find(
39 (candidate) => candidate.id === input.threadId,
40 );
41 if (shellThread !== undefined && shellThread.deletedAt !== null) return [];
42 if (get(input.detailStatus) === "deleted") return [];
43 return get(input.runs);
44 });
45 }
46
47 function runLeftQueue(runs: ReadonlyArray<QueuedRunStatus> | null, runId: RunId): boolean {
48 if (runs === null) return false;
49 return !runs.some((run) => run.id === runId && run.status === "queued");
50 }
51
52 /**
53 * What happens to an open edit when its run leaves the queue: an unchanged
54 * edit just closes; a changed one moves into the thread's own draft when that
55 * draft is empty, and is dropped otherwise so it never overwrites the user's
56 * other work.
57 */
58 export function resolveQueuedEditExit(input: {
59 readonly editChanged: boolean;
60 readonly threadDraftEmpty: boolean;
61 }): "kept" | "discarded" | "clean" {
62 if (!input.editChanged) return "clean";
63 return input.threadDraftEmpty ? "kept" : "discarded";
64 }
65
66 /**
67 * Why a queued message can't be opened in the composer now, or null when it
68 * can. An open question takes the composer over for its answer, so an edit
69 * begun then would happen out of sight and could be sent before it is seen.
70 */
71 export function queuedRunEditBlockedReason(
72 input: {
73 readonly openQuestionCount: number;
74 },
75 resolve: MFunctionType = mFallback,
76 ): string | null {
77 return input.openQuestionCount > 0
78 ? resolve(msg("Answer the question to edit queued messages"))
79 : null;
80 }
81
82 interface ExitWatch<E> {
83 readonly runs: QueuedRunsAtom;
84 readonly runId: RunId;
85 readonly onRunLeftQueue: (threadKey: string, edit: E) => void;
86 cancel: (() => void) | null;
87 }
88
89 /**
90 * Settles a save from `startSave`. False, changing nothing, when the edit was
91 * ended or begun again meanwhile. Success ends the edit; failure resumes its
92 * exit watch and returns whether the edit survived it.
93 */
94 export type FinishQueuedRunEditSave = (succeeded: boolean) => boolean;
95
96 export function makeQueuedRunEditStore<E extends { readonly runId: RunId }>(options: {
97 readonly registry: AtomRegistry.AtomRegistry;
98 readonly label: string;
99 }) {
100 const { registry } = options;
101 const atom = Atom.make<Readonly<Record<string, E>>>({}).pipe(
102 Atom.keepAlive,
103 Atom.withLabel(options.label),
104 );
105 const savingAtom = Atom.make<Readonly<Record<string, true>>>({}).pipe(
106 Atom.keepAlive,
107 Atom.withLabel(`${options.label}-saving`),
108 );
109 // Each begin creates a new watch, so the watch is the edit's identity.
110 const watches = new Map<string, ExitWatch<E>>();
111
112 const setSaving = (threadKey: string, saving: boolean) => {
113 const current = registry.get(savingAtom);
114 if (threadKey in current === saving) return;
115 const next = { ...current };
116 if (saving) next[threadKey] = true;
117 else delete next[threadKey];
118 registry.set(savingAtom, next);
119 };
120
121 const get = (threadKey: string | null): E | null =>
122 threadKey === null ? null : (registry.get(atom)[threadKey] ?? null);
123
124 const write = (threadKey: string, edit: E | null) => {
125 const current = registry.get(atom);
126 if (edit === null) {
127 if (!(threadKey in current)) return;
128 const next = { ...current };
129 delete next[threadKey];
130 registry.set(atom, next);
131 return;
132 }
133 registry.set(atom, { ...current, [threadKey]: edit });
134 };
135
136 const unsubscribe = (watch: ExitWatch<E>) => {
137 watch.cancel?.();
138 watch.cancel = null;
139 };
140
141 const subscribe = (threadKey: string, watch: ExitWatch<E>) => {
142 const check = (runs: ReadonlyArray<QueuedRunStatus> | null) => {
143 if (watches.get(threadKey) !== watch || watch.cancel === null) return;
144 if (!runLeftQueue(runs, watch.runId)) return;
145 unsubscribe(watch);
146 watches.delete(threadKey);
147 const edit = get(threadKey);
148 if (edit === null || edit.runId !== watch.runId) return;
149 write(threadKey, null);
150 watch.onRunLeftQueue(threadKey, edit);
151 };
152 watch.cancel = registry.subscribe(watch.runs, check);
153 check(registry.get(watch.runs));
154 };
155
156 const stopWatch = (threadKey: string) => {
157 const watch = watches.get(threadKey);
158 if (watch === undefined) return;
159 unsubscribe(watch);
160 watches.delete(threadKey);
161 };
162
163 return {
164 atom,
165 /** Thread keys whose edit has a save in flight. */
166 savingAtom,
167 get,
168 /**
169 * Starts an edit, replacing any edit already open on the thread. When the
170 * run leaves the queue the edit is removed and `onRunLeftQueue` receives
171 * it; if the run already left, that happens immediately.
172 */
173 begin(
174 threadKey: string,
175 edit: E,
176 watch: {
177 readonly runs: QueuedRunsAtom;
178 readonly onRunLeftQueue: (threadKey: string, edit: E) => void;
179 },
180 ) {
181 stopWatch(threadKey);
182 write(threadKey, edit);
183 const next: ExitWatch<E> = { ...watch, runId: edit.runId, cancel: null };
184 watches.set(threadKey, next);
185 subscribe(threadKey, next);
186 },
187 update(threadKey: string, f: (edit: E) => E) {
188 const edit = get(threadKey);
189 if (edit !== null) write(threadKey, f(edit));
190 },
191 end(threadKey: string) {
192 stopWatch(threadKey);
193 write(threadKey, null);
194 },
195 /**
196 * Claims the open edit for a save, or returns null when there is no edit
197 * or a save is in flight. The exit watch pauses so the save's result decides
198 * the edit's fate. The claim outlives the edit: the server orders saves by
199 * arrival, so an overlapping older save could overwrite a newer one.
200 */
201 startSave(threadKey: string): FinishQueuedRunEditSave | null {
202 const watch = watches.get(threadKey);
203 if (watch === undefined || threadKey in registry.get(savingAtom)) return null;
204 setSaving(threadKey, true);
205 unsubscribe(watch);
206 let settled = false;
207 return (succeeded) => {
208 if (!settled) {
209 settled = true;
210 setSaving(threadKey, false);
211 }
212 if (watches.get(threadKey) !== watch) return false;
213 if (succeeded) {
214 stopWatch(threadKey);
215 write(threadKey, null);
216 return true;
217 }
218 subscribe(threadKey, watch);
219 return watches.get(threadKey) === watch;
220 };
221 },
222 };
223 }