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

main
ts 521 lines 17.1 KB
Raw
1 import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
2 import * as Updates from "expo-updates";
3 // Metro namespace imports evaluate unrelated React Native getters, including unavailable native modules.
4 import { AppState } from "react-native";
5 import { msg } from "gt-react-native";
6
7 import {
8 type AtomCommandResult,
9 isAtomCommandInterrupted,
10 reportAtomCommandResult,
11 settlePromise,
12 squashAtomCommandFailure,
13 } from "@t3tools/client-runtime/state/runtime";
14
15 import { m } from "../../i18n/messages";
16
17 export type AppUpdateCheckState =
18 | "idle"
19 | "checking"
20 | "downloading"
21 | "ready"
22 | "restarting"
23 | "current";
24
25 export interface AppUpdateClient {
26 readonly isEnabled: boolean;
27 readonly checkForUpdateAsync: () => Promise<{
28 readonly isAvailable: boolean;
29 readonly isRollBackToEmbedded: boolean;
30 }>;
31 readonly fetchUpdateAsync: () => Promise<{
32 readonly isNew: boolean;
33 readonly isRollBackToEmbedded: boolean;
34 }>;
35 readonly reloadAsync: () => Promise<void>;
36 }
37
38 export interface AppUpdateEnvironment {
39 readonly confirmInstallNow: () => Promise<boolean>;
40 readonly flushPendingWrites: () => Promise<void>;
41 /** Re-check background state after flushing; exclude app-initiated handoffs such as image pickers. */
42 readonly isSafeToRestartInBackground: () => Promise<boolean>;
43 /** includeCurrent covers module-load backgrounding; omit after failure to prevent tight same-session retries. */
44 readonly onNextBackground: (apply: () => void, includeCurrent: boolean) => void;
45 readonly onForegroundStay: (apply: () => void) => void;
46 }
47
48 export interface AppUpdateDeferral {
49 pendingInstall: boolean;
50 installInProgress: boolean;
51 }
52
53 export function createAppUpdateDeferral(): AppUpdateDeferral {
54 return { pendingInstall: false, installInProgress: false };
55 }
56
57 const appUpdateDeferral = createAppUpdateDeferral();
58
59 interface AppUpdateCheckOptions {
60 readonly applyMode?: "background" | "immediate";
61 readonly client?: AppUpdateClient;
62 readonly deferral?: AppUpdateDeferral;
63 readonly environment?: AppUpdateEnvironment;
64 readonly onFailure?: (message: string) => void;
65 readonly onStateChange?: (state: AppUpdateCheckState) => void;
66 }
67
68 interface AppUpdateCheckProgress {
69 failure: string | undefined;
70 state: AppUpdateCheckState | undefined;
71 }
72
73 interface AppUpdateCheckInFlight {
74 readonly failureListeners: Set<NonNullable<AppUpdateCheckOptions["onFailure"]>>;
75 readonly progress: AppUpdateCheckProgress;
76 readonly promise: Promise<void>;
77 readonly stateListeners: Set<NonNullable<AppUpdateCheckOptions["onStateChange"]>>;
78 }
79
80 interface Deferred {
81 readonly promise: Promise<void>;
82 readonly reject: (cause: unknown) => void;
83 readonly resolve: () => void;
84 }
85
86 const HIDDEN_UPDATE_TAP_COUNT = 5;
87 const UPDATE_CHECK_UNAVAILABLE_ERROR_CODES = new Set([
88 "ERR_NOT_AVAILABLE_IN_DEV_CLIENT",
89 "ERR_UPDATES_DISABLED",
90 ]);
91 let appUpdateCheckInFlight: AppUpdateCheckInFlight | undefined;
92
93 /** Expo's development launcher reports updates as enabled even though its OTA APIs reject. */
94 export function isAppUpdateCheckAvailable(client: Pick<AppUpdateClient, "isEnabled"> = Updates) {
95 return client.isEnabled && !(typeof __DEV__ !== "undefined" && __DEV__);
96 }
97
98 export function registerHiddenUpdateTap(count: number): {
99 readonly nextCount: number;
100 readonly shouldCheck: boolean;
101 } {
102 const nextCount = count + 1;
103 if (nextCount >= HIDDEN_UPDATE_TAP_COUNT) {
104 return {
105 nextCount: 0,
106 shouldCheck: true,
107 };
108 }
109 return {
110 nextCount,
111 shouldCheck: false,
112 };
113 }
114
115 export async function runAppUpdateCheck(options: AppUpdateCheckOptions = {}): Promise<void> {
116 const client = options.client ?? Updates;
117 if (!isAppUpdateCheckAvailable(client)) return;
118
119 if (appUpdateCheckInFlight) {
120 await observeAppUpdateCheck(appUpdateCheckInFlight, options);
121 if (options.applyMode === "immediate") {
122 const deferral = options.deferral ?? appUpdateDeferral;
123 if (deferral.pendingInstall) {
124 const environment = options.environment ?? defaultAppUpdateEnvironment;
125 await installPendingAppUpdate(client, environment, deferral, options);
126 }
127 }
128 return;
129 }
130
131 const progress: AppUpdateCheckProgress = {
132 failure: undefined,
133 state: undefined,
134 };
135 const failureListeners = new Set<NonNullable<AppUpdateCheckOptions["onFailure"]>>();
136 const stateListeners = new Set<NonNullable<AppUpdateCheckOptions["onStateChange"]>>();
137 if (options.onFailure) failureListeners.add(options.onFailure);
138 if (options.onStateChange) stateListeners.add(options.onStateChange);
139
140 const deferred = createDeferred();
141 const inFlight: AppUpdateCheckInFlight = {
142 failureListeners,
143 progress,
144 promise: deferred.promise,
145 stateListeners,
146 };
147 // Publish the operation before any state listener can synchronously re-enter.
148 appUpdateCheckInFlight = inFlight;
149
150 const execution = performAppUpdateCheck(client, {
151 applyMode: options.applyMode,
152 deferral: options.deferral,
153 environment: options.environment,
154 onFailure: (message) => {
155 progress.failure = message;
156 notifyListeners(failureListeners, message);
157 },
158 onStateChange: (state) => {
159 progress.state = state;
160 notifyListeners(stateListeners, state);
161 },
162 });
163 void execution.then(deferred.resolve, deferred.reject);
164
165 try {
166 await deferred.promise;
167 } finally {
168 if (appUpdateCheckInFlight === inFlight) {
169 appUpdateCheckInFlight = undefined;
170 }
171 }
172 }
173
174 function createDeferred(): Deferred {
175 let reject!: Deferred["reject"];
176 let resolve!: Deferred["resolve"];
177 const promise = new Promise<void>((resolvePromise, rejectPromise) => {
178 resolve = () => resolvePromise();
179 reject = rejectPromise;
180 });
181 return { promise, reject, resolve };
182 }
183
184 function notifyListeners<A>(listeners: ReadonlySet<(value: A) => void>, value: A): void {
185 // Snapshot listeners so reentrant subscribers receive only observeAppUpdateCheck's explicit replay.
186 const snapshot = Array.from(listeners);
187 for (const listener of snapshot) listener(value);
188 }
189
190 async function observeAppUpdateCheck(
191 inFlight: AppUpdateCheckInFlight,
192 options: AppUpdateCheckOptions,
193 ): Promise<void> {
194 const onFailure = options.onFailure;
195 const onStateChange = options.onStateChange;
196
197 if (onFailure) {
198 inFlight.failureListeners.add(onFailure);
199 if (inFlight.progress.failure) onFailure(inFlight.progress.failure);
200 }
201 if (onStateChange) {
202 inFlight.stateListeners.add(onStateChange);
203 if (inFlight.progress.state) onStateChange(inFlight.progress.state);
204 }
205
206 try {
207 await inFlight.promise;
208 } finally {
209 if (onFailure) inFlight.failureListeners.delete(onFailure);
210 if (onStateChange) inFlight.stateListeners.delete(onStateChange);
211 }
212 }
213
214 async function performAppUpdateCheck(
215 client: AppUpdateClient,
216 options: AppUpdateCheckOptions,
217 ): Promise<void> {
218 const setState = options.onStateChange ?? (() => {});
219 const environment = options.environment ?? defaultAppUpdateEnvironment;
220 const deferral = options.deferral ?? appUpdateDeferral;
221
222 if (options.applyMode === "immediate" && deferral.pendingInstall) {
223 await installPendingAppUpdate(client, environment, deferral, options);
224 return;
225 }
226
227 setState("checking");
228 const check = await settlePromise(() => client.checkForUpdateAsync());
229 if (check._tag === "Failure") {
230 reportUpdateFailure(check, m(msg("Could not check for updates.")), options.onFailure);
231 setState("idle");
232 return;
233 }
234 // Rollback directives report isAvailable: false and isRollBackToEmbedded: true; still drop the running OTA.
235 if (!check.value.isAvailable && !check.value.isRollBackToEmbedded) {
236 setState("current");
237 return;
238 }
239
240 setState("downloading");
241 const fetched = await settlePromise(() => client.fetchUpdateAsync());
242 if (fetched._tag === "Failure") {
243 reportUpdateFailure(fetched, m(msg("Could not download the update.")), options.onFailure);
244 setState("idle");
245 return;
246 }
247 // isNew is always false for a rollback, so it cannot be the sole gate.
248 if (!fetched.value.isNew && !fetched.value.isRollBackToEmbedded) {
249 setState("current");
250 return;
251 }
252
253 if (options.applyMode === "immediate" || fetched.value.isRollBackToEmbedded) {
254 const outcome = await installAppUpdate(
255 client,
256 environment,
257 deferral,
258 options,
259 options.applyMode === "immediate",
260 );
261 if (outcome === "flush-failed") {
262 setState("ready");
263 armDeferredAppUpdateInstall(client, environment, deferral);
264 }
265 return;
266 }
267
268 setState("ready");
269 armDeferredAppUpdateInstall(client, environment, deferral);
270 }
271
272 type AppUpdateInstallOutcome = "installed" | "flush-failed" | "restart-failed";
273
274 /** Flush persistence and wait for backgrounding before restarting mounted native surfaces. */
275 async function installAppUpdate(
276 client: AppUpdateClient,
277 environment: AppUpdateEnvironment,
278 deferral: AppUpdateDeferral,
279 options: AppUpdateCheckOptions,
280 userRequested: boolean,
281 ): Promise<AppUpdateInstallOutcome> {
282 if (deferral.installInProgress) return "installed";
283 deferral.installInProgress = true;
284 const setState = options.onStateChange ?? (() => {});
285 setState("restarting");
286 const flushed = await settlePromise(() => environment.flushPendingWrites());
287 if (flushed._tag === "Failure") {
288 reportUpdateFailure(flushed, m(msg("Could not save pending state.")), undefined);
289 if (!userRequested) {
290 deferral.installInProgress = false;
291 return "flush-failed";
292 }
293 }
294 const reloaded = await settlePromise(() => client.reloadAsync());
295 if (reloaded._tag === "Failure") {
296 reportUpdateFailure(
297 reloaded,
298 m(msg("Downloaded, but could not restart the app.")),
299 options.onFailure,
300 );
301 setState("idle");
302 deferral.installInProgress = false;
303 return "restart-failed";
304 }
305 return "installed";
306 }
307
308 async function installPendingAppUpdate(
309 client: AppUpdateClient,
310 environment: AppUpdateEnvironment,
311 deferral: AppUpdateDeferral,
312 options: AppUpdateCheckOptions,
313 ): Promise<void> {
314 const outcome = await installAppUpdate(client, environment, deferral, options, true);
315 if (outcome === "restart-failed") {
316 deferral.pendingInstall = false;
317 }
318 }
319
320 function armDeferredAppUpdateInstall(
321 client: AppUpdateClient,
322 environment: AppUpdateEnvironment,
323 deferral: AppUpdateDeferral,
324 ): void {
325 if (deferral.pendingInstall) return;
326 deferral.pendingInstall = true;
327 scheduleDeferredAppUpdateInstall(client, environment, deferral, true);
328 environment.onForegroundStay(() => {
329 void promptDeferredAppUpdateInstall(client, environment, deferral);
330 });
331 }
332
333 async function promptDeferredAppUpdateInstall(
334 client: AppUpdateClient,
335 environment: AppUpdateEnvironment,
336 deferral: AppUpdateDeferral,
337 ): Promise<void> {
338 if (!deferral.pendingInstall || deferral.installInProgress) return;
339 const installNow = await settlePromise(() => environment.confirmInstallNow());
340 if (installNow._tag !== "Success" || !installNow.value) return;
341 // Backgrounding may already have started deferred restart while the alert was open; ignore stale acceptance.
342 if (!deferral.pendingInstall || deferral.installInProgress) return;
343 await installPendingAppUpdate(client, environment, deferral, {});
344 }
345
346 function scheduleDeferredAppUpdateInstall(
347 client: AppUpdateClient,
348 environment: AppUpdateEnvironment,
349 deferral: AppUpdateDeferral,
350 includeCurrent: boolean,
351 ): void {
352 environment.onNextBackground(() => {
353 void applyDeferredAppUpdateInstall(client, environment, deferral);
354 }, includeCurrent);
355 }
356
357 async function applyDeferredAppUpdateInstall(
358 client: AppUpdateClient,
359 environment: AppUpdateEnvironment,
360 deferral: AppUpdateDeferral,
361 ): Promise<void> {
362 if (!deferral.pendingInstall || deferral.installInProgress) return;
363 deferral.installInProgress = true;
364 const flushed = await settlePromise(() => environment.flushPendingWrites());
365 const safe = await settlePromise(() => environment.isSafeToRestartInBackground());
366 if (flushed._tag === "Failure" || safe._tag !== "Success" || !safe.value) {
367 if (flushed._tag === "Failure") {
368 reportUpdateFailure(flushed, m(msg("Could not save pending state.")), undefined);
369 }
370 deferral.installInProgress = false;
371 // Wait for a fresh background transition after failure to avoid same-session retry loops.
372 scheduleDeferredAppUpdateInstall(client, environment, deferral, false);
373 return;
374 }
375 const reloaded = await settlePromise(() => client.reloadAsync());
376 if (reloaded._tag === "Failure") {
377 reportUpdateFailure(reloaded, m(msg("Downloaded, but could not restart the app.")), undefined);
378 deferral.installInProgress = false;
379 deferral.pendingInstall = false;
380 }
381 }
382
383 async function defaultConfirmInstallNow(): Promise<boolean> {
384 const Dialog = await import("../../components/ui/Dialog");
385 return new Promise<boolean>((resolve) => {
386 Dialog.alert(
387 m(msg("Update ready")),
388 m(
389 msg(
390 "A new version has been downloaded and installs automatically the next time you leave the app. Install it now instead?",
391 ),
392 ),
393 [
394 { onPress: () => resolve(false), style: "cancel", text: m(msg("Later")) },
395 { onPress: () => resolve(true), text: m(msg("Install Now")) },
396 ],
397 { cancelable: true, onDismiss: () => resolve(false) },
398 );
399 });
400 }
401
402 async function defaultFlushPendingWrites(): Promise<void> {
403 const results = await Promise.allSettled([
404 import("../../state/use-composer-drafts").then((drafts) => drafts.flushComposerDrafts()),
405 import("../../state/thread-outbox").then((outbox) => outbox.flushThreadOutbox()),
406 ]);
407 const failed = results.find(
408 (result): result is PromiseRejectedResult => result.status === "rejected",
409 );
410 if (failed) throw failed.reason;
411 }
412
413 async function defaultIsSafeToRestartInBackground(): Promise<boolean> {
414 const { isForegroundHandoffActive } = await import("../../lib/foreground-handoff");
415 if (isForegroundHandoffActive()) return false;
416 return AppState.currentState === "background";
417 }
418
419 function defaultOnNextBackground(apply: () => void, includeCurrent: boolean): void {
420 const subscription = AppState.addEventListener("change", (state) => {
421 if (state !== "background") return;
422 subscription.remove();
423 apply();
424 });
425 if (includeCurrent && AppState.currentState === "background") {
426 subscription.remove();
427 apply();
428 }
429 }
430
431 const DEFERRED_INSTALL_PROMPT_AFTER_MS = 30 * 60 * 1000;
432
433 /** iOS inactive blips, including the app switcher, leave this timer running. */
434 function defaultOnForegroundStay(apply: () => void): void {
435 let timer: ReturnType<typeof setTimeout> | undefined;
436 const arm = () => {
437 timer ??= setTimeout(() => {
438 subscription.remove();
439 apply();
440 }, DEFERRED_INSTALL_PROMPT_AFTER_MS);
441 };
442 const disarm = () => {
443 if (timer === undefined) return;
444 clearTimeout(timer);
445 timer = undefined;
446 };
447 const subscription = AppState.addEventListener("change", (state) => {
448 if (state === "active") arm();
449 else if (state === "background") disarm();
450 });
451 if (AppState.currentState === "active") arm();
452 }
453
454 const defaultAppUpdateEnvironment: AppUpdateEnvironment = {
455 confirmInstallNow: defaultConfirmInstallNow,
456 flushPendingWrites: defaultFlushPendingWrites,
457 isSafeToRestartInBackground: defaultIsSafeToRestartInBackground,
458 onNextBackground: defaultOnNextBackground,
459 onForegroundStay: defaultOnForegroundStay,
460 };
461
462 function reportUpdateFailure(
463 result: AtomCommandResult<unknown, unknown>,
464 fallback: string,
465 onFailure: AppUpdateCheckOptions["onFailure"],
466 ): void {
467 if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
468 const error = squashAtomCommandFailure(result);
469 if (isAppUpdateUnavailableError(error)) return;
470
471 reportAtomCommandResult(result, { label: "app update check" });
472 onFailure?.(error instanceof Error ? (errorDisplayMessage(error, m) ?? error.message) : fallback);
473 }
474
475 function isAppUpdateUnavailableError(error: unknown): boolean {
476 if (typeof error !== "object" || error === null || !("code" in error)) return false;
477 const code = error.code;
478 return typeof code === "string" && UPDATE_CHECK_UNAVAILABLE_ERROR_CODES.has(code);
479 }
480
481 const FOREGROUND_APP_UPDATE_RECHECK_AFTER_MS = 15 * 60 * 1000;
482
483 function shouldRecheckAppUpdateOnForeground(
484 backgroundedAtMs: number | null,
485 activeAtMs: number,
486 pendingInstall: boolean,
487 ): boolean {
488 if (pendingInstall) return false;
489 return (
490 backgroundedAtMs !== null &&
491 activeAtMs - backgroundedAtMs >= FOREGROUND_APP_UPDATE_RECHECK_AFTER_MS
492 );
493 }
494
495 /**
496 * App-lifetime update checks: one at launch, then again when the app returns
497 * from a long stay in the background.
498 */
499 export function installAppUpdateChecks(
500 client: AppUpdateClient = Updates,
501 deferral: AppUpdateDeferral = appUpdateDeferral,
502 ): () => void {
503 if (!isAppUpdateCheckAvailable(client)) return () => undefined;
504 void runAppUpdateCheck({ client, deferral });
505 let backgroundedAtMs: number | null = null;
506 const subscription = AppState.addEventListener("change", (state) => {
507 if (state === "background") {
508 backgroundedAtMs = Date.now();
509 return;
510 }
511 if (state !== "active") return;
512 const shouldCheck = shouldRecheckAppUpdateOnForeground(
513 backgroundedAtMs,
514 Date.now(),
515 deferral.pendingInstall,
516 );
517 backgroundedAtMs = null;
518 if (shouldCheck) void runAppUpdateCheck({ client, deferral });
519 });
520 return () => subscription.remove();
521 }