Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix(storage): keep app and updates usable during recovery (#7030)

Ezra Elletteabc5bc161088
diff --git a/apps/screenpipe-app-tauri/bun.lock b/apps/screenpipe-app-tauri/bun.lock
index 4398b9800..ae01e2ce5 100644
--- a/apps/screenpipe-app-tauri/bun.lock
+++ b/apps/screenpipe-app-tauri/bun.lock
@@ -34,10 +34,8 @@
"@tauri-apps/plugin-notification": "~2.3.3",
"@tauri-apps/plugin-opener": "~2.5.3",
"@tauri-apps/plugin-os": "~2.3.2",
- "@tauri-apps/plugin-process": "~2.3.1",
"@tauri-apps/plugin-shell": "~2.3.5",
"@tauri-apps/plugin-store": "~2.4.2",
- "@tauri-apps/plugin-updater": "~2.10.0",
"@tiptap/extension-hard-break": "^3.22.5",
"@tiptap/extension-image": "3.22.5",
"@tiptap/extension-list": "^3.22.5",
@@ -712,14 +710,10 @@
"@tauri-apps/plugin-os": ["@tauri-apps/[email protected]", "", { "dependencies": { "@tauri-apps/api": "^2.8.0" } }, "sha512-n+nXWeuSeF9wcEsSPmRnBEGrRgOy6jjkSU+UVCOV8YUGKb2erhDOxis7IqRXiRVHhY8XMKks00BJ0OAdkpf6+A=="],
- "@tauri-apps/plugin-process": ["@tauri-apps/[email protected]", "", { "dependencies": { "@tauri-apps/api": "^2.8.0" } }, "sha512-nCa4fGVaDL/B9ai03VyPOjfAHRHSBz5v6F/ObsB73r/dA3MHHhZtldaDMIc0V/pnUw9ehzr2iEG+XkSEyC0JJA=="],
-
"@tauri-apps/plugin-shell": ["@tauri-apps/[email protected]", "", { "dependencies": { "@tauri-apps/api": "^2.10.1" } }, "sha512-jewtULhiQ7lI7+owCKAjc8tYLJr92U16bPOeAa472LHJdgaibLP83NcfAF2e+wkEcA53FxKQAZ7byDzs2eeizg=="],
"@tauri-apps/plugin-store": ["@tauri-apps/[email protected]", "", { "dependencies": { "@tauri-apps/api": "^2.8.0" } }, "sha512-0ClHS50Oq9HEvLPhNzTNFxbWVOqoAp3dRvtewQBeqfIQ0z5m3JRnOISIn2ZVPCrQC0MyGyhTS9DWhHjpigQE7A=="],
- "@tauri-apps/plugin-updater": ["@tauri-apps/[email protected]", "", { "dependencies": { "@tauri-apps/api": "^2.10.1" } }, "sha512-ljN8jPlnT0aSn8ecYhuBib84alxfMx6Hc8vJSKMJyzGbTPFZAC44T2I1QNFZssgWKrAlofvJqCC6Rr472JWfkQ=="],
-
"@testing-library/dom": ["@testing-library/[email protected]", "", { "dependencies": { "@babel/code-frame": "^7.10.4", "@babel/runtime": "^7.12.5", "@types/aria-query": "^5.0.1", "aria-query": "5.1.3", "chalk": "^4.1.0", "dom-accessibility-api": "^0.5.9", "lz-string": "^1.5.0", "pretty-format": "^27.0.2" } }, "sha512-FlS4ZWlp97iiNWig0Muq8p+3rVDjRiYE+YKGbAqXOu9nwJFFOdL00kFpz42M+4huzYi86vAK1sOOfyOG45muIQ=="],
"@testing-library/jest-dom": ["@testing-library/[email protected]", "", { "dependencies": { "@adobe/css-tools": "^4.4.0", "aria-query": "^5.0.0", "css.escape": "^1.5.1", "dom-accessibility-api": "^0.6.3", "picocolors": "^1.1.1", "redent": "^3.0.0" } }, "sha512-zIcONa+hVtVSSep9UT3jZ5rizo2BsxgyDYU7WFD5eICBE7no3881HGeb/QkGfsJs6JTkY1aQhT7rIPC7e+0nnA=="],
@@ -2860,14 +2854,10 @@
"@tauri-apps/plugin-os/@tauri-apps/api": ["@tauri-apps/[email protected]", "", {}, "sha512-ga7zdhbS2GXOMTIZRT0mYjKJtR9fivsXzsyq5U3vjDL0s6DTMwYRm0UHNjzTY5dh4+LSC68Sm/7WEiimbQNYlw=="],
- "@tauri-apps/plugin-process/@tauri-apps/api": ["@tauri-apps/[email protected]", "", {}, "sha512-ga7zdhbS2GXOMTIZRT0mYjKJtR9fivsXzsyq5U3vjDL0s6DTMwYRm0UHNjzTY5dh4+LSC68Sm/7WEiimbQNYlw=="],
-
"@tauri-apps/plugin-shell/@tauri-apps/api": ["@tauri-apps/[email protected]", "", {}, "sha512-hKL/jWf293UDSUN09rR69hrToyIXBb8CjGaWC7gfinvnQrBVvnLr08FeFi38gxtugAVyVcTa5/FD/Xnkb1siBw=="],
"@tauri-apps/plugin-store/@tauri-apps/api": ["@tauri-apps/[email protected]", "", {}, "sha512-ga7zdhbS2GXOMTIZRT0mYjKJtR9fivsXzsyq5U3vjDL0s6DTMwYRm0UHNjzTY5dh4+LSC68Sm/7WEiimbQNYlw=="],
- "@tauri-apps/plugin-updater/@tauri-apps/api": ["@tauri-apps/[email protected]", "", {}, "sha512-hKL/jWf293UDSUN09rR69hrToyIXBb8CjGaWC7gfinvnQrBVvnLr08FeFi38gxtugAVyVcTa5/FD/Xnkb1siBw=="],
-
"@testing-library/dom/aria-query": ["[email protected]", "", { "dependencies": { "deep-equal": "^2.0.5" } }, ""],
"@testing-library/dom/chalk": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, ""],
diff --git a/apps/screenpipe-app-tauri/components/storage-migration-gate.test.tsx b/apps/screenpipe-app-tauri/components/storage-migration-gate.test.tsx
index 878a02c83..ef9ce92a5 100644
--- a/apps/screenpipe-app-tauri/components/storage-migration-gate.test.tsx
+++ b/apps/screenpipe-app-tauri/components/storage-migration-gate.test.tsx
@@ -13,9 +13,10 @@ vi.mock("@/lib/utils/tauri", () => ({ commands: { getStorageMigrationActivity: m
vi.mock("@/lib/hooks/use-tauri-event", () => ({
useTauriEvent: (_: string, handler: typeof mock.onActivity) => { mock.onActivity = handler; },
}));
+vi.mock("./update-banner", () => ({ UpdateBanner: () => <button>restart to update</button> }));
import { StorageMigrationGate } from "./storage-migration-gate";
-const idle: StorageMigrationActivity = { root: "/fixture", busy: false, message: "", error: null, elapsed_seconds: 0, completed_records: null, total_records: null, bytes_saved: null, available_bytes: null, completed: false };
+const idle: StorageMigrationActivity = { root: "/fixture", busy: false, recovering: false, message: "", error: null, elapsed_seconds: 0, completed_records: null, total_records: null, bytes_saved: null, available_bytes: null, completed: false };
const running = { ...idle, busy: true, message: "compressing recordings" };
const notify = (payload: StorageMigrationActivity) => act(() => mock.onActivity({ payload }));
@@ -29,14 +30,21 @@ beforeEach(() => {
afterEach(cleanup);
describe("app-wide migration modal", () => {
- it("shows startup recovery until recording is ready without offering duplicate retries", async () => {
- mock.getActivity.mockResolvedValue({ ...running, message: "restoring saved screen records" });
- render(<StorageMigrationGate />);
- const dialog = await screen.findByRole("dialog", { name: "preparing storage" });
- expect(dialog).toHaveTextContent("restoring saved screen records");
+ it("keeps settings and updates accessible during startup recovery without duplicate retries", async () => {
+ mock.getActivity.mockResolvedValue({ ...running, recovering: true, message: "restoring saved screen records" });
+ const openSettings = vi.fn();
+ render(<><StorageMigrationGate /><button onClick={openSettings}>settings</button></>);
+ const recovery = await screen.findByRole("complementary", { name: "storage recovery" });
+ expect(recovery).toHaveTextContent("restoring saved screen records");
+ expect(screen.queryByRole("dialog")).toBeNull();
+ expect(screen.getByRole("button", { name: "restart to update" })).toBeEnabled();
+ fireEvent.click(screen.getByRole("button", { name: "settings" }));
+ expect(openSettings).toHaveBeenCalledOnce();
expect(screen.queryByRole("button", { name: /try again|do later/i })).toBeNull();
- notify({ ...running, message: "starting recording on recovered storage" });
- expect(dialog).toHaveTextContent("starting recording on recovered storage");
+ notify({ ...running, recovering: true, message: "starting recording on recovered storage" });
+ expect(recovery).toHaveTextContent("starting recording on recovered storage");
+ fireEvent.click(screen.getByRole("button", { name: "hide" }));
+ expect(screen.queryByRole("complementary")).toBeNull();
notify(idle);
expect(screen.queryByRole("dialog")).toBeNull();
});
@@ -118,6 +126,7 @@ describe("app-wide migration modal", () => {
window.addEventListener("keydown", shortcut, true);
try {
notify(running);
+ expect(fireEvent.keyDown(screen.getByRole("button", { name: "restart to update" }), { key: "Tab" })).toBe(true);
expect(fireEvent.keyDown(window, { key: "Tab", ctrlKey: true })).toBe(false);
fireEvent.keyDown(window, { key: "Escape" });
expect(shortcut).not.toHaveBeenCalled();
@@ -128,4 +137,18 @@ describe("app-wide migration modal", () => {
window.removeEventListener("keydown", shortcut, true);
}
});
+
+ it("does not swallow keyboard shortcuts during recovery", async () => {
+ mock.getActivity.mockResolvedValue({ ...running, recovering: true });
+ render(<StorageMigrationGate />);
+ await screen.findByRole("complementary");
+ const shortcut = vi.fn();
+ window.addEventListener("keydown", shortcut, true);
+ try {
+ fireEvent.keyDown(window, { key: "Tab", ctrlKey: true });
+ expect(shortcut).toHaveBeenCalledOnce();
+ } finally {
+ window.removeEventListener("keydown", shortcut, true);
+ }
+ });
});
diff --git a/apps/screenpipe-app-tauri/components/storage-migration-gate.tsx b/apps/screenpipe-app-tauri/components/storage-migration-gate.tsx
index 3782d0072..3665648f7 100644
--- a/apps/screenpipe-app-tauri/components/storage-migration-gate.tsx
+++ b/apps/screenpipe-app-tauri/components/storage-migration-gate.tsx
@@ -7,10 +7,12 @@ import { Loader2 } from "lucide-react";
import { commands, type StorageMigrationActivity } from "@/lib/utils/tauri";
import { migrationBytes, migrationElapsed, StorageMigrationPrompt } from "./storage-migration-prompt";
import { useTauriEvent } from "@/lib/hooks/use-tauri-event";
+import { UpdateBanner } from "./update-banner";
-/** One blocker per webview, driven only by this native process's active operation. */
+/** Explicit conversion blocks history; startup recovery leaves the shell usable. */
export function StorageMigrationGate({ offerMigration = false }: { offerMigration?: boolean }) {
- const [activity, setActivity] = useState<StorageMigrationActivity>({ root: null, busy: false, message: "", error: null, completed: false, elapsed_seconds: 0, completed_records: null, total_records: null, bytes_saved: null, available_bytes: null });
+ const [activity, setActivity] = useState<StorageMigrationActivity>({ root: null, busy: false, recovering: false, message: "", error: null, completed: false, elapsed_seconds: 0, completed_records: null, total_records: null, bytes_saved: null, available_bytes: null });
+ const [recoveryDismissed, setRecoveryDismissed] = useState(false);
const [unavailable, setUnavailable] = useState(false);
const [elapsed, setElapsed] = useState(0);
useEffect(() => {
@@ -22,15 +24,16 @@ export function StorageMigrationGate({ offerMigration = false }: { offerMigratio
}, [activity.busy, activity.elapsed_seconds]);
const revision = useRef(0);
const dialog = useRef<HTMLDialogElement>(null);
- const busy = useRef(activity.busy);
- busy.current = activity.busy;
+ const modal = activity.busy && !activity.recovering;
+ const busy = useRef(modal);
+ busy.current = modal;
useLayoutEffect(() => {
const blockAppShortcuts = (event: KeyboardEvent) => {
if (!busy.current) return;
event.stopImmediatePropagation();
if (event.key === "Escape") event.preventDefault();
- if (event.key === "Tab") {
+ if (event.key === "Tab" && (event.ctrlKey || event.metaKey)) {
event.preventDefault();
dialog.current?.focus();
}
@@ -75,13 +78,28 @@ export function StorageMigrationGate({ offerMigration = false }: { offerMigratio
useLayoutEffect(() => {
const element = dialog.current;
if (!element) return;
- if (activity.busy && !element.open) element.showModal();
- if (!activity.busy && element.open) element.close();
+ if (modal && !element.open) element.showModal();
+ if (!modal && element.open) element.close();
return () => { if (element.open) element.close(); };
- }, [activity.busy]);
+ }, [modal]);
if (!activity.busy) return offerMigration ? <StorageMigrationPrompt activity={activity} /> : null;
+ if (activity.recovering) {
+ if (recoveryDismissed) return null;
+ return (
+ <aside aria-label="storage recovery" className="fixed bottom-4 right-4 z-50 w-[calc(100%-2rem)] max-w-sm space-y-3 rounded-lg border border-border bg-background p-4 text-foreground shadow-lg">
+ <div className="flex items-center justify-between gap-3">
+ <h2 className="text-sm font-semibold">restoring recording</h2>
+ <button type="button" onClick={() => setRecoveryDismissed(true)} className="text-xs underline">hide</button>
+ </div>
+ <p className="text-xs text-muted-foreground">Recording and history are unavailable while recovery runs. You can use settings and install updates.</p>
+ <p role="status" className="text-xs">{unavailable ? "Waiting for recovery status…" : activity.message} · {migrationElapsed(elapsed)}</p>
+ <UpdateBanner compact />
+ </aside>
+ );
+ }
+
const total = activity.total_records ?? 0;
const converted = activity.completed_records ?? 0;
const percentage = total > 0 ? Math.min(100, Math.floor(converted / total * 100)) : null;
@@ -125,6 +143,7 @@ export function StorageMigrationGate({ offerMigration = false }: { offerMigratio
<p className="border-t border-border pt-4 text-xs text-muted-foreground">
Keep Screenpipe open until storage is ready. If interrupted, Screenpipe restores recording from the saved progress before migration can be retried.
</p>
+ <UpdateBanner compact />
</div>
</dialog>
);
diff --git a/apps/screenpipe-app-tauri/components/storage-migration-prompt.test.tsx b/apps/screenpipe-app-tauri/components/storage-migration-prompt.test.tsx
index 255b99999..9daa4a887 100644
--- a/apps/screenpipe-app-tauri/components/storage-migration-prompt.test.tsx
+++ b/apps/screenpipe-app-tauri/components/storage-migration-prompt.test.tsx
@@ -12,7 +12,7 @@ const commands = vi.hoisted(() => ({
vi.mock("@/lib/utils/tauri", () => ({ commands }));
import { StorageMigrationPrompt } from "./storage-migration-prompt";
-const idle: StorageMigrationActivity = { root: "/fixture", busy: false, message: "", error: null, elapsed_seconds: 0, completed_records: null, total_records: null, bytes_saved: null, available_bytes: null, completed: false };
+const idle: StorageMigrationActivity = { root: "/fixture", busy: false, recovering: false, message: "", error: null, elapsed_seconds: 0, completed_records: null, total_records: null, bytes_saved: null, available_bytes: null, completed: false };
let status: StorageMigrationStatus;
beforeEach(() => {
diff --git a/apps/screenpipe-app-tauri/components/update-banner.test.tsx b/apps/screenpipe-app-tauri/components/update-banner.test.tsx
new file mode 100644
index 000000000..e5dadb6bb
--- /dev/null
+++ b/apps/screenpipe-app-tauri/components/update-banner.test.tsx
@@ -0,0 +1,40 @@
+// screenpipe — AI that knows everything you've seen, said, or heard
+// https://screenpipe.com
+
+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+
+const mock = vi.hoisted(() => ({ restart: vi.fn(), flush: vi.fn(), toast: vi.fn() }));
+vi.mock("@/lib/utils/tauri", () => ({ commands: { restartForUpdate: mock.restart } }));
+vi.mock("@/lib/hooks/use-settings", () => ({ flushPendingSettingsWrites: mock.flush }));
+vi.mock("@/components/ui/use-toast", () => ({ useToast: () => ({ toast: mock.toast }) }));
+
+import { UpdateBanner, useUpdateBanner } from "./update-banner";
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mock.flush.mockResolvedValue(undefined);
+ mock.restart.mockResolvedValue({ status: "ok", data: "proceed" });
+ useUpdateBanner.setState({ isVisible: true, updateInfo: { version: "999.0.0", body: "" }, isInstalling: false, authRequired: null });
+});
+afterEach(cleanup);
+
+it("flushes settings before the native update handoff, including the recovery banner", async () => {
+ let finishSave!: () => void;
+ mock.flush.mockReturnValue(new Promise<void>((resolve) => { finishSave = resolve; }));
+ render(<UpdateBanner compact />);
+ fireEvent.click(screen.getByRole("button", { name: "restart to update" }));
+ expect(mock.restart).not.toHaveBeenCalled();
+ await act(async () => finishSave());
+ await waitFor(() => expect(mock.restart).toHaveBeenCalledWith(60));
+ expect(screen.getByRole("button", { name: "restarting..." })).toBeDisabled();
+});
+
+it("makes a failed native install retryable and shows its error", async () => {
+ mock.restart.mockResolvedValueOnce({ status: "error", error: "installer could not start" });
+ render(<UpdateBanner compact />);
+ fireEvent.click(screen.getByRole("button", { name: "restart to update" }));
+ await waitFor(() => expect(mock.toast).toHaveBeenCalledWith(expect.objectContaining({ description: "installer could not start" })));
+ fireEvent.click(screen.getByRole("button", { name: "restart to update" }));
+ await waitFor(() => expect(mock.restart).toHaveBeenCalledTimes(2));
+});
diff --git a/apps/screenpipe-app-tauri/components/update-banner.tsx b/apps/screenpipe-app-tauri/components/update-banner.tsx
index d3694aacd..246c638c0 100644
--- a/apps/screenpipe-app-tauri/components/update-banner.tsx
+++ b/apps/screenpipe-app-tauri/components/update-banner.tsx
@@ -9,16 +9,10 @@ import { Sparkles, X } from "lucide-react";
import { create } from "zustand";
import { useEffect } from "react";
import { listen } from "@tauri-apps/api/event";
-import { relaunch } from "@tauri-apps/plugin-process";
import { commands } from "@/lib/utils/tauri";
-import { check, type Update } from "@tauri-apps/plugin-updater";
-import { platform, arch } from "@tauri-apps/plugin-os";
import { useToast } from "@/components/ui/use-toast";
import { cn } from "@/lib/utils";
-import { screenpipeWebUrl } from "@/lib/web-url";
-import { enterpriseUpdateAuthHeaders } from "@/lib/enterprise-auth-recovery";
-import { flushPendingSettingsWrites, useSettings, type Settings } from "@/lib/hooks/use-settings";
-import { resolveConsumerUpdateChannel } from "@/lib/update-channel";
+import { flushPendingSettingsWrites } from "@/lib/hooks/use-settings";
interface UpdateInfo {
version: string;
@@ -35,7 +29,6 @@ interface UpdateBannerState {
isVisible: boolean;
updateInfo: UpdateInfo | null;
isInstalling: boolean;
- pendingUpdate: Update | null;
authRequired: AuthRequiredInfo | null;
// Version the user dismissed in this session. Periodic re-checks and
// providers-remount hydration would otherwise re-show the same banner
@@ -44,7 +37,6 @@ interface UpdateBannerState {
setIsVisible: (visible: boolean) => void;
setUpdateInfo: (info: UpdateInfo | null) => void;
setIsInstalling: (installing: boolean) => void;
- setPendingUpdate: (update: Update | null) => void;
setAuthRequired: (info: AuthRequiredInfo | null) => void;
dismiss: (version: string) => void;
resetDismissed: () => void;
@@ -54,13 +46,11 @@ export const useUpdateBanner = create<UpdateBannerState>((set) => ({
isVisible: false,
updateInfo: null,
isInstalling: false,
- pendingUpdate: null,
authRequired: null,
dismissedVersion: null,
setIsVisible: (visible) => set({ isVisible: visible }),
setUpdateInfo: (info) => set({ updateInfo: info }),
setIsInstalling: (installing) => set({ isInstalling: installing }),
- setPendingUpdate: (update) => set({ pendingUpdate: update }),
setAuthRequired: (info) => set({ authRequired: info }),
dismiss: (version) => set({ isVisible: false, authRequired: null, dismissedVersion: version }),
resetDismissed: () => set({ dismissedVersion: null }),
@@ -73,44 +63,12 @@ interface UpdateBannerProps {
variant?: "default" | "sidebar";
}
-async function getWindowsUpdateOptions(settings: Settings | null | undefined) {
- const cpuArch = arch();
- const isEnterprise = await commands.isEnterpriseBuildCmd().catch(() => false);
- const channel = isEnterprise
- ? "enterprise"
- : resolveConsumerUpdateChannel(settings);
- const headers: Record<string, string> = {};
-
- if (isEnterprise) {
- const [licenseKey, accountToken] = await Promise.all([
- commands.getEnterpriseLicenseKey().catch(() => null),
- commands.getCloudToken().catch(() => null),
- ]);
- Object.assign(
- headers,
- enterpriseUpdateAuthHeaders(licenseKey, accountToken),
- );
- }
-
- return {
- checkOptions: {
- endpoints: [
- screenpipeWebUrl(`/api/app-update/${channel}/windows-${cpuArch}/{{current_version}}`, "https://screenpipe.com"),
- ],
- ...(Object.keys(headers).length > 0 ? { headers } : {}),
- },
- downloadOptions: Object.keys(headers).length > 0 ? { headers } : undefined,
- };
-}
-
export function UpdateBanner({ className, compact = false, variant = "default" }: UpdateBannerProps) {
- const { isVisible, updateInfo, isInstalling, setIsInstalling, pendingUpdate, authRequired, dismiss } = useUpdateBanner();
+ const { isVisible, updateInfo, isInstalling, setIsInstalling, authRequired, dismiss } = useUpdateBanner();
const { toast } = useToast();
- const { settings } = useSettings();
const handleUpdate = async () => {
setIsInstalling(true);
- const os = platform();
try {
// A user can enable Auto-update and immediately click this banner. The
@@ -133,83 +91,24 @@ export function UpdateBanner({ className, compact = false, variant = "default" }
return;
}
- // Windows: NSIS installer calls process::exit directly, bypassing our
- // ExitRequested handler — plain relaunch is fine. macOS/Linux go through
- // restart_for_update which sets QUIT_REQUESTED so the exit isn't blocked
- // by main.rs (2026-06-10 "stuck on still starting" report).
- if (os === "windows" && !updateInfo?.persistent) {
- const gate = await commands.awaitSafeRestart(60);
- if (gate !== "proceed") {
- setIsInstalling(false);
- toast({
- title: "screenpipe is still starting up",
- description:
- gate === "errored"
- ? "startup error — open settings to see details before restarting"
- : "finish startup first, then click update again",
- variant: "destructive",
- });
- return;
- }
- toast({
- title: "downloading update...",
- description: "please wait while the update is downloaded",
- duration: Infinity,
- });
-
- // Stop screenpipe before update on Windows
- try {
- await commands.stopScreenpipe();
- } catch (e) {
- console.warn("failed to stop screenpipe:", e);
- }
-
- // Get or check for the update
- let update = pendingUpdate;
- const { checkOptions, downloadOptions } = await getWindowsUpdateOptions(settings);
- if (!update) {
- update = await check(checkOptions as any);
- }
-
- if (update?.available) {
-
-
- await update.downloadAndInstall(undefined, downloadOptions);
-
- toast({
- title: "update complete",
- description: "relaunching application",
- duration: 3000,
- });
- }
-
- // Fallback relaunch only if installer didn't run (no update available
- // at click time); normal path: downloadAndInstall already exited.
- await relaunch();
- } else {
- // macOS/Linux: bundle already staged by backend. `restart_for_update`
- // gates internally, so no separate `awaitSafeRestart` call needed.
+ // Native code owns the download/install handoff on Windows and the
+ // staged restart elsewhere, including startup exclusion and bounded stop.
+ toast({
+ title: "installing update...",
+ description: "screenpipe will restart automatically",
+ duration: 10000,
+ });
+ const res = await commands.restartForUpdate(60);
+ const outcome = res.status === "ok" ? res.data : "errored";
+ if (outcome !== "proceed") {
+ setIsInstalling(false);
toast({
- title: "installing update...",
- description: "screenpipe will restart automatically",
- duration: 10000,
+ title: "update could not restart",
+ description: res.status === "error"
+ ? res.error
+ : "audio is still initializing — try updating again shortly",
+ variant: "destructive",
});
- const res = await commands.restartForUpdate(60);
- const outcome = res.status === "ok" ? res.data : "errored";
- if (outcome !== "proceed") {
- setIsInstalling(false);
- toast({
- title: "screenpipe is still starting up",
- description:
- outcome === "errored"
- ? "startup error — open settings to see details before restarting"
- : "finish startup first, then click update again",
- variant: "destructive",
- });
- return;
- }
- // restart scheduled off-thread; runtime will tear down shortly.
- // Leave button on "restarting…" until the process is replaced.
}
} catch (error) {
console.error("failed to update:", error);
diff --git a/apps/screenpipe-app-tauri/lib/utils/tauri.ts b/apps/screenpipe-app-tauri/lib/utils/tauri.ts
index bcf48f6cf..f6beffdaf 100644
--- a/apps/screenpipe-app-tauri/lib/utils/tauri.ts
+++ b/apps/screenpipe-app-tauri/lib/utils/tauri.ts
@@ -4332,7 +4332,7 @@ headless?: boolean;
headlessRecordOnly?: boolean }
export type ShowRewindWindow = "Main" | { Home: { page: string | null } } | { Search: { query: string | null } } | "Onboarding" | "Chat" | "PermissionRecovery"
export type StartExportRecordingResponse = { jobId: string }
-export type StorageMigrationActivity = { root: string | null; busy: boolean; message: string; error: string | null; elapsed_seconds: number; completed_records: number | null; total_records: number | null; bytes_saved: number | null; available_bytes: number | null; completed: boolean }
+export type StorageMigrationActivity = { root: string | null; busy: boolean; recovering: boolean; message: string; error: string | null; elapsed_seconds: number; completed_records: number | null; total_records: number | null; bytes_saved: number | null; available_bytes: number | null; completed: boolean }
export type StorageMigrationStatus = { root: string; app_session_id: string; busy: boolean; message: string; error: string | null; pending: boolean; in_place: boolean; completed: boolean; using_new_storage: boolean; generation: string | null; source_bytes: number; migrated_bytes: number | null; bytes_saved: number | null; available_bytes: number | null; can_migrate: boolean; can_cancel: boolean; can_delete_source: boolean; blocked_reason: string | null }
export type Suggestion = { text: string;
/**
diff --git a/apps/screenpipe-app-tauri/package.json b/apps/screenpipe-app-tauri/package.json
index 15a7a8c5e..517907823 100644
--- a/apps/screenpipe-app-tauri/package.json
+++ b/apps/screenpipe-app-tauri/package.json
@@ -113,10 +113,8 @@
"@tauri-apps/plugin-notification": "~2.3.3",
"@tauri-apps/plugin-opener": "~2.5.3",
"@tauri-apps/plugin-os": "~2.3.2",
- "@tauri-apps/plugin-process": "~2.3.1",
"@tauri-apps/plugin-shell": "~2.3.5",
"@tauri-apps/plugin-store": "~2.4.2",
- "@tauri-apps/plugin-updater": "~2.10.0",
"@tiptap/extension-hard-break": "^3.22.5",
"@tiptap/extension-image": "3.22.5",
"@tiptap/extension-list": "^3.22.5",
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
index d233d5571..e78e455bb 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
@@ -134,6 +134,7 @@ mod tray;
mod staged_update;
mod stale_tier;
mod startup_auth;
+mod update_restart;
mod updates;
mod voice_training;
mod window;
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs b/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs
index 427c191be..ef3896678 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs
@@ -459,6 +459,11 @@ impl ServerCore {
};
info!("Database initialized at {}", db_path);
+ // A pending update may interrupt database recovery, but must exclude
+ // native model initialization until the old process exits. Retain the
+ // read guard through all remaining startup work, including errors.
+ let _native_startup = crate::update_restart::RESTART_SAFETY.native_startup().await;
+
// --- Audio devices + manager (built but NOT started) ---
let audio_devices = if config.disable_audio {
Vec::new()
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/storage_migration.rs b/apps/screenpipe-app-tauri/src-tauri/src/storage_migration.rs
index bd83aa458..959b47381 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/storage_migration.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/storage_migration.rs
@@ -54,6 +54,7 @@ fn clear_migration_error(root: &Path) -> Result<(), String> {
struct Operation {
root: Option<PathBuf>,
busy: bool,
+ recovering: bool,
message: String,
error: Option<String>,
started_at: Option<Instant>,
@@ -71,6 +72,7 @@ impl Operation {
StorageMigrationActivity {
root: self.root.as_ref().map(|root| root.display().to_string()),
busy: self.busy,
+ recovering: self.recovering,
message: self.message.clone(),
error: self.error.clone(),
elapsed_seconds: self
@@ -93,6 +95,7 @@ pub struct StorageMigrationState(Mutex<Operation>);
pub struct StorageMigrationActivity {
pub root: Option<String>,
pub busy: bool,
+ pub recovering: bool,
pub message: String,
pub error: Option<String>,
pub elapsed_seconds: u64,
@@ -316,6 +319,7 @@ pub(crate) async fn resume_before_startup(
root: Some(root.clone()),
busy: true,
message: "restoring recording after an interrupted migration".into(),
+ recovering: true,
started_at: Some(Instant::now()),
..Default::default()
};
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/update_restart.rs b/apps/screenpipe-app-tauri/src-tauri/src/update_restart.rs
new file mode 100644
index 000000000..419d388d2
--- /dev/null
+++ b/apps/screenpipe-app-tauri/src-tauri/src/update_restart.rs
@@ -0,0 +1,67 @@
+// screenpipe — AI that knows everything you've seen, said, or heard
+// https://screenpipe.com
+
+use std::time::Duration;
+use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
+
+/// Storage recovery is restartable, but exiting during native model creation
+/// can race ONNX Runtime's process destructors (#3622). Hold this barrier from
+/// audio initialization through the end of ServerCore startup. An updater that
+/// wins during recovery prevents startup from entering native initialization.
+pub(crate) static RESTART_SAFETY: RestartSafety = RestartSafety(RwLock::const_new(()));
+
+pub(crate) struct RestartSafety(RwLock<()>);
+
+impl RestartSafety {
+ pub(crate) async fn native_startup(&self) -> RwLockReadGuard<'_, ()> {
+ self.0.read().await
+ }
+
+ pub(crate) async fn prepare_restart(
+ &self,
+ timeout: Duration,
+ ) -> Option<RwLockWriteGuard<'_, ()>> {
+ tokio::time::timeout(timeout, self.0.write()).await.ok()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[tokio::test]
+ async fn recovery_does_not_block_updates_and_cannot_start_native_init_after_handoff() {
+ let safety = RestartSafety(RwLock::new(()));
+ // Database recovery does not hold the native initialization barrier.
+ let update = safety
+ .prepare_restart(Duration::from_secs(1))
+ .await
+ .unwrap();
+ assert!(
+ tokio::time::timeout(Duration::from_millis(10), safety.native_startup())
+ .await
+ .is_err()
+ );
+ // A failed/cancelled install releases the reservation, allowing the
+ // original startup to continue without relaunching or losing progress.
+ drop(update);
+ let _startup = tokio::time::timeout(Duration::from_secs(1), safety.native_startup())
+ .await
+ .unwrap();
+ }
+
+ #[tokio::test]
+ async fn native_initialization_still_defers_restart_until_it_finishes() {
+ let safety = RestartSafety(RwLock::new(()));
+ let startup = safety.native_startup().await;
+ assert!(safety
+ .prepare_restart(Duration::from_millis(10))
+ .await
+ .is_none());
+ drop(startup);
+ assert!(safety
+ .prepare_restart(Duration::from_secs(1))
+ .await
+ .is_some());
+ }
+}
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/updates.rs b/apps/screenpipe-app-tauri/src-tauri/src/updates.rs
index 39e399dd5..30c79fc3d 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/updates.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/updates.rs
@@ -41,6 +41,85 @@ fn consumer_update_endpoint(channel: &str) -> String {
)
}
+fn configured_updater(app: &tauri::AppHandle) -> Result<tauri_plugin_updater::Updater, Error> {
+ let mut builder = app.updater_builder();
+ let settings = SettingsStore::get(app).ok().flatten();
+ let is_beta_build = app.config().identifier.contains("beta");
+ if !is_enterprise_build(app) && !is_beta_build {
+ let channel = consumer_update_channel(settings.as_ref());
+ builder = builder.endpoints(vec![consumer_update_endpoint(channel).parse()?])?;
+ }
+ if is_enterprise_build(app) {
+ if let Some(license_key) = crate::commands::get_enterprise_license_key() {
+ builder = builder.header("X-License-Key", license_key)?;
+ }
+ if let Some(token) = crate::commands::get_cloud_token() {
+ builder = builder.header("Authorization", format!("Bearer {token}"))?;
+ }
+ } else if let Some(settings) = settings {
+ if let Some(token) = settings
+ .user
+ .token
+ .clone()
+ .filter(|t| !t.is_empty())
+ .or_else(crate::auth_token::cached_cloud_token)
+ {
+ builder = builder.header("Authorization", format!("Bearer {token}"))?;
+ }
+ }
+ Ok(builder.build()?)
+}
+
+async fn stop_before_update(app: &tauri::AppHandle) {
+ match bounded_teardown(
+ PRE_EXIT_TEARDOWN_TIMEOUT,
+ stop_screenpipe(app.state::<RecordingState>(), app.clone()),
+ )
+ .await
+ {
+ TeardownOutcome::Completed => {}
+ TeardownOutcome::Failed(error) => warn!("update teardown failed (continuing): {error}"),
+ TeardownOutcome::TimedOut => warn!(
+ "update teardown exceeded {}s — continuing with the update",
+ PRE_EXIT_TEARDOWN_TIMEOUT.as_secs()
+ ),
+ }
+}
+
+#[cfg(target_os = "windows")]
+async fn install_windows_update(
+ app: &tauri::AppHandle,
+ update: &tauri_plugin_updater::Update,
+ bytes: Vec<u8>,
+ timeout: Duration,
+) -> Result<(), tauri_plugin_updater::Error> {
+ let restart = crate::update_restart::RESTART_SAFETY
+ .prepare_restart(timeout)
+ .await
+ .ok_or_else(|| std::io::Error::other("audio is still initializing; try updating again"))?;
+ crate::store::persist_store_before_restart(app).map_err(std::io::Error::other)?;
+ let recording = app.state::<RecordingState>();
+ let wants_recording = recording.capture_intended();
+ stop_before_update(app).await;
+ save_pre_update_version(app, update.body.clone());
+ record_update_attempt(app, &update.version);
+ // The NSIS handoff exits this process. Keep native startup excluded until
+ // that exit; an install error drops the guard so startup can continue.
+ UPDATE_RESTART_STARTED.store(true, Ordering::SeqCst);
+ if let Err(error) = update.install(bytes) {
+ UPDATE_RESTART_STARTED.store(false, Ordering::SeqCst);
+ recording.set_capture_intent(wants_recording);
+ return Err(error);
+ }
+ std::mem::forget(restart);
+ crate::process_exit::request_app_relaunch(
+ app.clone(),
+ "windows update restart",
+ Duration::from_millis(250),
+ );
+ Ok(())
+}
+
// ---------------------------------------------------------------------------
// Rollback: download a specific older version from R2 via the website API
// ---------------------------------------------------------------------------
@@ -219,19 +298,12 @@ pub struct PendingUpdateSnapshot {
}
// ─────────────────────────────────────────────────────────────────────────────
-// Restart gate (#3622)
+// Legacy boot-readiness IPC (#3622)
//
-// Every code path that culminates in `process::exit` — the auto-update
-// restart, banner-triggered relaunch, rollback restart — must wait for
-// `ServerCore::start` to reach the "ready" phase first. Otherwise the OS
-// runs onnxruntime's C++ static destructors while `AudioManager::new` is
-// still mid-`create_session` on the server worker thread, and the global
-// DataTypeRegistry gets torn down under the still-running PlannerImpl,
-// segfaulting at 0x2c8. Stack: #3557. Sentry can't see this crash because
-// the Rust SDK dies before the event ships.
-//
-// `await_restart_gate` is the single internal entry point; the
-// `await_safe_restart` Tauri command exposes it to the frontend banner.
+// Retain await_safe_restart for older callers that only query readiness.
+// Actual update installs/restarts now hold update_restart::RESTART_SAFETY:
+// waiting for all of ServerCore::start stranded interrupted migrations, and
+// a readiness snapshot alone cannot prevent a later native initialization.
// ─────────────────────────────────────────────────────────────────────────────
/// Outcome of `await_restart_gate`. Callers branch on this rather than a
@@ -272,10 +344,8 @@ impl RestartGate {
}
}
-/// Cap for the auto-update restart wait. Production boot is well under a
-/// minute even on cold installs; a 5-minute cap covers slow first-time
-/// model downloads and large DB migrations without holding the CheckGuard
-/// forever on a stuck startup.
+/// Cap while native initialization holds the restart barrier. Database
+/// migration/recovery does not hold it and must not defer an update.
const AUTO_UPDATE_GATE_TIMEOUT: Duration = Duration::from_secs(5 * 60);
/// Frontend (banner) cap. Shorter than the internal one because the user
@@ -417,11 +487,33 @@ pub async fn restart_for_update(
timeout_secs: Option<u64>,
) -> Result<String, String> {
let cap = Duration::from_secs(timeout_secs.unwrap_or(BANNER_GATE_TIMEOUT_SECS));
- let gate = await_restart_gate(cap, "banner-triggered restart").await;
- if !gate.should_restart() {
- return Ok(gate.as_str().to_string());
+ #[cfg(target_os = "windows")]
+ if !is_enterprise_build(&app) || enterprise_update_route(&app) == EnterpriseUpdateRoute::Tauri {
+ // Keep recovery running during the download. Reserve native startup
+ // only for the bounded teardown and installer handoff.
+ let update = configured_updater(&app)
+ .map_err(|error| error.to_string())?
+ .check()
+ .await
+ .map_err(|error| error.to_string())?
+ .ok_or_else(|| "no update is available; check for updates again".to_string())?;
+ let bytes = update
+ .download(|_, _| {}, || {})
+ .await
+ .map_err(|error| error.to_string())?;
+ install_windows_update(&app, &update, bytes, cap)
+ .await
+ .map_err(|error| error.to_string())?;
+ return Ok("proceed".into());
}
+ let Some(restart) = crate::update_restart::RESTART_SAFETY
+ .prepare_restart(cap)
+ .await
+ else {
+ return Ok("pending".into());
+ };
+
// The native tray calls this function directly, without passing through
// UpdateBanner's webview-local settings queue. Flush the shared store here
// so every caller has the same durability guarantee. Refuse the restart if
@@ -475,26 +567,11 @@ pub async fn restart_for_update(
// stall the relaunch (2026-06-26 MacBook Air: VisionManager hung 10s →
// ~57s frozen before the update applied). server_core.rs retries the
// port bind if the next boot races teardown.
- match bounded_teardown(
- PRE_EXIT_TEARDOWN_TIMEOUT,
- stop_screenpipe(app.state::<RecordingState>(), app.clone()),
- )
- .await
- {
- TeardownOutcome::Completed => {}
- TeardownOutcome::Failed(err) => {
- warn!(
- "banner restart: stop_screenpipe failed (continuing): {}",
- err
- )
- }
- TeardownOutcome::TimedOut => warn!(
- "banner restart: teardown exceeded {}s (capture shutdown wedged) — relaunching anyway",
- PRE_EXIT_TEARDOWN_TIMEOUT.as_secs()
- ),
- }
+ stop_before_update(&app).await;
// Off-thread so the IPC reply flushes before runtime teardown.
+ // Keep the reservation until process exit, including that IPC delay.
+ std::mem::forget(restart);
if persistent_version.is_some() {
crate::process_exit::request_app_quit(app.clone());
} else {
@@ -1066,33 +1143,7 @@ impl UpdatesManager {
current_version,
self.app.config().identifier
);
- // Build updater with auth header so paid users can download from R2
- let mut builder = self.app.updater_builder();
- let settings = SettingsStore::get(&self.app).ok().flatten();
- let is_beta_build = self.app.config().identifier.contains("beta");
- if !is_enterprise_build(&self.app) && !is_beta_build {
- let channel = consumer_update_channel(settings.as_ref());
- builder = builder.endpoints(vec![consumer_update_endpoint(channel).parse()?])?;
- }
- if is_enterprise_build(&self.app) {
- if let Some(license_key) = crate::commands::get_enterprise_license_key() {
- builder = builder.header("X-License-Key", license_key)?;
- }
- if let Some(token) = crate::commands::get_cloud_token() {
- builder = builder.header("Authorization", format!("Bearer {token}"))?;
- }
- } else if let Some(settings) = settings {
- if let Some(token) = settings
- .user
- .token
- .clone()
- .filter(|t| !t.is_empty())
- .or_else(crate::auth_token::cached_cloud_token)
- {
- builder = builder.header("Authorization", format!("Bearer {}", token))?;
- }
- }
- let check_result = builder.build()?.check().await;
+ let check_result = configured_updater(&self.app)?.check().await;
match &check_result {
Ok(Some(ref u)) => {
info!("update found: v{}", u.version);
@@ -1286,19 +1337,6 @@ impl UpdatesManager {
item.set_text("Downloading latest version of screenpipe")?;
}
- #[cfg(target_os = "windows")]
- {
- if auto_update {
- wait_for_meeting_restart_window(&self.app).await;
- }
- // Windows: stop screenpipe before replacing the binary
- if let Err(err) =
- stop_screenpipe(self.app.state::<RecordingState>(), self.app.clone()).await
- {
- error!("Failed to stop recording before update: {}", err);
- }
- }
-
// Retry transient download failures with exponential backoff.
// Auth errors (401/403) short-circuit out of the loop — see error arm.
let retry_delays = [
@@ -1386,7 +1424,21 @@ impl UpdatesManager {
let result = if let Some(result) = persistent_result {
result
} else {
- update.download_and_install(on_chunk, || {}).await
+ match update.download(on_chunk, || {}).await {
+ Ok(bytes) => {
+ if auto_update {
+ wait_for_meeting_restart_window(&self.app).await;
+ }
+ install_windows_update(
+ &self.app,
+ &update,
+ bytes,
+ AUTO_UPDATE_GATE_TIMEOUT,
+ )
+ .await
+ }
+ Err(error) => Err(error),
+ }
};
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
let result = update.download_and_install(on_chunk, || {}).await;
@@ -1562,16 +1614,17 @@ impl UpdatesManager {
update.version
);
- // #3622: gate process::exit on boot-ready to avoid the ORT teardown
- // race. In the common case boot is already ready and this returns
- // immediately. See `await_restart_gate` for the full rationale.
- let label = format!("auto-update v{}", update.version);
- if !await_restart_gate(AUTO_UPDATE_GATE_TIMEOUT, &label)
+ let _ = self.app.emit(
+ "update-restarting",
+ serde_json::json!({ "version": update.version, "delay_secs": 30 }),
+ );
+ wait_for_meeting_restart_window(&self.app).await;
+ let Some(restart) = crate::update_restart::RESTART_SAFETY
+ .prepare_restart(AUTO_UPDATE_GATE_TIMEOUT)
.await
- .should_restart()
- {
+ else {
return Result::Ok(true);
- }
+ };
// Only the first trigger applies; defer to an in-flight restart.
if UPDATE_RESTART_STARTED.swap(true, Ordering::SeqCst) {
@@ -1584,34 +1637,11 @@ impl UpdatesManager {
let persistent_update =
enterprise_route == EnterpriseUpdateRoute::PersistentPackage;
- let _ = self.app.emit(
- "update-restarting",
- serde_json::json!({
- "version": update.version,
- "delay_secs": 30,
- }),
- );
- wait_for_meeting_restart_window(&self.app).await;
if persistent_update {
request_persistent_update_for_restart().map_err(std::io::Error::other)?;
}
- // Time-bounded: never let a wedged capture/audio teardown stall
- // the relaunch (see PRE_EXIT_TEARDOWN_TIMEOUT / 2026-06-26 report).
- match bounded_teardown(
- PRE_EXIT_TEARDOWN_TIMEOUT,
- stop_screenpipe(self.app.state::<RecordingState>(), self.app.clone()),
- )
- .await
- {
- TeardownOutcome::Completed => {}
- TeardownOutcome::Failed(err) => {
- error!("Failed to stop recording before auto-update: {}", err)
- }
- TeardownOutcome::TimedOut => warn!(
- "auto-update: teardown exceeded {}s (capture shutdown wedged) — relaunching anyway",
- PRE_EXIT_TEARDOWN_TIMEOUT.as_secs()
- ),
- }
+ stop_before_update(&self.app).await;
+ std::mem::forget(restart);
if persistent_update {
crate::process_exit::request_app_quit(self.app.clone());
} else {