The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { Atom, type AtomRegistry } from "effect/reactivity"; |
| 2 | import { msg } from "gt-react-native"; |
| 3 | |
| 4 | import { m } from "../../i18n/messages"; |
| 5 | import type { DraftComposerAttachment } from "../../lib/composerImages"; |
| 6 | import type { ComposerDraft } from "../../state/use-composer-drafts"; |
| 7 | import type { |
| 8 | IncomingShareDestination, |
| 9 | IncomingShareDraft, |
| 10 | selectIncomingShareAttachmentsForServer, |
| 11 | } from "../sharing/incoming-share-model"; |
| 12 | |
| 13 | export type ShareImportPhase = |
| 14 | | "idle" |
| 15 | | "reserving" |
| 16 | | "attaching" |
| 17 | | "consuming" |
| 18 | | "done" |
| 19 | | "failed" |
| 20 | | "cancelling" |
| 21 | | "cancelled"; |
| 22 | |
| 23 | export type ShareImportEvent = |
| 24 | | "start" |
| 25 | | "reserved" |
| 26 | | "attached" |
| 27 | | "consumed" |
| 28 | | "failed" |
| 29 | | "cancel" |
| 30 | | "cancelFailed" |
| 31 | | "cancelled"; |
| 32 | |
| 33 | const TRANSITIONS: Readonly< |
| 34 | Record<ShareImportPhase, Partial<Record<ShareImportEvent, ShareImportPhase>>> |
| 35 | > = { |
| 36 | idle: { start: "reserving" }, |
| 37 | reserving: { reserved: "attaching", failed: "failed" }, |
| 38 | attaching: { attached: "consuming", failed: "failed" }, |
| 39 | consuming: { consumed: "done", failed: "failed" }, |
| 40 | done: {}, |
| 41 | // "start" from failed is a retry. |
| 42 | failed: { start: "reserving", cancel: "cancelling" }, |
| 43 | cancelling: { cancelled: "cancelled", cancelFailed: "failed" }, |
| 44 | cancelled: {}, |
| 45 | }; |
| 46 | |
| 47 | /** Events that do not apply to the current phase leave it unchanged. */ |
| 48 | export function transitionShareImport( |
| 49 | phase: ShareImportPhase, |
| 50 | event: ShareImportEvent, |
| 51 | ): ShareImportPhase { |
| 52 | return TRANSITIONS[phase][event] ?? phase; |
| 53 | } |
| 54 | |
| 55 | function isShareImportInFlight(phase: ShareImportPhase): boolean { |
| 56 | return phase === "reserving" || phase === "attaching" || phase === "consuming"; |
| 57 | } |
| 58 | |
| 59 | /** |
| 60 | * One draft route importing one share into one draft. Plain data, compared |
| 61 | * structurally, so the screen can build it on every render. |
| 62 | */ |
| 63 | export interface ShareImportTarget { |
| 64 | /** The draft route's flow key; the import is abandoned once it leaves the stack. */ |
| 65 | readonly flowKey: string; |
| 66 | readonly routeKey: string; |
| 67 | readonly draftKey: string; |
| 68 | readonly destination: IncomingShareDestination; |
| 69 | readonly shareId: string; |
| 70 | } |
| 71 | |
| 72 | export interface ShareImportDeps { |
| 73 | readonly registry: AtomRegistry.AtomRegistry; |
| 74 | /** The share as the inbox holds it now. */ |
| 75 | readonly getShare: (shareId: string) => IncomingShareDraft | null; |
| 76 | readonly reserve: (shareId: string, destination: IncomingShareDestination) => Promise<void>; |
| 77 | readonly release: (shareId: string, destination: IncomingShareDestination) => Promise<void>; |
| 78 | readonly consume: (shareId: string) => Promise<void>; |
| 79 | readonly readDraft: (draftKey: string) => ComposerDraft; |
| 80 | /** |
| 81 | * Restores `snapshot` if the draft still equals `merged`; otherwise removes only |
| 82 | * what the merge added, keeping later edits. |
| 83 | */ |
| 84 | readonly undoMerge: ( |
| 85 | draftKey: string, |
| 86 | snapshot: ComposerDraft, |
| 87 | merged: ComposerDraft, |
| 88 | ) => Promise<void>; |
| 89 | readonly mergeIntoDraft: ( |
| 90 | draftKey: string, |
| 91 | content: { |
| 92 | readonly text: string; |
| 93 | readonly attachments: ReadonlyArray<DraftComposerAttachment>; |
| 94 | readonly sourceShareId: string; |
| 95 | }, |
| 96 | ) => Promise<{ readonly skippedAttachmentCount: number }>; |
| 97 | readonly selectAttachments: ( |
| 98 | share: IncomingShareDraft, |
| 99 | environmentId: string, |
| 100 | ) => ReturnType<typeof selectIncomingShareAttachmentsForServer>; |
| 101 | /** Sweeps files no draft retained; the sweep re-checks ownership. */ |
| 102 | readonly releaseUnusedAttachments: (attachments: ReadonlyArray<DraftComposerAttachment>) => void; |
| 103 | readonly onWarnings: (warnings: ReadonlyArray<string>) => void; |
| 104 | readonly onImportFailure: (target: ShareImportTarget, error: unknown) => void; |
| 105 | /** Reported even after the route left: the undo is still incomplete. */ |
| 106 | readonly onCancelFailure: (target: ShareImportTarget, error: unknown) => void; |
| 107 | /** Leaves the draft route once its import is cancelled. */ |
| 108 | readonly leave: (target: ShareImportTarget) => void; |
| 109 | } |
| 110 | |
| 111 | interface Entry { |
| 112 | readonly target: ShareImportTarget; |
| 113 | phase: ShareImportPhase; |
| 114 | readonly controller: AbortController; |
| 115 | /** Set when another draft of the same route took over before this import finished. */ |
| 116 | superseded: boolean; |
| 117 | /** Set when the route left while a failed import still waits for retry or cancel. */ |
| 118 | detached: boolean; |
| 119 | run: Promise<void>; |
| 120 | /** The draft before the first attempt merged into it; cancel restores it. */ |
| 121 | backup: ComposerDraft | null; |
| 122 | /** The draft as the last merge published it; cancel undoes against it. */ |
| 123 | merged: ComposerDraft | null; |
| 124 | reservedFor: IncomingShareDestination | null; |
| 125 | consumed: boolean; |
| 126 | needsRestore: boolean; |
| 127 | readonly listeners: Set<() => void>; |
| 128 | } |
| 129 | |
| 130 | function keyOf(target: ShareImportTarget): string { |
| 131 | return JSON.stringify([ |
| 132 | target.flowKey, |
| 133 | target.routeKey, |
| 134 | target.draftKey, |
| 135 | target.destination.environmentId, |
| 136 | target.destination.projectId, |
| 137 | target.shareId, |
| 138 | ]); |
| 139 | } |
| 140 | |
| 141 | interface ImportedShare { |
| 142 | readonly flowKey: string; |
| 143 | readonly shareId: string; |
| 144 | } |
| 145 | |
| 146 | /** |
| 147 | * Share imports for draft routes. Imports do durable writes, so each is tied to |
| 148 | * its target, not an atom node that can be rebuilt. Reading a target's phase atom |
| 149 | * starts its import at most once; alerts, navigation and notifications all |
| 150 | * follow an await, never run inside the read. |
| 151 | */ |
| 152 | export function makeIncomingShareImports(deps: ShareImportDeps) { |
| 153 | const entries = new Map<string, Entry>(); |
| 154 | // Shares each route already moved into a draft. Sending clears the draft's |
| 155 | // import receipt a frame before the route leaves, so the route needs its |
| 156 | // own record to tell "imported" from "vanished". |
| 157 | const importedAtom = Atom.make<ReadonlyArray<ImportedShare>>([]).pipe( |
| 158 | Atom.keepAlive, |
| 159 | Atom.withLabel("mobile:incoming-share-imported"), |
| 160 | ); |
| 161 | const isImportedAtom = Atom.family((key: string) => |
| 162 | Atom.make((get) => |
| 163 | get(importedAtom).some( |
| 164 | (imported) => JSON.stringify([imported.flowKey, imported.shareId]) === key, |
| 165 | ), |
| 166 | ).pipe(Atom.withLabel("mobile:incoming-share-imported:route")), |
| 167 | ); |
| 168 | // One flow key per running attempt, abandoned ones included: an abandoned |
| 169 | // attempt can still be inside a draft write when the screen's target goes away. |
| 170 | const runningAtom = Atom.make<ReadonlyArray<string>>([]).pipe( |
| 171 | Atom.keepAlive, |
| 172 | Atom.withLabel("mobile:incoming-share-import-running"), |
| 173 | ); |
| 174 | const isRunningAtom = Atom.family((flowKey: string) => |
| 175 | Atom.make((get) => get(runningAtom).includes(flowKey)).pipe( |
| 176 | Atom.withLabel("mobile:incoming-share-import-running:route"), |
| 177 | ), |
| 178 | ); |
| 179 | |
| 180 | function notify(entry: Entry): void { |
| 181 | // Listeners rebuild their node, which re-registers them; iterate a copy. |
| 182 | for (const listener of Array.from(entry.listeners)) listener(); |
| 183 | } |
| 184 | |
| 185 | function advance(entry: Entry, event: ShareImportEvent): void { |
| 186 | const next = transitionShareImport(entry.phase, event); |
| 187 | if (next === entry.phase) return; |
| 188 | entry.phase = next; |
| 189 | notify(entry); |
| 190 | } |
| 191 | |
| 192 | function settle(key: string, entry: Entry): void { |
| 193 | if (entry.detached && entries.get(key) === entry) entries.delete(key); |
| 194 | } |
| 195 | |
| 196 | async function runImport(key: string, entry: Entry): Promise<void> { |
| 197 | const { signal } = entry.controller; |
| 198 | const { shareId, destination, draftKey } = entry.target; |
| 199 | // A phase atom node of a superseded import may still be cached; rebuilding |
| 200 | // it lets a route that switches back start over instead of showing the |
| 201 | // abandoned import's last phase. |
| 202 | const stopped = () => { |
| 203 | if (!signal.aborted) return false; |
| 204 | if (entry.superseded) notify(entry); |
| 205 | return true; |
| 206 | }; |
| 207 | try { |
| 208 | await deps.reserve(shareId, destination); |
| 209 | entry.reservedFor = destination; |
| 210 | // The durable reservation makes an interrupted transfer resume only in |
| 211 | // this project instead of copying into a second project draft. |
| 212 | if (stopped()) return; |
| 213 | advance(entry, "reserved"); |
| 214 | const share = deps.getShare(shareId); |
| 215 | if (!share) throw new Error(m(msg("The shared content is no longer in the inbox."))); |
| 216 | const selected = deps.selectAttachments(share, destination.environmentId); |
| 217 | if (selected.status === "pending") { |
| 218 | throw new Error(m(msg("Server attachment support is still loading."))); |
| 219 | } |
| 220 | entry.needsRestore = true; |
| 221 | let skippedAttachmentCount: number; |
| 222 | try { |
| 223 | ({ skippedAttachmentCount } = await deps.mergeIntoDraft(draftKey, { |
| 224 | text: share.text, |
| 225 | attachments: selected.attachments, |
| 226 | sourceShareId: shareId, |
| 227 | })); |
| 228 | } finally { |
| 229 | // The merge publishes before it persists, so read it back even when |
| 230 | // persisting rejects. |
| 231 | entry.merged = deps.readDraft(draftKey); |
| 232 | } |
| 233 | if (stopped()) return; |
| 234 | advance(entry, "attached"); |
| 235 | await deps.consume(shareId); |
| 236 | entry.consumed = true; |
| 237 | // The consumed inbox draft was the last owner of files that never made |
| 238 | // it into the composer draft (unsupported server, oversize, limit |
| 239 | // skips). Release them even when the route left meanwhile. |
| 240 | const retainedIds = new Set( |
| 241 | deps.readDraft(draftKey).attachments.map((attachment) => attachment.id), |
| 242 | ); |
| 243 | deps.releaseUnusedAttachments( |
| 244 | share.attachments.filter((attachment) => !retainedIds.has(attachment.id)), |
| 245 | ); |
| 246 | deps.registry.set(importedAtom, [ |
| 247 | ...deps.registry.get(importedAtom), |
| 248 | { flowKey: entry.target.flowKey, shareId }, |
| 249 | ]); |
| 250 | advance(entry, "consumed"); |
| 251 | entry.backup = null; |
| 252 | settle(key, entry); |
| 253 | if (stopped()) return; |
| 254 | const warnings = [...share.warnings, ...selected.warnings]; |
| 255 | if (skippedAttachmentCount > 0) { |
| 256 | warnings.push( |
| 257 | m( |
| 258 | msg( |
| 259 | "{count, plural, one {{count} shared file was skipped because this draft reached the attachment limit.} other {{count} shared files were skipped because this draft reached the attachment limit.}}", |
| 260 | { count: skippedAttachmentCount }, |
| 261 | ), |
| 262 | ), |
| 263 | ); |
| 264 | } |
| 265 | if (warnings.length > 0) deps.onWarnings(warnings); |
| 266 | } catch (error) { |
| 267 | if (stopped()) return; |
| 268 | advance(entry, "failed"); |
| 269 | deps.onImportFailure(entry.target, error); |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | function begin(key: string, entry: Entry): void { |
| 274 | entry.backup ??= deps.readDraft(entry.target.draftKey); |
| 275 | advance(entry, "start"); |
| 276 | const { flowKey } = entry.target; |
| 277 | deps.registry.set(runningAtom, [...deps.registry.get(runningAtom), flowKey]); |
| 278 | entry.run = runImport(key, entry).finally(() => { |
| 279 | const running = [...deps.registry.get(runningAtom)]; |
| 280 | running.splice(running.indexOf(flowKey), 1); |
| 281 | deps.registry.set(runningAtom, running); |
| 282 | }); |
| 283 | } |
| 284 | |
| 285 | function abandon(key: string, entry: Entry): void { |
| 286 | entry.controller.abort(); |
| 287 | entries.delete(key); |
| 288 | } |
| 289 | |
| 290 | function start(target: ShareImportTarget): Entry { |
| 291 | const key = keyOf(target); |
| 292 | const existing = entries.get(key); |
| 293 | if (existing) return existing; |
| 294 | // A route imports into one draft at a time; a superseded import stops at |
| 295 | // its next step and no longer reports failures. |
| 296 | for (const [otherKey, other] of entries) { |
| 297 | if (other.target.flowKey === target.flowKey && isShareImportInFlight(other.phase)) { |
| 298 | other.superseded = true; |
| 299 | abandon(otherKey, other); |
| 300 | } |
| 301 | } |
| 302 | const entry: Entry = { |
| 303 | target, |
| 304 | phase: "idle", |
| 305 | controller: new AbortController(), |
| 306 | superseded: false, |
| 307 | detached: false, |
| 308 | run: Promise.resolve(), |
| 309 | backup: null, |
| 310 | merged: null, |
| 311 | reservedFor: null, |
| 312 | consumed: false, |
| 313 | needsRestore: false, |
| 314 | listeners: new Set(), |
| 315 | }; |
| 316 | entries.set(key, entry); |
| 317 | begin(key, entry); |
| 318 | return entry; |
| 319 | } |
| 320 | |
| 321 | async function cancel(target: ShareImportTarget): Promise<void> { |
| 322 | const key = keyOf(target); |
| 323 | const entry = entries.get(key); |
| 324 | if (!entry || entry.phase !== "failed") return; |
| 325 | const { draftKey, shareId } = entry.target; |
| 326 | advance(entry, "cancel"); |
| 327 | // Cancelling finishes even if the route leaves meanwhile: it only undoes |
| 328 | // durable writes this import made. |
| 329 | try { |
| 330 | if (entry.needsRestore && entry.backup) { |
| 331 | // The draft can change while a failed import waits for an answer, by the |
| 332 | // user or an upload finishing, and a retried undo runs after its own |
| 333 | // publish. Undoing against the merged draft keeps those changes. |
| 334 | const merged = entry.merged ?? entry.backup; |
| 335 | await deps.undoMerge(draftKey, entry.backup, merged); |
| 336 | entry.needsRestore = false; |
| 337 | // Sweep the share's merged-in files only once the inbox entry was |
| 338 | // consumed: before that, the inbox still owns them for a later import. |
| 339 | // The sweep skips files a draft still holds. |
| 340 | if (entry.consumed) deps.releaseUnusedAttachments(merged.attachments); |
| 341 | } |
| 342 | if (entry.reservedFor) { |
| 343 | await deps.release(shareId, entry.reservedFor); |
| 344 | entry.reservedFor = null; |
| 345 | } |
| 346 | advance(entry, "cancelled"); |
| 347 | if (entry.detached) settle(key, entry); |
| 348 | else deps.leave(entry.target); |
| 349 | } catch (error) { |
| 350 | advance(entry, "cancelFailed"); |
| 351 | deps.onCancelFailure(entry.target, error); |
| 352 | } |
| 353 | } |
| 354 | |
| 355 | return { |
| 356 | phaseAtom: Atom.family((target: ShareImportTarget) => |
| 357 | Atom.make((get): ShareImportPhase => { |
| 358 | const entry = start(target); |
| 359 | const rebuild = () => get.refreshSelf(); |
| 360 | entry.listeners.add(rebuild); |
| 361 | get.addFinalizer(() => entry.listeners.delete(rebuild)); |
| 362 | return entry.phase; |
| 363 | }).pipe(Atom.withLabel("mobile:incoming-share-import")), |
| 364 | ), |
| 365 | /** |
| 366 | * Whether an import for this route is still running, including one whose |
| 367 | * target the screen no longer renders. |
| 368 | */ |
| 369 | inFlightAtom: isRunningAtom, |
| 370 | /** Resolves once the target's current attempt stops. */ |
| 371 | settled(target: ShareImportTarget): Promise<void> { |
| 372 | return entries.get(keyOf(target))?.run ?? Promise.resolve(); |
| 373 | }, |
| 374 | /** Whether this route already moved the share into one of its drafts. */ |
| 375 | importedAtom(flowKey: string, shareId: string) { |
| 376 | return isImportedAtom(JSON.stringify([flowKey, shareId])); |
| 377 | }, |
| 378 | retry(target: ShareImportTarget): void { |
| 379 | const key = keyOf(target); |
| 380 | const entry = entries.get(key); |
| 381 | if (!entry || entry.phase !== "failed") return; |
| 382 | begin(key, entry); |
| 383 | }, |
| 384 | cancel, |
| 385 | /** |
| 386 | * Abandons the imports of draft routes that are no longer on the stack. |
| 387 | * A failed import keeps its retry and cancel until the user answers. |
| 388 | * Resolves once the abandoned imports have stopped. |
| 389 | */ |
| 390 | prune(liveFlowKeys: ReadonlySet<string>): Promise<void> { |
| 391 | const stopping: Array<Promise<void>> = []; |
| 392 | for (const [key, entry] of entries) { |
| 393 | if (liveFlowKeys.has(entry.target.flowKey)) continue; |
| 394 | if (entry.phase === "failed" || entry.phase === "cancelling") { |
| 395 | entry.detached = true; |
| 396 | } else { |
| 397 | abandon(key, entry); |
| 398 | stopping.push(entry.run); |
| 399 | } |
| 400 | } |
| 401 | const imported = deps.registry.get(importedAtom); |
| 402 | const kept = imported.filter((share) => liveFlowKeys.has(share.flowKey)); |
| 403 | if (kept.length !== imported.length) deps.registry.set(importedAtom, kept); |
| 404 | return Promise.all(stopping).then(() => undefined); |
| 405 | }, |
| 406 | }; |
| 407 | } |
| 408 | |
| 409 | export const idleShareImportPhaseAtom = Atom.make<ShareImportPhase>("idle").pipe( |
| 410 | Atom.withLabel("mobile:incoming-share-import:idle"), |
| 411 | ); |
| 412 | |
| 413 | export const idleShareFlagAtom = Atom.make(false).pipe( |
| 414 | Atom.withLabel("mobile:incoming-share-flag:idle"), |
| 415 | ); |