A desktop coding agent with free access to frontier models.
TypeScript
fix: restart through staged update install
Samrat Talukdarb6d7181af863
diff --git a/apps/app/src/app/lib/desktop.ts b/apps/app/src/app/lib/desktop.tsindex 13a2a174..26b93f0a 100644--- a/apps/app/src/app/lib/desktop.ts+++ b/apps/app/src/app/lib/desktop.ts@@ -145,6 +145,8 @@ export type StartFailureAnswer = {resetIncludesChats?: boolean;/** The local databases cannot be written: offer "Fix and restart". */canRepairStore?: boolean;+ /** Show Reset app data first (a restart alone would fail the same way). */+ leadWithReset?: boolean;hint: { title: string; body: string } | null;};diff --git a/apps/app/src/react-app/shell/loading-overlay.tsx b/apps/app/src/react-app/shell/loading-overlay.tsxindex 1dbede5c..527f2e41 100644--- a/apps/app/src/react-app/shell/loading-overlay.tsx+++ b/apps/app/src/react-app/shell/loading-overlay.tsx@@ -119,6 +119,31 @@ export function LoadingOverlay() {const resetAppData = window.__OMNIRUSH_ELECTRON__?.startup?.resetAppData;const repairStore = failureAnswer?.canRepairStore ? window.__OMNIRUSH_ELECTRON__?.startup?.repairStore : undefined;const hint = failureAnswer?.hint ?? null;+ const leadWithReset = failureAnswer?.leadWithReset === true;+ const resetButton = (primary: boolean) => (+ <button+ type="button"+ data-testid="start-failure-reset"+ className={primary+ ? "rounded-md bg-dls-accent px-3 py-2 font-medium text-[var(--dls-accent-fg)]"+ : "rounded-md border border-dls-border px-3 py-2 font-medium text-dls-primary"}+ onClick={() => {+ if (!resetAppData) return;+ const confirmText = failureAnswer?.resetIncludesChats ? RESET_APP_DATA_CONFIRM_WITH_CHATS : RESET_APP_DATA_CONFIRM;+ if (!window.confirm(confirmText)) return;+ setActionState("Restarting with fresh app data…");+ void resetAppData()+ .then((result) => {+ if (result.backupDir) {+ setActionState(`Restarting with fresh app data. Your previous app data is kept in ${result.backupDir}; after the restart, choose Restore previous app data to go back to it.`);+ }+ })+ .catch(() => setActionState("Reset could not be started. Please retry."));+ }}+ >+ Reset app data+ </button>+ );if (!visible || (suppressForGateway && !error)) return null;@@ -145,6 +170,7 @@ export function LoadingOverlay() {) : (<div className="text-dls-secondary">Try again. If it keeps failing, return to a version that works on this computer.</div>)}+ {resetAppData && leadWithReset ? resetButton(true) : null}{repairStore ? (<buttontype="button"@@ -164,7 +190,7 @@ export function LoadingOverlay() {) : null}<buttontype="button"- className={repairStore+ className={repairStore || leadWithReset? "rounded-md border border-dls-border px-3 py-2 font-medium text-dls-primary": "rounded-md bg-dls-accent px-3 py-2 font-medium text-[var(--dls-accent-fg)]"}onClick={() => window.location.reload()}@@ -212,26 +238,7 @@ export function LoadingOverlay() {))}</div>) : null}- {resetAppData ? (- <button- type="button"- className="rounded-md border border-dls-border px-3 py-2 font-medium text-dls-primary"- onClick={() => {- const confirmText = failureAnswer?.resetIncludesChats ? RESET_APP_DATA_CONFIRM_WITH_CHATS : RESET_APP_DATA_CONFIRM;- if (!window.confirm(confirmText)) return;- setActionState("Restarting with fresh app data…");- void resetAppData()- .then((result) => {- if (result.backupDir) {- setActionState(`Restarting with fresh app data. Your previous app data is kept in ${result.backupDir}; after the restart, choose Restore previous app data to go back to it.`);- }- })- .catch(() => setActionState("Reset could not be started. Please retry."));- }}- >- Reset app data- </button>- ) : null}+ {resetAppData && !leadWithReset ? resetButton(false) : null}{actionState ? <div className="text-dls-secondary">{actionState}</div> : null}<details className="text-left text-dls-secondary"><summary className="cursor-pointer">Technical details</summary>diff --git a/apps/app/tests/start-failure-lead-reset.test.tsx b/apps/app/tests/start-failure-lead-reset.test.tsxnew file mode 100644index 00000000..326e747c--- /dev/null+++ b/apps/app/tests/start-failure-lead-reset.test.tsx@@ -0,0 +1,65 @@+import { GlobalRegistrator } from "@happy-dom/global-registrator";+import { expect, mock, test } from "bun:test";+import { act } from "react";+import { createRoot } from "react-dom/client";++test("couldn't start on a read-only store that marks cannot fix: Reset app data leads, no Fix and restart", async () => {+ const registeredDom = typeof globalThis.window === "undefined" || typeof globalThis.document === "undefined";+ if (registeredDom) GlobalRegistrator.register({ url: "http://localhost/" });+ Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", { configurable: true, value: true });++ // Stable values, as the real providers keep them across renders.+ const desktopConfig = { config: {}, refreshFresh: async () => ({}) };+ const cloudStatus = { gatewayMode: false, visible: false, viewModel: { variant: "hidden" } };+ mock.module("@/react-app/domains/cloud/desktop-config-provider", () => ({+ useDesktopConfig: () => desktopConfig,+ }));+ mock.module("@/react-app/shell/cloud-workspace-overlay", () => ({+ useCloudWorkspaceStatus: () => cloudStatus,+ }));+ const technical = "attempt to write a readonly database";+ const bootState = { phase: "error", routeReady: false, message: "Something went wrong", error: technical };+ mock.module("@/react-app/shell/boot-state", () => ({+ bootOverlayCanHide: () => false,+ useBootOverlayVisible: () => true,+ useBootState: () => bootState,+ }));++ const reportFailure = mock(async (_input: { message?: string | null }) => ({+ category: "store_readonly",+ avHint: "none",+ canRepairStore: false,+ leadWithReset: true,+ hint: { title: "omnirush.ai can't write its local data", body: "Press Fix and restart." },+ }));+ const repairStore = mock(async () => ({ ok: true, fixed: 2, failed: 0 }));+ Object.assign(window, {+ __OMNIRUSH_ELECTRON__: {+ startup: { reportFailure, repairStore, resetAppData: async () => ({ ok: true }) },+ recovery: { list: async () => ({ ok: true, releases: [] }) },+ },+ __omnirushRecoveryControl: {},+ });++ const { LoadingOverlay } = await import("../src/react-app/shell/loading-overlay");+ const container = document.createElement("div");+ document.body.append(container);+ const root = createRoot(container);+ try {+ await act(async () => {+ root.render(<LoadingOverlay />);+ });+ await act(async () => {+ await Promise.resolve();+ });+ expect(container.querySelector("[data-testid=start-failure-repair-store]")).toBeNull();+ const buttons = [...container.querySelectorAll("button")].map((button) => button.textContent);+ expect(buttons[0]).toBe("Reset app data");+ expect(buttons.filter((text) => text === "Reset app data").length).toBe(1);+ expect(repairStore).toHaveBeenCalledTimes(0);+ } finally {+ await act(async () => root.unmount());+ container.remove();+ if (registeredDom) await GlobalRegistrator.unregister();+ }+});diff --git a/apps/desktop/electron/main.mjs b/apps/desktop/electron/main.mjsindex d802572c..987d7a22 100644--- a/apps/desktop/electron/main.mjs+++ b/apps/desktop/electron/main.mjs@@ -1501,6 +1501,21 @@ function startReportScrubRoots() {return roots;}+/** Set by restartApp(): the quit below ends in a restart. */+let restartAfterQuit = false;++/**+ * Quit and open again (Fix and restart, Reset / Restore app data). The+ * relaunch happens at the end of the before-quit teardown: when an update is+ * staged, its installer opens the new version instead, so the old exe never+ * starts while the installer replaces it.+ */+function restartApp() {+ restartAfterQuit = true;+ turnGuard.allowQuit();+ app.quit();+}+function startStoreFiles() {return storeFiles({ userDataPath: app.getPath("userData"), env: process.env, homedir: os.homedir() });}@@ -1563,7 +1578,10 @@ async function reportStartFailure(input = {}) {avHint,resetIncludesChats,// "Fix and restart": clear read-only marks on the store files, then restart.- canRepairStore: category === "store_readonly",+ // Only when there is a read-only mark to clear: otherwise a restart would fail the same way.+ canRepairStore: category === "store_readonly" && storeCheck?.repairable === true,+ // A read-only store that clearing marks cannot fix: Reset app data is the way out.+ leadWithReset: category === "store_readonly" && storeCheck?.repairable !== true,hint: startFailureHint(category, { avHint, storeCheck }),};if (storeCheck) {@@ -2142,11 +2160,7 @@ const desktopCommandHandlers = {const result = await repairStoreAccess({ files: startStoreFiles() });console.info(`[start-report] store repair: fixed=${result.fixed} failed=${result.failed}`);// Restart: connections opened read-only stay read-only in this process.- setTimeout(() => {- turnGuard.allowQuit();- app.relaunch();- app.quit();- }, 1_500).unref?.();+ setTimeout(() => restartApp(), 1_500).unref?.();return { ok: result.failed === 0, ...result };},"startupResetAppData": async () => {@@ -2155,11 +2169,7 @@ const desktopCommandHandlers = {includeEngineData: reportedStart.answer?.resetIncludesChats === true,});// A moment for the window to show where the backup goes.- setTimeout(() => {- turnGuard.allowQuit();- app.relaunch();- app.quit();- }, 4_000).unref?.();+ setTimeout(() => restartApp(), 4_000).unref?.();return { ok: true, backupDir };},"runtimeStatus": async (event, ...args) => {@@ -3234,7 +3244,7 @@ or use: pnpm dev:worktree`);// Re-check the update feed while services stop, so a download staged// before newer releases shipped is replaced by the newest one instead// of installing on quit.- const updateInstall = prepareInstallOnQuit();+ const updateInstall = prepareInstallOnQuit({ relaunch: restartAfterQuit });try {await Promise.all([disposeRuntimeBeforeQuit(),@@ -3247,7 +3257,10 @@ or use: pnpm dev:worktree`);scheduleBlankSlateProfileCleanup();const installUpdateAndQuit = await updateInstall;if (installUpdateAndQuit) installUpdateAndQuit();- else app.quit();+ else {+ if (restartAfterQuit) app.relaunch();+ app.quit();+ }}});});@@ -3370,9 +3383,7 @@ or use: pnpm dev:worktree`);if (response === 1) await shell.openPath(startReset.backupDir);if (response === 2) {await scheduleStartRestore({ userDataPath: app.getPath("userData"), backupDir: startReset.backupDir });- turnGuard.allowQuit();- app.relaunch();- app.quit();+ restartApp();}});}diff --git a/apps/desktop/electron/start-report.mjs b/apps/desktop/electron/start-report.mjsindex dcce19b2..dc36fa01 100644--- a/apps/desktop/electron/start-report.mjs+++ b/apps/desktop/electron/start-report.mjs@@ -551,7 +551,9 @@ export function startFailureHint(category, { platform = process.platform, avHintif (storeCheck?.elevated === true && windows) {return {title: "omnirush.ai is running as administrator",- body: "Close omnirush.ai and start it normally (not with Run as administrator). If it still can't start, press Fix and restart.",+ body: storeCheck?.repairable+ ? "Close omnirush.ai and start it normally (not with Run as administrator). If it still can't start, press Fix and restart."+ : "Close omnirush.ai and start it normally (not with Run as administrator). If it still can't start, use Reset app data.",};}return {@@ -561,8 +563,8 @@ export function startFailureHint(category, { platform = process.platform, avHint? "Some of omnirush.ai's data files are marked read-only. Press Fix and restart: it clears the read-only mark and restarts omnirush.ai.": "Some of omnirush.ai's data files are read-only. Press Fix and restart: it makes them writable and restarts omnirush.ai."): (windows- ? "Windows refuses omnirush.ai write access to its data files. Press Fix and restart. If that doesn't help, use Reset app data: it moves the files to a backup folder (nothing is deleted) and restarts with fresh ones. Don't start omnirush.ai with Run as administrator."- : "omnirush.ai can't write its data files. Press Fix and restart. If that doesn't help, use Reset app data: it moves the files to a backup folder (nothing is deleted) and restarts with fresh ones."),+ ? "Windows refuses omnirush.ai write access to its data files. Use Reset app data: it moves the files to a backup folder (nothing is deleted) and restarts with fresh ones. Don't start omnirush.ai with Run as administrator."+ : "omnirush.ai can't write its data files. Use Reset app data: it moves the files to a backup folder (nothing is deleted) and restarts with fresh ones."),};}if (category === "store_error") {diff --git a/apps/desktop/electron/start-report.test.mjs b/apps/desktop/electron/start-report.test.mjsindex 774f60a6..6b817e40 100644--- a/apps/desktop/electron/start-report.test.mjs+++ b/apps/desktop/electron/start-report.test.mjs@@ -385,7 +385,8 @@ test("the read-only hint names the fix", () => {assert.match(plain.title, /can't write its local data/);assert.match(plain.body, /read-only.*Fix and restart/);const denied = startFailureHint("store_readonly", { platform: "win32", storeCheck: { repairable: false, elevated: false } });- assert.match(denied.body, /Reset app data/);+ assert.match(denied.body, /^Windows refuses.*Use Reset app data/);+ assert.doesNotMatch(denied.body, /Fix and restart/);assert.match(denied.body, /Run as administrator/);const admin = startFailureHint("store_readonly", { platform: "win32", storeCheck: { repairable: false, elevated: true } });assert.match(admin.title, /running as administrator/);diff --git a/apps/desktop/electron/updater.mjs b/apps/desktop/electron/updater.mjsindex 8837eaa0..645bbe1a 100644--- a/apps/desktop/electron/updater.mjs+++ b/apps/desktop/electron/updater.mjs@@ -1441,9 +1441,12 @@ export function registerUpdaterIpc({* and quits, or to null when nothing should install (no staged download, a* restart already installed it, or a newer release could not be fetched in* time: the stale download is then skipped and the next launch updates).- * Never rejects.+ * With `relaunch` (the app restarts itself: Fix and restart, Reset app+ * data) the install opens the new version when it is done, and the caller+ * must not app.relaunch() as well: the old exe would start while the+ * installer replaces it. Never rejects.*/- async function prepareInstallOnQuit() {+ async function prepareInstallOnQuit({ relaunch = false } = {}) {try {const updater = autoUpdaterInstance;if (!updater || !updateDownloaded || installTriggered) return null;@@ -1463,7 +1466,7 @@ export function registerUpdaterIpc({if (installMode === "appimage" || installMode === "mac-swap") {return () => {installTriggered = true;- void selfInstall(installMode, { relaunch: false })+ void selfInstall(installMode, { relaunch }).catch((error) => console.warn("[updater] install on quit failed", error?.message ?? error)).finally(() => quitApp());};@@ -1471,14 +1474,16 @@ export function registerUpdaterIpc({return () => {installTriggered = true;quitInstallInProgress = true;- // Quit means quit: install silently without relaunching.- updater.autoRunAppAfterInstall = false;+ // Quit means quit: install silently without relaunching, unless the+ // app is restarting itself; then the installer opens the new version.+ updater.autoRunAppAfterInstall = relaunch;setTimeout(() => quitApp(), quitInstallFallbackMs);try {allowQuit();- updater.quitAndInstall(true, false);+ updater.quitAndInstall(true, relaunch);} catch (error) {console.warn("[updater] install on quit failed", error?.message ?? error);+ if (relaunch) app.relaunch();quitApp();}};diff --git a/apps/desktop/electron/updater.test.mjs b/apps/desktop/electron/updater.test.mjsindex ab7e9449..5aeb1ec9 100644--- a/apps/desktop/electron/updater.test.mjs+++ b/apps/desktop/electron/updater.test.mjs@@ -1141,6 +1141,23 @@ describe("installing the newest published release", () => {}});+ it("a restart (Fix and restart, Reset app data) installs the staged update and lets the installer open the new version", async () => {+ const { tempDir, handlers, installs, updater, prepareInstallOnQuit } = await publishingFeedHarness({+ quitInstallFallbackMs: 0,+ });+ try {+ await handlers.get("omnirush:updater:check")(null, "stable");+ await handlers.get("omnirush:updater:download")();+ const installAndQuit = await prepareInstallOnQuit({ relaunch: true });+ assert.equal(typeof installAndQuit, "function");+ installAndQuit();+ assert.deepEqual(installs, [{ version: "2.2.1", isSilent: true, isForceRunAfter: true }]);+ assert.equal(updater.autoRunAppAfterInstall, true);+ } finally {+ await rm(tempDir, { recursive: true, force: true });+ }+ });+it("on quit, skips the stale download when the newer release cannot be fetched", async () => {const { tempDir, handlers, feed, installs, prepareInstallOnQuit } = await publishingFeedHarness();try {diff --git a/apps/server/src/runtime-db.ts b/apps/server/src/runtime-db.tsindex db9be4c3..1529f336 100644--- a/apps/server/src/runtime-db.ts+++ b/apps/server/src/runtime-db.ts@@ -95,12 +95,16 @@ export function isSqliteReadonlyError(error: unknown): boolean {* reading once rolls it back. Throws what that open threw (for instance when* the file itself cannot be written).*/+/** How long the rollback open waits for another connection's lock (a write in progress elsewhere). */+const ROLLBACK_BUSY_TIMEOUT_MS = 2_000;+export async function rollBackRuntimeSqliteJournal(path: string): Promise<void> {if (!existsSync(path)) return;if (typeof process.versions.bun === "string") {const { Database } = await import("bun:sqlite");const sqlite = new Database(path, { create: false, readwrite: true });try {+ sqlite.exec(`PRAGMA busy_timeout = ${ROLLBACK_BUSY_TIMEOUT_MS}`);sqlite.query("SELECT count(*) FROM sqlite_master").get();} finally {sqlite.close();@@ -110,6 +114,7 @@ export async function rollBackRuntimeSqliteJournal(path: string): Promise<void>const { DatabaseSync } = await importNodeSqlite();const sqlite = new DatabaseSync(path);try {+ sqlite.exec(`PRAGMA busy_timeout = ${ROLLBACK_BUSY_TIMEOUT_MS}`);sqlite.prepare("SELECT count(*) FROM sqlite_master").get();// The rollback ran if the connection could write; a file that is itself read-only opens read-only.sqlite.exec("BEGIN IMMEDIATE; ROLLBACK;");