Open History to see the last commit
1import {
2 CommandId,
3 type EnvironmentId,
4 type OrchestrationV2ShellSnapshot,
5 type OrchestrationV2ThreadFamily,
6 type OrchestrationV2ThreadShell,
7 type ThreadId,
8} from "@t3tools/contracts";
9import * as Cause from "effect/Cause";
10import * as DateTime from "effect/DateTime";
11import * as Effect from "effect/Effect";
12import * as Exit from "effect/Exit";
13import * as SecureRandom from "effect/crypto/SecureRandom";
14import * as Schema from "effect/Schema";
15import * as Semaphore from "effect/Semaphore";
16import { Atom, type AtomRegistry } from "effect/reactivity";
17
18import {
19 type PendingThreadTriage,
20 type PendingThreadTriages,
21 ThreadTriageOutboxStore,
22} from "../platform/threadTriageOutboxStore.ts";
23import { EnvironmentRpcUnavailableError, isRpcClientError } from "../rpc/client.ts";
24import type { EnvironmentShellStatus, ShellCommandReceipt } from "./shell.ts";
25import { type AtomCommand, provideAtomRuntime } from "./runtime.ts";
26
27type Target<I> = { readonly environmentId: EnvironmentId; readonly input: I };
28
29const isUnavailable = Schema.is(EnvironmentRpcUnavailableError);
30
31/** Failures that say nothing about whether the server would accept the change. */
32const isTransient = (cause: Cause.Cause<unknown>) =>
33 cause.reasons.some(
34 (reason) =>
35 Cause.isInterruptReason(reason) ||
36 (Cause.isFailReason(reason) &&
37 (isUnavailable(reason.error) || isRpcClientError(reason.error))),
38 );
39
40/**
41 * What the user acted on: the thread's work and every triage decision with its time. A rename,
42 * tag change or visit is left out, so it does not drop the queued change.
43 */
44function seenState(thread: OrchestrationV2ThreadShell, withOrder = true) {
45 return JSON.stringify([
46 thread.latestRunId,
47 thread.status,
48 thread.itemCount,
49 thread.pendingRuntimeRequest?.id ?? null,
50 thread.settledOverride,
51 ...[
52 thread.settledAt,
53 thread.unsettledAt,
54 thread.snoozedUntil,
55 thread.snoozedAt,
56 thread.pinnedAt,
57 ].map((time) => (time == null ? null : DateTime.toEpochMillis(time))),
58 ...(withOrder ? [[thread.pinOrderKey ?? null, thread.activeOrderKey ?? null]] : []),
59 ]);
60}
61
62const sameEntries = (a: PendingThreadTriages, b: PendingThreadTriages) =>
63 a.length === b.length && a.every((entry, index) => entry.commandId === b[index]!.commandId);
64
65/**
66 * Settle and snooze for an environment that is not connected: the change is stored on the
67 * device, shown at once, and sent when the environment's shell is synchronized again.
68 */
69export function createThreadTriageOutbox<R, E, SendError, RE>(input: {
70 readonly runtime: Atom.AtomRuntime<SecureRandom.SecureRandom | R, E>;
71 readonly sourceSnapshotAtom: (
72 environmentId: EnvironmentId,
73 ) => Atom.Atom<OrchestrationV2ShellSnapshot | null>;
74 readonly shellStatusAtom: (environmentId: EnvironmentId) => Atom.Atom<EnvironmentShellStatus>;
75 /** Returns the thread itself when the action cannot apply to it. */
76 readonly apply: (
77 thread: OrchestrationV2ThreadShell,
78 action: PendingThreadTriage["action"],
79 queuedAt: DateTime.Utc,
80 ) => OrchestrationV2ThreadShell;
81 /** Sends the action under its command id, which the server answers only once. */
82 readonly send: (
83 registry: AtomRegistry.AtomRegistry,
84 entry: PendingThreadTriage,
85 ) => Effect.Effect<unknown, SendError>;
86 readonly readFamily: AtomCommand<Target<{ threadId: ThreadId }>, OrchestrationV2ThreadFamily, RE>;
87}) {
88 const entriesAtom = Atom.make<PendingThreadTriages>([]).pipe(Atom.keepAlive);
89 // Storage is shared with other tabs, so memory takes each result in the order storage gave it.
90 const order = Semaphore.makeUnsafe(1);
91 const update = Effect.fn("ThreadTriageOutbox.update")(function* (
92 registry: AtomRegistry.AtomRegistry,
93 change: (stored: PendingThreadTriages) => PendingThreadTriages,
94 ) {
95 const store = yield* ThreadTriageOutboxStore;
96 return yield* store.update(change).pipe(
97 Effect.tap((entries) =>
98 Effect.sync(() => {
99 if (!sameEntries(registry.get(entriesAtom), entries)) {
100 registry.set(entriesAtom, entries);
101 }
102 }),
103 ),
104 order.withPermit,
105 );
106 });
107 const read = (registry: AtomRegistry.AtomRegistry) => update(registry, (stored) => stored);
108
109 const pendingFor = (
110 registry: AtomRegistry.AtomRegistry,
111 environmentId: EnvironmentId,
112 threadId: ThreadId,
113 ) =>
114 registry
115 .get(entriesAtom)
116 .find((entry) => entry.environmentId === environmentId && entry.threadId === threadId);
117 /** Never fails: a change that stays stored is judged again on the next synchronized shell. */
118 const forget = (registry: AtomRegistry.AtomRegistry, commandId: CommandId | undefined) =>
119 commandId === undefined
120 ? Effect.void
121 : update(registry, (stored) =>
122 stored.some((entry) => entry.commandId === commandId)
123 ? stored.filter((entry) => entry.commandId !== commandId)
124 : stored,
125 ).pipe(provideAtomRuntime(registry, input.runtime), Effect.ignore);
126
127 // The live shell is the server's state: it wins over a change made against an older one.
128 const replay = Effect.fn("ThreadTriageOutbox.replay")(function* (
129 registry: AtomRegistry.AtomRegistry,
130 environmentId: EnvironmentId,
131 ) {
132 for (const entry of yield* read(registry)) {
133 if (entry.environmentId !== environmentId) continue;
134 const find = (rows: OrchestrationV2ThreadFamily | null) =>
135 rows?.threads.find((candidate) => candidate.id === entry.threadId);
136 const shell = () => registry.get(input.sourceSnapshotAtom(environmentId));
137 const target = { environmentId, input: { threadId: entry.threadId } };
138 const family =
139 find(shell()) === undefined && shell()?.olderSettled !== undefined
140 ? yield* Effect.exit(input.readFamily.run(registry, target))
141 : undefined;
142 if (family?._tag === "Failure") continue;
143 // Read again: this or another tab may have cancelled or replaced it while an earlier
144 // change was being sent.
145 const stored = yield* read(registry);
146 if (!stored.some((current) => current.commandId === entry.commandId)) continue;
147 // A shell past the host's read may have changed or removed the row: replay with a new read.
148 if (family && (shell()?.snapshotSequence ?? 0) > family.value.snapshotSequence)
149 return void registry.refresh(syncAtom(environmentId));
150 // The shell may have trimmed the row while storage was read; the host may still have it.
151 if (!family && find(shell()) === undefined && shell()?.olderSettled !== undefined)
152 return void registry.refresh(syncAtom(environmentId));
153 const thread = find(family?.value ?? shell());
154 if (
155 thread !== undefined &&
156 // A change stored before order keys were compared has none, so it matches without them.
157 (seenState(thread) === entry.seen || seenState(thread, false) === entry.seen) &&
158 input.apply(thread, entry.action, DateTime.nowUnsafe()) !== thread
159 ) {
160 const sent = yield* Effect.exit(input.send(registry, entry));
161 if (Exit.isFailure(sent) && isTransient(sent.cause)) continue;
162 }
163 yield* forget(registry, entry.commandId);
164 }
165 });
166 // Rebuilt on each shell status, which stops a replay when the shell is no longer synchronized
167 // and so keeps one replay per environment. Any other status only loads what is stored.
168 const syncAtom = Atom.family((environmentId: EnvironmentId) =>
169 input.runtime.atom((get) =>
170 get(input.shellStatusAtom(environmentId)) === "live"
171 ? replay(get.registry, environmentId)
172 : Effect.asVoid(read(get.registry)),
173 ),
174 );
175 const environmentEntriesAtom = Atom.family((environmentId: EnvironmentId) =>
176 Atom.make((get) => {
177 get.mount(syncAtom(environmentId));
178 return get(entriesAtom).filter((entry) => entry.environmentId === environmentId);
179 }),
180 );
181
182 const snapshotAtom = Atom.family((environmentId: EnvironmentId) =>
183 Atom.make((get) => {
184 const snapshot = get(input.sourceSnapshotAtom(environmentId));
185 const entries = get(environmentEntriesAtom(environmentId));
186 if (snapshot === null || entries.length === 0) return snapshot;
187 const byThread = new Map(entries.map((entry) => [entry.threadId, entry]));
188 return {
189 ...snapshot,
190 threads: snapshot.threads.map((thread) => {
191 const entry = byThread.get(thread.id);
192 return entry === undefined ? thread : input.apply(thread, entry.action, entry.queuedAt);
193 }),
194 };
195 }),
196 );
197
198 const pendingSyncAtom = Atom.family((environmentId: EnvironmentId) =>
199 Atom.make(
200 (get): ReadonlySet<ThreadId> =>
201 new Set(get(environmentEntriesAtom(environmentId)).map((entry) => entry.threadId)),
202 ),
203 );
204
205 const queue = Effect.fn("ThreadTriageOutbox.queue")(function* (
206 registry: AtomRegistry.AtomRegistry,
207 environmentId: EnvironmentId,
208 thread: OrchestrationV2ThreadShell,
209 action: PendingThreadTriage["action"],
210 queuedAt: DateTime.Utc,
211 ) {
212 const random = yield* SecureRandom.SecureRandom;
213 const commandId = CommandId.make(yield* random.uuidV4());
214 const stored = yield* update(registry, (current) => {
215 const sameThread = (entry: PendingThreadTriage) =>
216 entry.environmentId === environmentId && entry.threadId === thread.id;
217 // One change per thread. A snooze cannot replace a settle, which online it keeps.
218 return action.type === "snooze" && current.find(sameThread)?.action.type === "settle"
219 ? current
220 : [
221 ...current.filter((entry) => !sameThread(entry)),
222 {
223 environmentId,
224 threadId: thread.id,
225 commandId,
226 action,
227 queuedAt,
228 seen: seenState(thread),
229 },
230 ];
231 });
232 return stored.some((entry) => entry.commandId === commandId);
233 });
234
235 /** Queues the action on the device when its environment is not connected. */
236 function queueWhenOffline<I extends { readonly threadId: ThreadId }, CE>(
237 command: AtomCommand<Target<I>, ShellCommandReceipt, CE>,
238 toAction: (input: I) => PendingThreadTriage["action"],
239 ): typeof command {
240 return {
241 label: command.label,
242 run: (registry, target) =>
243 Effect.suspend(() => {
244 const { environmentId } = target;
245 const { threadId } = target.input;
246 // Read before sending: the change is judged against what the user saw when acting.
247 const snapshot = registry.get(input.sourceSnapshotAtom(environmentId));
248 const thread = snapshot?.threads.find((candidate) => candidate.id === threadId);
249 return command.run(registry, target).pipe(
250 // The server now has a newer decision than the queued one.
251 Effect.tap(() =>
252 forget(registry, pendingFor(registry, environmentId, threadId)?.commandId),
253 ),
254 Effect.catchIf(isUnavailable, (unavailable) => {
255 const action = toAction(target.input);
256 const queuedAt = DateTime.nowUnsafe();
257 if (
258 snapshot == null ||
259 thread === undefined ||
260 input.apply(thread, action, queuedAt) === thread
261 ) {
262 return Effect.fail(unavailable);
263 }
264 return queue(registry, environmentId, thread, action, queuedAt).pipe(
265 provideAtomRuntime(registry, input.runtime),
266 Effect.exit,
267 Effect.flatMap((queued) =>
268 Exit.isSuccess(queued) && queued.value
269 ? Effect.succeed({
270 value: { sequence: snapshot.snapshotSequence },
271 dispatched: undefined,
272 })
273 : Effect.fail(unavailable),
274 ),
275 );
276 }),
277 );
278 }),
279 };
280 }
281
282 /**
283 * Undo of a queued change removes it from storage first, so a replay that has not reached it
284 * skips it; storage decides, so the change removed is the one stored now, also by another tab.
285 * Offline that is the whole undo, reported as `cancelledOnDevice`. While the shell is
286 * synchronized the environment is asked too, after any send already in its lane.
287 */
288 function cancelQueued<I extends { readonly threadId: ThreadId }, CE>(
289 command: AtomCommand<Target<I>, { readonly sequence: number }, CE>,
290 cancels: PendingThreadTriage["action"]["type"],
291 ) {
292 const cancelled = { sequence: 0, cancelledOnDevice: true } as const;
293 return {
294 label: command.label,
295 run: (registry: AtomRegistry.AtomRegistry, target: Target<I>) =>
296 Effect.suspend(() => {
297 const { environmentId } = target;
298 const { threadId } = target.input;
299 const live = registry.get(input.shellStatusAtom(environmentId)) === "live";
300 let removed = false;
301 const remove = update(registry, (stored) => {
302 const kept = stored.filter(
303 (entry) =>
304 entry.environmentId !== environmentId ||
305 entry.threadId !== threadId ||
306 entry.action.type !== cancels,
307 );
308 removed = kept.length !== stored.length;
309 return removed ? kept : stored;
310 }).pipe(provideAtomRuntime(registry, input.runtime));
311 const sent = command.run(registry, target).pipe(
312 Effect.tap(() =>
313 forget(registry, pendingFor(registry, environmentId, threadId)?.commandId),
314 ),
315 // The connection dropped before the shell noticed, so nothing was sent.
316 Effect.catchIf(isUnavailable, (unavailable) =>
317 removed ? Effect.succeed(cancelled) : Effect.fail(unavailable),
318 ),
319 );
320 return remove.pipe(
321 Effect.flatMap(() => (removed && !live ? Effect.succeed(cancelled) : sent)),
322 );
323 }),
324 };
325 }
326
327 return { snapshotAtom, pendingSyncAtom, queueWhenOffline, cancelQueued };
328}