fix(mobile): prevent OTA update restart crashes (#6324)
Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
b3b4b57794
commit
21a3669cee
13 files changed
+959
-34
No files matched your search
@@ -11,7 +11,7 @@ import { useSavedRemoteConnections } from "../../state/use-remote-environment-re
|
||||
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
|
||||
import { WorkspaceEmptyDetail } from "../layout/WorkspaceEmptyDetail";
|
||||
import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
|
||||
import { checkForAppUpdateOnLaunch } from "../updates/app-updates";
|
||||
import { checkForAppUpdateOnLaunch, startAppUpdateForegroundRecheck } from "../updates/app-updates";
|
||||
import { AndroidHomeFabLayout } from "./AndroidHomeFab";
|
||||
import { HomeScreen } from "./HomeScreen";
|
||||
import { HomeHeader } from "./HomeHeader";
|
||||
@@ -34,6 +34,7 @@ export function HomeRouteScreen() {
|
||||
|
||||
useEffect(() => {
|
||||
void checkForAppUpdateOnLaunch();
|
||||
startAppUpdateForegroundRecheck();
|
||||
}, []);
|
||||
|
||||
const {
|
||||
|
||||
@@ -608,7 +608,10 @@ function AppSettingsSection() {
|
||||
if (updateInFlight.current) return;
|
||||
updateInFlight.current = true;
|
||||
try {
|
||||
// The user asked for this restart by tapping the version row, so it may
|
||||
// apply immediately instead of prompting.
|
||||
await runAppUpdateCheck({
|
||||
applyMode: "immediate",
|
||||
onFailure: (message) => Alert.alert("Update failed", message),
|
||||
onStateChange: setUpdateState,
|
||||
});
|
||||
@@ -631,11 +634,15 @@ function AppSettingsSection() {
|
||||
? "Checking…"
|
||||
: updateState === "downloading"
|
||||
? "Downloading…"
|
||||
: updateState === "restarting"
|
||||
? "Restarting…"
|
||||
: updateState === "current"
|
||||
? "Up to date"
|
||||
: null;
|
||||
: // "ready" appears only when this check joined an in-flight background-mode
|
||||
// check; that download installs at the next backgrounding.
|
||||
updateState === "ready"
|
||||
? "Update ready"
|
||||
: updateState === "restarting"
|
||||
? "Restarting…"
|
||||
: updateState === "current"
|
||||
? "Up to date"
|
||||
: null;
|
||||
|
||||
const versionRow = (
|
||||
<View className="flex-row items-center gap-4 p-4">
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
createAppUpdateDeferral,
|
||||
createAppUpdateLaunchCheck,
|
||||
FOREGROUND_APP_UPDATE_RECHECK_AFTER_MS,
|
||||
registerHiddenUpdateTap,
|
||||
runAppUpdateCheck,
|
||||
shouldRecheckAppUpdateOnForeground,
|
||||
type AppUpdateCheckState,
|
||||
type AppUpdateClient,
|
||||
type AppUpdateEnvironment,
|
||||
} from "./app-updates";
|
||||
|
||||
vi.mock("expo-updates", () => ({
|
||||
@@ -31,6 +35,41 @@ function makeUpdateClient(overrides: Partial<AppUpdateClient> = {}): AppUpdateCl
|
||||
};
|
||||
}
|
||||
|
||||
function makeUpdateEnvironment(overrides: Partial<AppUpdateEnvironment> = {}): {
|
||||
readonly backgroundCallbacks: Array<() => void>;
|
||||
readonly environment: AppUpdateEnvironment;
|
||||
readonly foregroundStayCallbacks: Array<() => void>;
|
||||
} {
|
||||
const backgroundCallbacks: Array<() => void> = [];
|
||||
const foregroundStayCallbacks: Array<() => void> = [];
|
||||
return {
|
||||
backgroundCallbacks,
|
||||
foregroundStayCallbacks,
|
||||
environment: {
|
||||
confirmInstallNow: vi.fn(async () => true),
|
||||
flushPendingWrites: vi.fn(async () => {}),
|
||||
isSafeToRestartInBackground: vi.fn(async () => true),
|
||||
onNextBackground: vi.fn((apply: () => void, _includeCurrent: boolean) => {
|
||||
backgroundCallbacks.push(apply);
|
||||
}),
|
||||
onForegroundStay: vi.fn((apply: () => void) => {
|
||||
foregroundStayCallbacks.push(apply);
|
||||
}),
|
||||
...overrides,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function makeAvailableUpdateClient(overrides: Partial<AppUpdateClient> = {}): AppUpdateClient {
|
||||
return makeUpdateClient({
|
||||
checkForUpdateAsync: vi.fn(async () => ({
|
||||
isAvailable: true,
|
||||
isRollBackToEmbedded: false,
|
||||
})),
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
describe("runAppUpdateCheck", () => {
|
||||
it("does nothing while running from the Metro development server", async () => {
|
||||
vi.stubGlobal("__DEV__", true);
|
||||
@@ -45,23 +84,313 @@ describe("runAppUpdateCheck", () => {
|
||||
expect(client.checkForUpdateAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("downloads and restarts when a new update is available", async () => {
|
||||
const client = makeUpdateClient({
|
||||
checkForUpdateAsync: vi.fn(async () => ({
|
||||
isAvailable: true,
|
||||
isRollBackToEmbedded: false,
|
||||
})),
|
||||
});
|
||||
it("downloads silently and installs at the next backgrounding", async () => {
|
||||
const client = makeAvailableUpdateClient();
|
||||
const { backgroundCallbacks, environment } = makeUpdateEnvironment();
|
||||
const deferral = createAppUpdateDeferral();
|
||||
const states: AppUpdateCheckState[] = [];
|
||||
|
||||
await runAppUpdateCheck({ client, onStateChange: (state) => states.push(state) });
|
||||
await runAppUpdateCheck({
|
||||
client,
|
||||
deferral,
|
||||
environment,
|
||||
onStateChange: (state) => states.push(state),
|
||||
});
|
||||
|
||||
expect(client.checkForUpdateAsync).toHaveBeenCalledOnce();
|
||||
expect(client.fetchUpdateAsync).toHaveBeenCalledOnce();
|
||||
expect(environment.confirmInstallNow).not.toHaveBeenCalled();
|
||||
expect(client.reloadAsync).not.toHaveBeenCalled();
|
||||
expect(states).toEqual(["checking", "downloading", "ready"]);
|
||||
expect(deferral.pendingInstall).toBe(true);
|
||||
expect(backgroundCallbacks).toHaveLength(1);
|
||||
|
||||
backgroundCallbacks[0]!();
|
||||
await vi.waitFor(() => expect(client.reloadAsync).toHaveBeenCalledOnce());
|
||||
expect(environment.flushPendingWrites).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("flushes pending writes before restarting", async () => {
|
||||
const client = makeAvailableUpdateClient();
|
||||
const { environment } = makeUpdateEnvironment();
|
||||
|
||||
await runAppUpdateCheck({
|
||||
applyMode: "immediate",
|
||||
client,
|
||||
deferral: createAppUpdateDeferral(),
|
||||
environment,
|
||||
});
|
||||
|
||||
const flushOrder = vi.mocked(environment.flushPendingWrites).mock.invocationCallOrder[0]!;
|
||||
const reloadOrder = vi.mocked(client.reloadAsync).mock.invocationCallOrder[0]!;
|
||||
expect(flushOrder).toBeLessThan(reloadOrder);
|
||||
});
|
||||
|
||||
it("prompts once the app has stayed foregrounded with the download waiting", async () => {
|
||||
const client = makeAvailableUpdateClient();
|
||||
const { environment, foregroundStayCallbacks } = makeUpdateEnvironment();
|
||||
const deferral = createAppUpdateDeferral();
|
||||
|
||||
await runAppUpdateCheck({ client, deferral, environment });
|
||||
expect(environment.confirmInstallNow).not.toHaveBeenCalled();
|
||||
expect(foregroundStayCallbacks).toHaveLength(1);
|
||||
|
||||
foregroundStayCallbacks[0]!();
|
||||
await vi.waitFor(() => expect(client.reloadAsync).toHaveBeenCalledOnce());
|
||||
expect(environment.confirmInstallNow).toHaveBeenCalledOnce();
|
||||
expect(environment.flushPendingWrites).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps the background install armed when the foreground prompt is declined", async () => {
|
||||
const client = makeAvailableUpdateClient();
|
||||
const { backgroundCallbacks, environment, foregroundStayCallbacks } = makeUpdateEnvironment({
|
||||
confirmInstallNow: vi.fn(async () => false),
|
||||
});
|
||||
const deferral = createAppUpdateDeferral();
|
||||
|
||||
await runAppUpdateCheck({ client, deferral, environment });
|
||||
|
||||
foregroundStayCallbacks[0]!();
|
||||
await vi.waitFor(() => expect(environment.confirmInstallNow).toHaveBeenCalledOnce());
|
||||
expect(client.reloadAsync).not.toHaveBeenCalled();
|
||||
expect(deferral.pendingInstall).toBe(true);
|
||||
|
||||
backgroundCallbacks[0]!();
|
||||
await vi.waitFor(() => expect(client.reloadAsync).toHaveBeenCalledOnce());
|
||||
});
|
||||
|
||||
it("skips the foreground prompt once the install is no longer pending", async () => {
|
||||
const client = makeAvailableUpdateClient();
|
||||
const { environment, foregroundStayCallbacks } = makeUpdateEnvironment();
|
||||
const deferral = createAppUpdateDeferral();
|
||||
|
||||
await runAppUpdateCheck({ client, deferral, environment });
|
||||
|
||||
// A failed deferred reload resets the deferral before the stay fires.
|
||||
deferral.pendingInstall = false;
|
||||
foregroundStayCallbacks[0]!();
|
||||
|
||||
expect(environment.confirmInstallNow).not.toHaveBeenCalled();
|
||||
expect(client.reloadAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("re-arms instead of restarting when the app is no longer safely backgrounded", async () => {
|
||||
const client = makeAvailableUpdateClient();
|
||||
const safe = vi.fn(async () => false);
|
||||
const { backgroundCallbacks, environment } = makeUpdateEnvironment({
|
||||
isSafeToRestartInBackground: safe,
|
||||
});
|
||||
const deferral = createAppUpdateDeferral();
|
||||
|
||||
await runAppUpdateCheck({ client, deferral, environment });
|
||||
expect(backgroundCallbacks).toHaveLength(1);
|
||||
// Arming may fire for an already-backgrounded app…
|
||||
expect(vi.mocked(environment.onNextBackground).mock.calls[0]![1]).toBe(true);
|
||||
|
||||
backgroundCallbacks[0]!();
|
||||
await vi.waitFor(() => expect(backgroundCallbacks).toHaveLength(2));
|
||||
expect(client.reloadAsync).not.toHaveBeenCalled();
|
||||
expect(deferral.pendingInstall).toBe(true);
|
||||
// …but a re-arm must wait for a fresh transition, or an unsafe attempt
|
||||
// would retry in a tight loop within the same background session.
|
||||
expect(vi.mocked(environment.onNextBackground).mock.calls[1]![1]).toBe(false);
|
||||
|
||||
safe.mockResolvedValue(true);
|
||||
backgroundCallbacks[1]!();
|
||||
await vi.waitFor(() => expect(client.reloadAsync).toHaveBeenCalledOnce());
|
||||
});
|
||||
|
||||
it("resets the deferral when the deferred restart fails", async () => {
|
||||
const reportError = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const client = makeAvailableUpdateClient({
|
||||
reloadAsync: vi.fn(async () => {
|
||||
throw new Error("reload rejected");
|
||||
}),
|
||||
});
|
||||
const { backgroundCallbacks, environment } = makeUpdateEnvironment();
|
||||
const deferral = createAppUpdateDeferral();
|
||||
|
||||
await runAppUpdateCheck({ client, deferral, environment });
|
||||
backgroundCallbacks[0]!();
|
||||
|
||||
await vi.waitFor(() => expect(deferral.pendingInstall).toBe(false));
|
||||
reportError.mockRestore();
|
||||
});
|
||||
|
||||
it("arms the deferred install once across repeated checks", async () => {
|
||||
const client = makeAvailableUpdateClient();
|
||||
const { environment } = makeUpdateEnvironment();
|
||||
const deferral = createAppUpdateDeferral();
|
||||
|
||||
await runAppUpdateCheck({ client, deferral, environment });
|
||||
await runAppUpdateCheck({ client, deferral, environment });
|
||||
|
||||
expect(environment.onNextBackground).toHaveBeenCalledOnce();
|
||||
expect(environment.onForegroundStay).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("restarts into an already-downloaded update when the user asks to install", async () => {
|
||||
const client = makeUpdateClient();
|
||||
const { environment } = makeUpdateEnvironment();
|
||||
const deferral = createAppUpdateDeferral();
|
||||
deferral.pendingInstall = true;
|
||||
|
||||
await runAppUpdateCheck({ applyMode: "immediate", client, deferral, environment });
|
||||
|
||||
expect(client.checkForUpdateAsync).not.toHaveBeenCalled();
|
||||
expect(client.reloadAsync).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("honors an immediate request that joined an in-flight background check", async () => {
|
||||
let resolveCheck!: (result: {
|
||||
readonly isAvailable: boolean;
|
||||
readonly isRollBackToEmbedded: boolean;
|
||||
}) => void;
|
||||
const checkResult = new Promise<{
|
||||
readonly isAvailable: boolean;
|
||||
readonly isRollBackToEmbedded: boolean;
|
||||
}>((resolve) => {
|
||||
resolveCheck = resolve;
|
||||
});
|
||||
const client = makeUpdateClient({
|
||||
checkForUpdateAsync: vi.fn(() => checkResult),
|
||||
});
|
||||
const { environment } = makeUpdateEnvironment();
|
||||
const deferral = createAppUpdateDeferral();
|
||||
|
||||
const backgroundCheck = runAppUpdateCheck({ client, deferral, environment });
|
||||
const manualCheck = runAppUpdateCheck({
|
||||
applyMode: "immediate",
|
||||
client,
|
||||
deferral,
|
||||
environment,
|
||||
});
|
||||
|
||||
resolveCheck({ isAvailable: true, isRollBackToEmbedded: false });
|
||||
await Promise.all([backgroundCheck, manualCheck]);
|
||||
|
||||
// The coalesced background check deferred the download, but the manual
|
||||
// caller explicitly asked to install, so the restart happens anyway.
|
||||
expect(client.checkForUpdateAsync).toHaveBeenCalledOnce();
|
||||
expect(client.reloadAsync).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("runs a single restart when the deferred install races the foreground prompt", async () => {
|
||||
const client = makeAvailableUpdateClient();
|
||||
let releaseFlush!: () => void;
|
||||
const blockedFlush = new Promise<void>((resolve) => {
|
||||
releaseFlush = resolve;
|
||||
});
|
||||
const flushPendingWrites = vi.fn(async (): Promise<void> => {});
|
||||
const { backgroundCallbacks, environment, foregroundStayCallbacks } = makeUpdateEnvironment({
|
||||
flushPendingWrites,
|
||||
});
|
||||
const deferral = createAppUpdateDeferral();
|
||||
|
||||
await runAppUpdateCheck({ client, deferral, environment });
|
||||
flushPendingWrites.mockReturnValue(blockedFlush);
|
||||
|
||||
// The deferred install starts and blocks on its flush; the foreground
|
||||
// prompt firing in that window must not begin a second restart.
|
||||
backgroundCallbacks[0]!();
|
||||
await vi.waitFor(() => expect(flushPendingWrites).toHaveBeenCalledOnce());
|
||||
foregroundStayCallbacks[0]!();
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
expect(environment.confirmInstallNow).not.toHaveBeenCalled();
|
||||
|
||||
releaseFlush();
|
||||
await vi.waitFor(() => expect(client.reloadAsync).toHaveBeenCalledOnce());
|
||||
});
|
||||
|
||||
it("holds the deferred restart and re-arms when the pre-restart flush fails", async () => {
|
||||
const reportError = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const client = makeAvailableUpdateClient();
|
||||
const { backgroundCallbacks, environment } = makeUpdateEnvironment({
|
||||
flushPendingWrites: vi.fn(async () => {
|
||||
throw new Error("disk full");
|
||||
}),
|
||||
});
|
||||
const deferral = createAppUpdateDeferral();
|
||||
|
||||
await runAppUpdateCheck({ client, deferral, environment });
|
||||
backgroundCallbacks[0]!();
|
||||
|
||||
await vi.waitFor(() => expect(backgroundCallbacks).toHaveLength(2));
|
||||
expect(client.reloadAsync).not.toHaveBeenCalled();
|
||||
expect(deferral.pendingInstall).toBe(true);
|
||||
reportError.mockRestore();
|
||||
});
|
||||
|
||||
it("restarts without prompting when the caller asked for an immediate install", async () => {
|
||||
const client = makeAvailableUpdateClient();
|
||||
const { environment } = makeUpdateEnvironment();
|
||||
const states: AppUpdateCheckState[] = [];
|
||||
|
||||
await runAppUpdateCheck({
|
||||
applyMode: "immediate",
|
||||
client,
|
||||
deferral: createAppUpdateDeferral(),
|
||||
environment,
|
||||
onStateChange: (state) => states.push(state),
|
||||
});
|
||||
|
||||
expect(environment.confirmInstallNow).not.toHaveBeenCalled();
|
||||
expect(client.reloadAsync).toHaveBeenCalledOnce();
|
||||
expect(states).toEqual(["checking", "downloading", "restarting"]);
|
||||
});
|
||||
|
||||
it("holds an automatic rollback restart when the flush fails and re-arms it", async () => {
|
||||
const reportError = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const client = makeUpdateClient({
|
||||
checkForUpdateAsync: vi.fn(async () => ({
|
||||
isAvailable: false,
|
||||
isRollBackToEmbedded: true,
|
||||
})),
|
||||
fetchUpdateAsync: vi.fn(async () => ({
|
||||
isNew: false,
|
||||
isRollBackToEmbedded: true,
|
||||
})),
|
||||
});
|
||||
const flushPendingWrites = vi.fn(async (): Promise<void> => {
|
||||
throw new Error("storage unavailable");
|
||||
});
|
||||
const { backgroundCallbacks, environment } = makeUpdateEnvironment({ flushPendingWrites });
|
||||
const deferral = createAppUpdateDeferral();
|
||||
|
||||
await runAppUpdateCheck({ client, deferral, environment });
|
||||
|
||||
// Nobody asked for this restart, so it must not discard the state it
|
||||
// failed to land; the rollback waits armed for the next backgrounding.
|
||||
expect(client.reloadAsync).not.toHaveBeenCalled();
|
||||
expect(deferral.pendingInstall).toBe(true);
|
||||
expect(backgroundCallbacks).toHaveLength(1);
|
||||
|
||||
flushPendingWrites.mockResolvedValue(undefined);
|
||||
backgroundCallbacks[0]!();
|
||||
await vi.waitFor(() => expect(client.reloadAsync).toHaveBeenCalledOnce());
|
||||
reportError.mockRestore();
|
||||
});
|
||||
|
||||
it("still restarts a user-requested install when the flush fails", async () => {
|
||||
const reportError = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const client = makeAvailableUpdateClient();
|
||||
const { environment } = makeUpdateEnvironment({
|
||||
flushPendingWrites: vi.fn(async () => {
|
||||
throw new Error("storage unavailable");
|
||||
}),
|
||||
});
|
||||
|
||||
await runAppUpdateCheck({
|
||||
applyMode: "immediate",
|
||||
client,
|
||||
deferral: createAppUpdateDeferral(),
|
||||
environment,
|
||||
});
|
||||
|
||||
expect(client.reloadAsync).toHaveBeenCalledOnce();
|
||||
reportError.mockRestore();
|
||||
});
|
||||
|
||||
it("restarts into the embedded bundle for a rollback directive", async () => {
|
||||
const client = makeUpdateClient({
|
||||
checkForUpdateAsync: vi.fn(async () => ({
|
||||
@@ -73,10 +402,13 @@ describe("runAppUpdateCheck", () => {
|
||||
isRollBackToEmbedded: true,
|
||||
})),
|
||||
});
|
||||
const { environment } = makeUpdateEnvironment();
|
||||
|
||||
await runAppUpdateCheck({ client });
|
||||
await runAppUpdateCheck({ client, deferral: createAppUpdateDeferral(), environment });
|
||||
|
||||
expect(client.fetchUpdateAsync).toHaveBeenCalledOnce();
|
||||
// A rollback pulls a broken bundle, so it never waits on the prompt.
|
||||
expect(environment.confirmInstallNow).not.toHaveBeenCalled();
|
||||
expect(client.reloadAsync).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
@@ -276,6 +608,36 @@ describe("createAppUpdateLaunchCheck", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("shouldRecheckAppUpdateOnForeground", () => {
|
||||
it("requires a meaningful background gap", () => {
|
||||
expect(shouldRecheckAppUpdateOnForeground(null, 100_000, false)).toBe(false);
|
||||
expect(
|
||||
shouldRecheckAppUpdateOnForeground(
|
||||
100_000,
|
||||
100_000 + FOREGROUND_APP_UPDATE_RECHECK_AFTER_MS - 1,
|
||||
false,
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldRecheckAppUpdateOnForeground(
|
||||
100_000,
|
||||
100_000 + FOREGROUND_APP_UPDATE_RECHECK_AFTER_MS,
|
||||
false,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("stays quiet while a downloaded update waits for its install", () => {
|
||||
expect(
|
||||
shouldRecheckAppUpdateOnForeground(
|
||||
100_000,
|
||||
100_000 + FOREGROUND_APP_UPDATE_RECHECK_AFTER_MS,
|
||||
true,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("registerHiddenUpdateTap", () => {
|
||||
it("unlocks the manual check on the fifth tap", () => {
|
||||
let count = 0;
|
||||
|
||||
@@ -8,7 +8,13 @@ import {
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
|
||||
export type AppUpdateCheckState = "idle" | "checking" | "downloading" | "restarting" | "current";
|
||||
export type AppUpdateCheckState =
|
||||
| "idle"
|
||||
| "checking"
|
||||
| "downloading"
|
||||
| "ready"
|
||||
| "restarting"
|
||||
| "current";
|
||||
|
||||
export interface AppUpdateClient {
|
||||
readonly isEnabled: boolean;
|
||||
@@ -23,8 +29,70 @@ export interface AppUpdateClient {
|
||||
readonly reloadAsync: () => Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The pieces of the app the update flow has to coordinate with before it may
|
||||
* tear down the JavaScript runtime. Injectable so the flow stays unit-testable.
|
||||
*/
|
||||
export interface AppUpdateEnvironment {
|
||||
/** Asks the user to install the waiting update now; `false` keeps it deferred. */
|
||||
readonly confirmInstallNow: () => Promise<boolean>;
|
||||
/**
|
||||
* Lands persisted state (drafts, outbox) before the restart. Rejects when a
|
||||
* write failed, so a silent restart can hold off instead of dropping the
|
||||
* unsaved in-memory state.
|
||||
*/
|
||||
readonly flushPendingWrites: () => Promise<void>;
|
||||
/**
|
||||
* Whether a deferred restart may fire right now: the app must still be
|
||||
* backgrounded (flush latency or an iOS suspend can push the continuation
|
||||
* into the next foreground session) and not merely paused behind an
|
||||
* app-initiated handoff like the Android image picker.
|
||||
*/
|
||||
readonly isSafeToRestartInBackground: () => Promise<boolean>;
|
||||
/**
|
||||
* Runs `apply` the next time the app enters the background. With
|
||||
* `includeCurrent`, an app that is already backgrounded fires immediately
|
||||
* (so a backgrounding that raced module load is not missed); without it,
|
||||
* only a future transition fires, so an attempt that already failed in the
|
||||
* current background session cannot retry in a tight loop.
|
||||
*/
|
||||
readonly onNextBackground: (apply: () => void, includeCurrent: boolean) => void;
|
||||
/**
|
||||
* Runs `apply` once the app has stayed foregrounded for the whole prompt
|
||||
* window — the signal that a deferred install has had no backgrounding to
|
||||
* ride on.
|
||||
*/
|
||||
readonly onForegroundStay: (apply: () => void) => void;
|
||||
}
|
||||
|
||||
/** Tracks a downloaded update waiting for a safe moment to install. */
|
||||
export interface AppUpdateDeferral {
|
||||
pendingInstall: boolean;
|
||||
/**
|
||||
* Claimed by whichever restart sequence (deferred backgrounding, foreground
|
||||
* prompt, manual install) starts first, so racing paths cannot tear down
|
||||
* the runtime twice.
|
||||
*/
|
||||
installInProgress: boolean;
|
||||
}
|
||||
|
||||
export function createAppUpdateDeferral(): AppUpdateDeferral {
|
||||
return { pendingInstall: false, installInProgress: false };
|
||||
}
|
||||
|
||||
const appUpdateDeferral = createAppUpdateDeferral();
|
||||
|
||||
interface AppUpdateCheckOptions {
|
||||
/**
|
||||
* "background" (default) installs silently at the next backgrounding,
|
||||
* asking only if the app then stays foregrounded so long that the install
|
||||
* never gets its chance. "immediate" restarts as soon as the download
|
||||
* lands — reserved for flows where the user explicitly requested the update.
|
||||
*/
|
||||
readonly applyMode?: "background" | "immediate";
|
||||
readonly client?: AppUpdateClient;
|
||||
readonly deferral?: AppUpdateDeferral;
|
||||
readonly environment?: AppUpdateEnvironment;
|
||||
readonly onFailure?: (message: string) => void;
|
||||
readonly onStateChange?: (state: AppUpdateCheckState) => void;
|
||||
}
|
||||
@@ -86,6 +154,15 @@ export async function runAppUpdateCheck(options: AppUpdateCheckOptions = {}): Pr
|
||||
|
||||
if (appUpdateCheckInFlight) {
|
||||
await observeAppUpdateCheck(appUpdateCheckInFlight, options);
|
||||
// A background-mode check in flight may have deferred the download this
|
||||
// caller explicitly asked to install; honor the explicit request now.
|
||||
if (options.applyMode === "immediate") {
|
||||
const deferral = options.deferral ?? appUpdateDeferral;
|
||||
if (deferral.pendingInstall) {
|
||||
const environment = options.environment ?? defaultAppUpdateEnvironment;
|
||||
await installPendingAppUpdate(client, environment, deferral, options);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -109,6 +186,9 @@ export async function runAppUpdateCheck(options: AppUpdateCheckOptions = {}): Pr
|
||||
appUpdateCheckInFlight = inFlight;
|
||||
|
||||
const execution = performAppUpdateCheck(client, {
|
||||
applyMode: options.applyMode,
|
||||
deferral: options.deferral,
|
||||
environment: options.environment,
|
||||
onFailure: (message) => {
|
||||
progress.failure = message;
|
||||
notifyListeners(failureListeners, message);
|
||||
@@ -175,6 +255,15 @@ async function performAppUpdateCheck(
|
||||
options: AppUpdateCheckOptions,
|
||||
): Promise<void> {
|
||||
const setState = options.onStateChange ?? (() => {});
|
||||
const environment = options.environment ?? defaultAppUpdateEnvironment;
|
||||
const deferral = options.deferral ?? appUpdateDeferral;
|
||||
|
||||
// The user explicitly asked to install and a previous check has already
|
||||
// downloaded the update; restart into it without another network round trip.
|
||||
if (options.applyMode === "immediate" && deferral.pendingInstall) {
|
||||
await installPendingAppUpdate(client, environment, deferral, options);
|
||||
return;
|
||||
}
|
||||
|
||||
setState("checking");
|
||||
const check = await settlePromise(() => client.checkForUpdateAsync());
|
||||
@@ -203,14 +292,252 @@ async function performAppUpdateCheck(
|
||||
return;
|
||||
}
|
||||
|
||||
// A rollback directive exists to pull a broken bundle; never hold it
|
||||
// behind a prompt or a deferred install.
|
||||
if (options.applyMode === "immediate" || fetched.value.isRollBackToEmbedded) {
|
||||
const outcome = await installAppUpdate(
|
||||
client,
|
||||
environment,
|
||||
deferral,
|
||||
options,
|
||||
options.applyMode === "immediate",
|
||||
);
|
||||
if (outcome === "flush-failed") {
|
||||
// Only reachable for an automatic rollback: keep the state-bearing
|
||||
// runtime alive and retry like a deferred install. The fetched rollback
|
||||
// still applies at the next cold start regardless.
|
||||
setState("ready");
|
||||
armDeferredAppUpdateInstall(client, environment, deferral);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
setState("ready");
|
||||
armDeferredAppUpdateInstall(client, environment, deferral);
|
||||
}
|
||||
|
||||
type AppUpdateInstallOutcome = "installed" | "flush-failed" | "restart-failed";
|
||||
|
||||
/**
|
||||
* Restarting mid-session while native surfaces are mounted is the crashiest
|
||||
* moment expo-updates has, so the restart flushes persistence first and, by
|
||||
* default, waits for a backgrounding — where nothing is rendering and the
|
||||
* teardown is invisible. Only a restart the user explicitly asked for may
|
||||
* proceed over a failed flush; an automatic one aborts with "flush-failed"
|
||||
* so unsaved state is never silently discarded.
|
||||
*/
|
||||
async function installAppUpdate(
|
||||
client: AppUpdateClient,
|
||||
environment: AppUpdateEnvironment,
|
||||
deferral: AppUpdateDeferral,
|
||||
options: AppUpdateCheckOptions,
|
||||
userRequested: boolean,
|
||||
): Promise<AppUpdateInstallOutcome> {
|
||||
// A concurrent install sequence already owns the restart.
|
||||
if (deferral.installInProgress) return "installed";
|
||||
deferral.installInProgress = true;
|
||||
const setState = options.onStateChange ?? (() => {});
|
||||
setState("restarting");
|
||||
const flushed = await settlePromise(() => environment.flushPendingWrites());
|
||||
if (flushed._tag === "Failure") {
|
||||
reportUpdateFailure(flushed, "Could not save pending state.", undefined);
|
||||
if (!userRequested) {
|
||||
deferral.installInProgress = false;
|
||||
return "flush-failed";
|
||||
}
|
||||
}
|
||||
const reloaded = await settlePromise(() => client.reloadAsync());
|
||||
if (reloaded._tag === "Failure") {
|
||||
reportUpdateFailure(reloaded, "Downloaded, but could not restart the app.", options.onFailure);
|
||||
setState("idle");
|
||||
deferral.installInProgress = false;
|
||||
return "restart-failed";
|
||||
}
|
||||
return "installed";
|
||||
}
|
||||
|
||||
/** Restarts into an already-downloaded update at the user's request. */
|
||||
async function installPendingAppUpdate(
|
||||
client: AppUpdateClient,
|
||||
environment: AppUpdateEnvironment,
|
||||
deferral: AppUpdateDeferral,
|
||||
options: AppUpdateCheckOptions,
|
||||
): Promise<void> {
|
||||
const outcome = await installAppUpdate(client, environment, deferral, options, true);
|
||||
if (outcome === "restart-failed") {
|
||||
// Let later checks re-arm the install; the downloaded update still
|
||||
// applies at the next cold start regardless.
|
||||
deferral.pendingInstall = false;
|
||||
}
|
||||
}
|
||||
|
||||
function armDeferredAppUpdateInstall(
|
||||
client: AppUpdateClient,
|
||||
environment: AppUpdateEnvironment,
|
||||
deferral: AppUpdateDeferral,
|
||||
): void {
|
||||
if (deferral.pendingInstall) return;
|
||||
deferral.pendingInstall = true;
|
||||
scheduleDeferredAppUpdateInstall(client, environment, deferral, true);
|
||||
environment.onForegroundStay(() => {
|
||||
void promptDeferredAppUpdateInstall(client, environment, deferral);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* A deferred install normally rides the next backgrounding, but a session that
|
||||
* never leaves the foreground would sit on the download forever. Only then is
|
||||
* the user asked, and declining simply leaves the background install armed.
|
||||
*/
|
||||
async function promptDeferredAppUpdateInstall(
|
||||
client: AppUpdateClient,
|
||||
environment: AppUpdateEnvironment,
|
||||
deferral: AppUpdateDeferral,
|
||||
): Promise<void> {
|
||||
if (!deferral.pendingInstall || deferral.installInProgress) return;
|
||||
const installNow = await settlePromise(() => environment.confirmInstallNow());
|
||||
if (installNow._tag !== "Success" || !installNow.value) return;
|
||||
// A backgrounding while the alert was up may have started the deferred
|
||||
// restart already; the stale accept must not start a second one.
|
||||
if (!deferral.pendingInstall || deferral.installInProgress) return;
|
||||
await installPendingAppUpdate(client, environment, deferral, {});
|
||||
}
|
||||
|
||||
function scheduleDeferredAppUpdateInstall(
|
||||
client: AppUpdateClient,
|
||||
environment: AppUpdateEnvironment,
|
||||
deferral: AppUpdateDeferral,
|
||||
includeCurrent: boolean,
|
||||
): void {
|
||||
environment.onNextBackground(() => {
|
||||
void applyDeferredAppUpdateInstall(client, environment, deferral);
|
||||
}, includeCurrent);
|
||||
}
|
||||
|
||||
async function applyDeferredAppUpdateInstall(
|
||||
client: AppUpdateClient,
|
||||
environment: AppUpdateEnvironment,
|
||||
deferral: AppUpdateDeferral,
|
||||
): Promise<void> {
|
||||
if (!deferral.pendingInstall || deferral.installInProgress) return;
|
||||
deferral.installInProgress = true;
|
||||
const flushed = await settlePromise(() => environment.flushPendingWrites());
|
||||
const safe = await settlePromise(() => environment.isSafeToRestartInBackground());
|
||||
if (flushed._tag === "Failure" || safe._tag !== "Success" || !safe.value) {
|
||||
if (flushed._tag === "Failure") {
|
||||
// Nothing is lost yet: keep the state-bearing runtime alive and retry
|
||||
// the flush at the next backgrounding instead of restarting over it.
|
||||
reportUpdateFailure(flushed, "Could not save pending state.", undefined);
|
||||
}
|
||||
deferral.installInProgress = false;
|
||||
// This attempt already ran in the current background session; retrying
|
||||
// before a fresh transition would just loop over the same failure.
|
||||
scheduleDeferredAppUpdateInstall(client, environment, deferral, false);
|
||||
return;
|
||||
}
|
||||
const reloaded = await settlePromise(() => client.reloadAsync());
|
||||
if (reloaded._tag === "Failure") {
|
||||
reportUpdateFailure(reloaded, "Downloaded, but could not restart the app.", undefined);
|
||||
deferral.installInProgress = false;
|
||||
// Let later checks re-arm the install; the downloaded update still
|
||||
// applies at the next cold start regardless.
|
||||
deferral.pendingInstall = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function defaultConfirmInstallNow(): Promise<boolean> {
|
||||
const { Alert } = await import("react-native");
|
||||
return new Promise<boolean>((resolve) => {
|
||||
Alert.alert(
|
||||
"Update ready",
|
||||
"A new version has been downloaded and installs automatically the next time you leave the app. Install it now instead?",
|
||||
[
|
||||
{ onPress: () => resolve(false), style: "cancel", text: "Later" },
|
||||
{ onPress: () => resolve(true), text: "Install Now" },
|
||||
],
|
||||
{ cancelable: true, onDismiss: () => resolve(false) },
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async function defaultFlushPendingWrites(): Promise<void> {
|
||||
// Attempt every flush before surfacing the first failure, so one broken
|
||||
// store cannot keep the others from landing.
|
||||
const results = await Promise.allSettled([
|
||||
import("../../state/use-composer-drafts").then((drafts) => drafts.flushComposerDrafts()),
|
||||
import("../../state/thread-outbox").then((outbox) => outbox.flushThreadOutbox()),
|
||||
]);
|
||||
const failed = results.find(
|
||||
(result): result is PromiseRejectedResult => result.status === "rejected",
|
||||
);
|
||||
if (failed) throw failed.reason;
|
||||
}
|
||||
|
||||
async function defaultIsSafeToRestartInBackground(): Promise<boolean> {
|
||||
const { isForegroundHandoffActive } = await import("../../lib/foreground-handoff");
|
||||
if (isForegroundHandoffActive()) return false;
|
||||
const { AppState } = await import("react-native");
|
||||
return AppState.currentState === "background";
|
||||
}
|
||||
|
||||
function defaultOnNextBackground(apply: () => void, includeCurrent: boolean): void {
|
||||
void import("react-native").then(({ AppState }) => {
|
||||
const subscription = AppState.addEventListener("change", (state) => {
|
||||
if (state !== "background") return;
|
||||
subscription.remove();
|
||||
apply();
|
||||
});
|
||||
// The app may already have backgrounded while this module was loading;
|
||||
// the listener alone would then wait a whole extra foreground cycle.
|
||||
if (includeCurrent && AppState.currentState === "background") {
|
||||
subscription.remove();
|
||||
apply();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* How long the app may stay foregrounded with a downloaded update before the
|
||||
* install prompt appears. Long enough that most sessions background naturally
|
||||
* and install silently instead.
|
||||
*/
|
||||
export const DEFERRED_INSTALL_PROMPT_AFTER_MS = 30 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* The window resets on every backgrounding because that is exactly when the
|
||||
* deferred install gets its chance. iOS "inactive" blips (app switcher, a
|
||||
* pulled-down notification shade) leave the timer running.
|
||||
*/
|
||||
function defaultOnForegroundStay(apply: () => void): void {
|
||||
void import("react-native").then(({ AppState }) => {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const arm = () => {
|
||||
timer ??= setTimeout(() => {
|
||||
subscription.remove();
|
||||
apply();
|
||||
}, DEFERRED_INSTALL_PROMPT_AFTER_MS);
|
||||
};
|
||||
const disarm = () => {
|
||||
if (timer === undefined) return;
|
||||
clearTimeout(timer);
|
||||
timer = undefined;
|
||||
};
|
||||
const subscription = AppState.addEventListener("change", (state) => {
|
||||
if (state === "active") arm();
|
||||
else if (state === "background") disarm();
|
||||
});
|
||||
if (AppState.currentState === "active") arm();
|
||||
});
|
||||
}
|
||||
|
||||
const defaultAppUpdateEnvironment: AppUpdateEnvironment = {
|
||||
confirmInstallNow: defaultConfirmInstallNow,
|
||||
flushPendingWrites: defaultFlushPendingWrites,
|
||||
isSafeToRestartInBackground: defaultIsSafeToRestartInBackground,
|
||||
onNextBackground: defaultOnNextBackground,
|
||||
onForegroundStay: defaultOnForegroundStay,
|
||||
};
|
||||
|
||||
function reportUpdateFailure(
|
||||
result: AtomCommandResult<unknown, unknown>,
|
||||
fallback: string,
|
||||
@@ -243,3 +570,53 @@ export function createAppUpdateLaunchCheck(
|
||||
}
|
||||
|
||||
export const checkForAppUpdateOnLaunch = createAppUpdateLaunchCheck();
|
||||
|
||||
/**
|
||||
* The app can stay resident for days, so a launch-only check misses updates
|
||||
* published while it was in memory. Anything shorter reads as noise: brief
|
||||
* app switches should not trigger network checks or an install prompt.
|
||||
*/
|
||||
export const FOREGROUND_APP_UPDATE_RECHECK_AFTER_MS = 15 * 60 * 1000;
|
||||
|
||||
export function shouldRecheckAppUpdateOnForeground(
|
||||
backgroundedAtMs: number | null,
|
||||
activeAtMs: number,
|
||||
pendingInstall: boolean,
|
||||
): boolean {
|
||||
if (pendingInstall) return false;
|
||||
return (
|
||||
backgroundedAtMs !== null &&
|
||||
activeAtMs - backgroundedAtMs >= FOREGROUND_APP_UPDATE_RECHECK_AFTER_MS
|
||||
);
|
||||
}
|
||||
|
||||
export function createAppUpdateForegroundRecheck(
|
||||
client: AppUpdateClient = Updates,
|
||||
deferral: AppUpdateDeferral = appUpdateDeferral,
|
||||
): () => void {
|
||||
let started = false;
|
||||
|
||||
return () => {
|
||||
if (started || !isAppUpdateCheckAvailable(client)) return;
|
||||
started = true;
|
||||
void import("react-native").then(({ AppState }) => {
|
||||
let backgroundedAtMs: number | null = null;
|
||||
AppState.addEventListener("change", (state) => {
|
||||
if (state === "background") {
|
||||
backgroundedAtMs = Date.now();
|
||||
return;
|
||||
}
|
||||
if (state !== "active") return;
|
||||
const shouldCheck = shouldRecheckAppUpdateOnForeground(
|
||||
backgroundedAtMs,
|
||||
Date.now(),
|
||||
deferral.pendingInstall,
|
||||
);
|
||||
backgroundedAtMs = null;
|
||||
if (shouldCheck) void runAppUpdateCheck({ client, deferral });
|
||||
});
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
export const startAppUpdateForegroundRecheck = createAppUpdateForegroundRecheck();
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { File } from "expo-file-system";
|
||||
|
||||
let tempFileSequence = 0;
|
||||
|
||||
/**
|
||||
* Replaces a file's contents through a sibling temp file and an overwriting
|
||||
* rename, so an interrupted write (app restart, process death) never leaves a
|
||||
* truncated document at the final path. Each write stages through its own
|
||||
* temp file so concurrent writers to the same destination cannot move or
|
||||
* clobber each other's staging file mid-flight.
|
||||
*/
|
||||
export async function writeFileAtomically(file: File, contents: string): Promise<void> {
|
||||
const { File: FileConstructor } = await import("expo-file-system");
|
||||
tempFileSequence += 1;
|
||||
const temp = new FileConstructor(file.parentDirectory, `${file.name}.${tempFileSequence}.tmp`);
|
||||
temp.create({ intermediates: true, overwrite: true });
|
||||
temp.write(contents);
|
||||
temp.moveSync(file, { overwrite: true });
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
type UploadChatImageAttachment,
|
||||
} from "@t3tools/contracts";
|
||||
import { estimateBase64ByteSize } from "./base64";
|
||||
import { beginForegroundHandoff } from "./foreground-handoff";
|
||||
import { uuidv4 } from "./uuid";
|
||||
|
||||
export interface DraftComposerImageAttachment extends UploadChatImageAttachment {
|
||||
@@ -65,13 +66,21 @@ export async function pickComposerImages(input: { readonly existingCount: number
|
||||
};
|
||||
}
|
||||
|
||||
const result = await imagePicker.launchImageLibraryAsync({
|
||||
mediaTypes: ["images"],
|
||||
allowsMultipleSelection: true,
|
||||
selectionLimit: remainingSlots,
|
||||
base64: true,
|
||||
quality: 1,
|
||||
});
|
||||
// The picker covers the Android activity, which reports the app as
|
||||
// backgrounded; the guard keeps background-triggered restarts away mid-pick.
|
||||
const endHandoff = beginForegroundHandoff();
|
||||
let result: Awaited<ReturnType<typeof imagePicker.launchImageLibraryAsync>>;
|
||||
try {
|
||||
result = await imagePicker.launchImageLibraryAsync({
|
||||
mediaTypes: ["images"],
|
||||
allowsMultipleSelection: true,
|
||||
selectionLimit: remainingSlots,
|
||||
base64: true,
|
||||
quality: 1,
|
||||
});
|
||||
} finally {
|
||||
endHandoff();
|
||||
}
|
||||
|
||||
if (result.canceled) {
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { beginForegroundHandoff, isForegroundHandoffActive } from "./foreground-handoff";
|
||||
|
||||
describe("foreground handoff", () => {
|
||||
it("is active only while a handoff is open", () => {
|
||||
expect(isForegroundHandoffActive()).toBe(false);
|
||||
const end = beginForegroundHandoff();
|
||||
expect(isForegroundHandoffActive()).toBe(true);
|
||||
end();
|
||||
expect(isForegroundHandoffActive()).toBe(false);
|
||||
});
|
||||
|
||||
it("stays active until every overlapping handoff ends", () => {
|
||||
const endFirst = beginForegroundHandoff();
|
||||
const endSecond = beginForegroundHandoff();
|
||||
endFirst();
|
||||
expect(isForegroundHandoffActive()).toBe(true);
|
||||
endSecond();
|
||||
expect(isForegroundHandoffActive()).toBe(false);
|
||||
});
|
||||
|
||||
it("tolerates an end function called twice", () => {
|
||||
const endFirst = beginForegroundHandoff();
|
||||
const endSecond = beginForegroundHandoff();
|
||||
endFirst();
|
||||
endFirst();
|
||||
expect(isForegroundHandoffActive()).toBe(true);
|
||||
endSecond();
|
||||
expect(isForegroundHandoffActive()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Tracks app-initiated OS-surface handoffs (image picker, auth tab, share
|
||||
* sheet). Android reports the app as backgrounded while one of these covers
|
||||
* the activity, so background-triggered work — like a deferred app update
|
||||
* restart — has to wait them out instead of tearing down the mid-flow runtime.
|
||||
*/
|
||||
let activeHandoffs = 0;
|
||||
|
||||
/** Returns an idempotent end function; call it when the handoff resolves. */
|
||||
export function beginForegroundHandoff(): () => void {
|
||||
activeHandoffs += 1;
|
||||
let ended = false;
|
||||
return () => {
|
||||
if (ended) return;
|
||||
ended = true;
|
||||
activeHandoffs -= 1;
|
||||
};
|
||||
}
|
||||
|
||||
export function isForegroundHandoffActive(): boolean {
|
||||
return activeHandoffs > 0;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { writeFileAtomically } from "../lib/atomic-file";
|
||||
import {
|
||||
decodeQueuedThreadMessage,
|
||||
encodeQueuedThreadMessage,
|
||||
@@ -9,6 +10,24 @@ import {
|
||||
|
||||
const THREAD_OUTBOX_DIRECTORY = "thread-outbox";
|
||||
|
||||
const inFlightWrites = new Set<Promise<void>>();
|
||||
|
||||
function trackInFlightWrite(operation: Promise<void>): Promise<void> {
|
||||
inFlightWrites.add(operation);
|
||||
void operation.catch(() => undefined).finally(() => inFlightWrites.delete(operation));
|
||||
return operation;
|
||||
}
|
||||
|
||||
/**
|
||||
* Awaits queued-message writes so an app update restart cannot tear down the
|
||||
* runtime while one is mid-file.
|
||||
*/
|
||||
export async function flushThreadOutboxWrites(): Promise<void> {
|
||||
while (inFlightWrites.size > 0) {
|
||||
await Promise.allSettled(inFlightWrites);
|
||||
}
|
||||
}
|
||||
|
||||
export class ThreadOutboxStorageError extends Schema.TaggedErrorClass<ThreadOutboxStorageError>()(
|
||||
"ThreadOutboxStorageError",
|
||||
{
|
||||
@@ -89,11 +108,12 @@ export const expoThreadOutboxStorage: ThreadOutboxStorage = {
|
||||
write: async (message) => {
|
||||
const fileName = messageFileName(message.messageId);
|
||||
try {
|
||||
const file = await getMessageFile(message.messageId);
|
||||
if (!file.exists) {
|
||||
file.create({ intermediates: true, overwrite: true });
|
||||
}
|
||||
file.write(JSON.stringify(encodeQueuedThreadMessage(message)));
|
||||
await trackInFlightWrite(
|
||||
(async () => {
|
||||
const file = await getMessageFile(message.messageId);
|
||||
await writeFileAtomically(file, JSON.stringify(encodeQueuedThreadMessage(message)));
|
||||
})(),
|
||||
);
|
||||
} catch (cause) {
|
||||
throw new ThreadOutboxStorageError({
|
||||
operation: "write",
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import { createThreadOutboxManager } from "./thread-outbox-manager";
|
||||
import type { QueuedThreadMessage } from "./thread-outbox-model";
|
||||
import { expoThreadOutboxStorage } from "./thread-outbox-storage";
|
||||
import { expoThreadOutboxStorage, flushThreadOutboxWrites } from "./thread-outbox-storage";
|
||||
|
||||
export * from "./thread-outbox-model";
|
||||
|
||||
@@ -12,6 +12,17 @@ export const threadOutboxManager = createThreadOutboxManager({
|
||||
storage: expoThreadOutboxStorage,
|
||||
});
|
||||
|
||||
/**
|
||||
* Lands queued outbox mutations before the JS runtime is torn down (app update
|
||||
* restart). An enqueued message is published to the atom immediately but its
|
||||
* durable write waits behind the mutation queue, so draining only the writes
|
||||
* already mid-file would miss it.
|
||||
*/
|
||||
export async function flushThreadOutbox(): Promise<void> {
|
||||
await threadOutboxManager.serialize(async () => {});
|
||||
await flushThreadOutboxWrites();
|
||||
}
|
||||
|
||||
export function ensureThreadOutboxLoaded(): void {
|
||||
void threadOutboxManager.load();
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { vi } from "vite-plus/test";
|
||||
|
||||
const composerDraftFileMocks = vi.hoisted(() => {
|
||||
let document = "";
|
||||
let writeError: Error | null = null;
|
||||
let releaseRead: (() => void) | null = null;
|
||||
let readBarrier = Promise.resolve();
|
||||
|
||||
@@ -17,23 +18,35 @@ const composerDraftFileMocks = vi.hoisted(() => {
|
||||
releaseRead?.();
|
||||
releaseRead = null;
|
||||
},
|
||||
getDocument() {
|
||||
return document;
|
||||
},
|
||||
setDocument(value: unknown) {
|
||||
document = JSON.stringify(value);
|
||||
},
|
||||
setWriteError(error: Error | null) {
|
||||
writeError = error;
|
||||
},
|
||||
Directory: class {
|
||||
create() {}
|
||||
},
|
||||
File: class {
|
||||
exists = true;
|
||||
parentDirectory = null;
|
||||
|
||||
create() {}
|
||||
|
||||
moveSync() {}
|
||||
|
||||
async text() {
|
||||
await readBarrier;
|
||||
return document;
|
||||
}
|
||||
|
||||
write(value: string) {
|
||||
if (writeError) {
|
||||
throw writeError;
|
||||
}
|
||||
document = value;
|
||||
}
|
||||
},
|
||||
@@ -49,15 +62,18 @@ vi.mock("expo-file-system", () => ({
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import {
|
||||
clearComposerDraftContentState,
|
||||
ComposerDraftPersistenceError,
|
||||
composerDraftsAtom,
|
||||
copyComposerDraftContentIfEmpty,
|
||||
copyComposerDraftContentState,
|
||||
decodePersistedComposerDrafts,
|
||||
type ComposerDraft,
|
||||
flushComposerDrafts,
|
||||
getComposerDraftSnapshot,
|
||||
mergeComposerDraftContentState,
|
||||
removeComposerDraftsForEnvironment,
|
||||
restoreComposerDraftSnapshotState,
|
||||
setComposerDraftText,
|
||||
} from "./use-composer-drafts";
|
||||
|
||||
const DRAFT: ComposerDraft = {
|
||||
@@ -393,4 +409,27 @@ describe("mobile composer drafts", () => {
|
||||
[unrelatedKey]: unrelated,
|
||||
});
|
||||
});
|
||||
|
||||
it("lands a still-debounced draft write when flushed", async () => {
|
||||
const draftKey = "environment-1:thread-1";
|
||||
setComposerDraftText(draftKey, "typed right before the restart");
|
||||
|
||||
await flushComposerDrafts();
|
||||
|
||||
expect(JSON.parse(composerDraftFileMocks.getDocument())).toMatchObject({
|
||||
drafts: { [draftKey]: { text: "typed right before the restart" } },
|
||||
});
|
||||
});
|
||||
|
||||
it("propagates a flush write failure instead of resolving as saved", async () => {
|
||||
const draftKey = "environment-1:thread-1";
|
||||
setComposerDraftText(draftKey, "unsaved");
|
||||
composerDraftFileMocks.setWriteError(new Error("storage unavailable"));
|
||||
|
||||
try {
|
||||
await expect(flushComposerDrafts()).rejects.toBeInstanceOf(ComposerDraftPersistenceError);
|
||||
} finally {
|
||||
composerDraftFileMocks.setWriteError(null);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -13,6 +13,7 @@ import * as Schema from "effect/Schema";
|
||||
import { useEffect } from "react";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { writeFileAtomically } from "../lib/atomic-file";
|
||||
import { DraftComposerImageAttachmentSchema } from "../lib/composer-image-schema";
|
||||
import type { DraftComposerImageAttachment } from "../lib/composerImages";
|
||||
import { SerializedAsyncQueue } from "../lib/serialized-async-queue";
|
||||
@@ -188,10 +189,7 @@ async function writePersistedComposerDrafts(drafts: Record<string, ComposerDraft
|
||||
} as const;
|
||||
const encoded = JSON.stringify(document);
|
||||
operation = "write";
|
||||
if (!file.exists) {
|
||||
file.create({ intermediates: true, overwrite: true });
|
||||
}
|
||||
file.write(encoded);
|
||||
await writeFileAtomically(file, encoded);
|
||||
} catch (cause) {
|
||||
throw new ComposerDraftPersistenceError({
|
||||
operation,
|
||||
@@ -211,6 +209,26 @@ async function savePersistedComposerDrafts(drafts: Record<string, ComposerDraft>
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lands any debounced or in-flight draft write before the JS runtime is torn
|
||||
* down (app update restart), so the freshest draft state survives it. A write
|
||||
* failure propagates so the caller can decide whether the restart may proceed.
|
||||
*/
|
||||
export async function flushComposerDrafts(): Promise<void> {
|
||||
// An edit during an awaited write schedules another debounced write, so
|
||||
// keep landing snapshots until no debounce is pending after a queue drain.
|
||||
do {
|
||||
while (persistTimer !== null) {
|
||||
clearTimeout(persistTimer);
|
||||
persistTimer = null;
|
||||
await persistenceQueue.run(() =>
|
||||
writePersistedComposerDrafts(appAtomRegistry.get(composerDraftsAtom)),
|
||||
);
|
||||
}
|
||||
await persistenceQueue.run(() => Promise.resolve());
|
||||
} while (persistTimer !== null);
|
||||
}
|
||||
|
||||
function schedulePersistComposerDrafts(drafts: Record<string, ComposerDraft>): void {
|
||||
if (persistTimer !== null) {
|
||||
clearTimeout(persistTimer);
|
||||
@@ -627,7 +645,7 @@ export async function clearComposerDraftsEnvironment(environmentId: EnvironmentI
|
||||
persistTimer = null;
|
||||
}
|
||||
appAtomRegistry.set(composerDraftsAtom, next);
|
||||
await writePersistedComposerDrafts(next);
|
||||
await persistenceQueue.run(() => writePersistedComposerDrafts(next));
|
||||
}
|
||||
|
||||
export function useComposerDraft(draftKey: string | null): ComposerDraft {
|
||||
|
||||
@@ -70,4 +70,12 @@ If a step fails:
|
||||
3. For a command-line server, relaunch it with `npx t3@<client-version>`, replacing
|
||||
`<client-version>` with the client version shown in the warning.
|
||||
|
||||
## The Mobile App
|
||||
|
||||
The mobile app keeps itself current on its own. When it finds a new version, it downloads it in the
|
||||
background and installs it automatically the next time you leave the app. Unsent drafts and queued
|
||||
messages are saved before the restart. Only if the app stays open long enough that the update never
|
||||
gets that chance does it ask whether to install right away; choosing **Later** is safe and keeps the
|
||||
automatic install armed.
|
||||
|
||||
For remote connection setup and access troubleshooting, see [Remote Access](./remote-access.md).
|
||||
Reference in new issue
Block a user