A desktop coding agent with free access to frontier models.
TypeScript
feat: fix read-only data from start screen
Samrat Talukdar5dac0a53c455
diff --git a/apps/app/src/app/lib/desktop.ts b/apps/app/src/app/lib/desktop.tsindex 652b06e5..13a2a174 100644--- a/apps/app/src/app/lib/desktop.ts+++ b/apps/app/src/app/lib/desktop.ts@@ -143,6 +143,8 @@ export type StartFailureAnswer = {avHint: string;/** Reset app data also moves the engine's data (chats): only when its store failed. */resetIncludesChats?: boolean;+ /** The local databases cannot be written: offer "Fix and restart". */+ canRepairStore?: boolean;hint: { title: string; body: string } | null;};@@ -230,6 +232,7 @@ declare global {startup?: {reportFailure?: (input: { message?: string | null }) => Promise<StartFailureAnswer>;resetAppData?: () => Promise<{ ok: boolean; backupDir?: string }>;+ repairStore?: () => Promise<{ ok: boolean; fixed: number; failed: number }>;};nuke?: {preview?: (options?: NukeOptions) => Promise<NukeManifestPreview>;diff --git a/apps/app/src/react-app/shell/loading-overlay.tsx b/apps/app/src/react-app/shell/loading-overlay.tsxindex 9a401784..9c5ac754 100644--- a/apps/app/src/react-app/shell/loading-overlay.tsx+++ b/apps/app/src/react-app/shell/loading-overlay.tsx@@ -117,6 +117,7 @@ export function LoadingOverlay() {const useRelease = window.__OMNIRUSH_ELECTRON__?.recovery?.use;const resetAppData = window.__OMNIRUSH_ELECTRON__?.startup?.resetAppData;+ const repairStore = failureAnswer?.canRepairStore ? window.__OMNIRUSH_ELECTRON__?.startup?.repairStore : undefined;const hint = failureAnswer?.hint ?? null;if (!visible || (suppressForGateway && !error)) return null;@@ -144,9 +145,28 @@ export function LoadingOverlay() {) : (<div className="text-dls-secondary">Try again. If it keeps failing, return to a version that works on this computer.</div>)}+ {repairStore ? (+ <button+ type="button"+ className="rounded-md bg-dls-accent px-3 py-2 font-medium text-dls-accent-foreground"+ data-testid="start-failure-repair-store"+ onClick={() => {+ setActionState("Fixing access to omnirush.ai's local data and restarting…");+ void repairStore()+ .then((result) => {+ if (!result.ok) setActionState("Some files could not be changed. Restarting anyway; if it still can't start, use Reset app data.");+ })+ .catch(() => setActionState("The fix could not be started. Use Reset app data."));+ }}+ >+ Fix and restart+ </button>+ ) : null}<buttontype="button"- className="rounded-md bg-dls-accent px-3 py-2 font-medium text-dls-accent-foreground"+ className={repairStore+ ? "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-dls-accent-foreground"}onClick={() => window.location.reload()}>Try againdiff --git a/apps/app/tests/start-failure-repair.test.tsx b/apps/app/tests/start-failure-repair.test.tsxnew file mode 100644index 00000000..a3e0657f--- /dev/null+++ b/apps/app/tests/start-failure-repair.test.tsx@@ -0,0 +1,68 @@+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: Fix and restart clears the marks and restarts", 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: 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-hint]")?.textContent).toContain("can't write its local data");+ const fix = container.querySelector("[data-testid=start-failure-repair-store]");+ expect(fix?.textContent).toBe("Fix and restart");+ await act(async () => {+ fix?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+ expect(repairStore).toHaveBeenCalledTimes(1);+ expect(container.textContent).toContain("restarting");+ expect([...container.querySelectorAll("button")].some((button) => button.textContent === "Reset app data")).toBe(true);+ } 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 c769c818..da5f990a 100644--- a/apps/desktop/electron/main.mjs+++ b/apps/desktop/electron/main.mjs@@ -56,6 +56,7 @@ import {scheduleStartRestore,startResetTargets,} from "./start-reset.mjs";+import { checkStoreAccess, repairStoreAccess, storeFiles } from "./start-store-check.mjs";import { createTerminalSessions, terminalShells } from "./terminal-sessions.mjs";import {buildNukeManifest,@@ -1500,6 +1501,10 @@ function startReportScrubRoots() {return roots;}+function startStoreFiles() {+ return storeFiles({ userDataPath: app.getPath("userData"), env: process.env, homedir: os.homedir() });+}+/*** The window shows "couldn't start": classify the attempt's error (or the* window's message when the main process saw none), send one report for@@ -1541,9 +1546,24 @@ async function reportStartFailure(input = {}) {attempt: failure.attempt,};const category = buildStartFailureReport(draft).category;+ // Which store files cannot be written, and whether this start runs elevated (start-store-check.mjs).+ const storeCheck = category === "store_readonly" || category === "store_error"+ ? await checkStoreAccess({ files: startStoreFiles() }).catch(() => null)+ : null;+ const engineStoreFailed = classified.phase === "engine_ready" || storeCheck?.blockedStores.includes("engine") === true;// Reset app data moves the engine's data (chats, sessions not yet uploaded) only when its store failed.- const resetIncludesChats = category === "store_error" && classified.phase === "engine_ready";- const answer = { category, avHint, resetIncludesChats, hint: startFailureHint(category, { avHint }) };+ const resetIncludesChats = (category === "store_error" || category === "store_readonly") && engineStoreFailed;+ const answer = {+ category,+ avHint,+ resetIncludesChats,+ // "Fix and restart": clear read-only marks on the store files, then restart.+ canRepairStore: category === "store_readonly",+ hint: startFailureHint(category, { avHint, storeCheck }),+ };+ if (storeCheck) {+ console.info(`[start-report] store check: blocked=${storeCheck.blockedStores.join(",") || "none"} read-only=${storeCheck.runtime.readOnlyFlags + storeCheck.engine.readOnlyFlags} not-writable=${storeCheck.runtime.notWritable + storeCheck.engine.notWritable} hot-journal=${storeCheck.runtime.hotJournal} elevated=${storeCheck.elevated}`);+ }reportedStart = { attempt: failure.attempt, answer };void (async () => {const outcome = await startReporter.report(buildStartFailureReport(draft));@@ -2113,6 +2133,17 @@ const desktopCommandHandlers = {"startupReportFailure": async (event, ...args) => {return reportStartFailure(args[0] ?? {});},+ "startupRepairStore": async () => {+ 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?.();+ return { ok: result.failed === 0, ...result };+ },"startupResetAppData": async () => {const { backupDir } = await scheduleStartReset({userDataPath: app.getPath("userData"),diff --git a/apps/desktop/electron/preload.mjs b/apps/desktop/electron/preload.mjsindex 91d39ec7..e3b99791 100644--- a/apps/desktop/electron/preload.mjs+++ b/apps/desktop/electron/preload.mjs@@ -141,6 +141,10 @@ contextBridge.exposeInMainWorld("__OMNIRUSH_ELECTRON__", {reportFailure(input) {return ipcRenderer.invoke("omnirush:desktop", "startupReportFailure", input ?? {});},+ /** Clear read-only marks on the local databases, then restart. */+ repairStore() {+ return ipcRenderer.invoke("omnirush:desktop", "startupRepairStore");+ },/** Move the local start state into a backup folder on restart, then restart. */resetAppData() {return ipcRenderer.invoke("omnirush:desktop", "startupResetAppData");diff --git a/apps/desktop/electron/start-report.mjs b/apps/desktop/electron/start-report.mjsindex 9d4b044a..4c910525 100644--- a/apps/desktop/electron/start-report.mjs+++ b/apps/desktop/electron/start-report.mjs@@ -32,8 +32,10 @@ export const START_FAILURE_CATEGORIES = ["unknown", "engine_missing", "engine_blocked", "engine_modified", "engine_timeout","engine_exit", "engine_crash", "engine_cpu_unsupported", "engine_stuck","config_incompatible", "config_invalid", "workspace_inaccessible", "port_in_use",- "store_error", "disk_full", "server_bundle_missing", "server_not_ready", "renderer",+ "store_error", "store_readonly", "disk_full", "server_bundle_missing", "server_not_ready", "renderer",];+/** Categories a server older than them refuses (HTTP 422): sent again as the older one. */+const LEGACY_CATEGORIES = { store_readonly: "store_error" };const ERROR_NAMES = new Set(["Error", "TypeError", "ReferenceError", "SyntaxError", "RangeError",@@ -54,7 +56,82 @@ const STATUS_ILLEGAL_INSTRUCTION = 0xc000001d;// Win32 ERROR_VIRUS_INFECTED / ERROR_VIRUS_DELETED.const VIRUS_CODES = new Set([225, 226]);-const SQLITE_PATTERN = /\b(SQLITE_[A-Z]+)\b|database disk image is malformed|file is not a database|database is locked/;+const SQLITE_PATTERN = /\b(SQLITE_[A-Z]+)\b|database disk image is malformed|file is not a database|database is locked|attempt to write a readonly database|unable to open database file|disk I\/O error/;++/** SQLite's primary result codes the report names (node:sqlite: `errcode`, extended codes in the high bits). */+const SQLITE_PRIMARY = {+ 5: "SQLITE_BUSY", 6: "SQLITE_BUSY", 8: "SQLITE_READONLY", 10: "SQLITE_IOERR", 11: "SQLITE_CORRUPT",+ 13: "SQLITE_FULL", 14: "SQLITE_CANTOPEN", 26: "SQLITE_NOTADB",+};+const SQLITE_MESSAGES = [+ [/attempt to write a readonly database/i, "SQLITE_READONLY"],+ [/database disk image is malformed/i, "SQLITE_CORRUPT"],+ [/file is not a database/i, "SQLITE_NOTADB"],+ [/database (?:table )?is locked/i, "SQLITE_BUSY"],+ [/unable to open database file/i, "SQLITE_CANTOPEN"],+ [/disk I\/O error/i, "SQLITE_IOERR"],+ [/database or disk is full/i, "SQLITE_FULL"],+];++/** The SQLite code an error or text carries (SQLITE_READONLY, ...), else null. */+export function sqliteCodeOf(error, text = messageOf(error)) {+ const errcode = error && typeof error === "object" ? error.errcode : undefined;+ if (Number.isInteger(errcode) && SQLITE_PRIMARY[errcode & 0xff]) return SQLITE_PRIMARY[errcode & 0xff];+ const code = typeof error?.code === "string" ? error.code : "";+ const named = `${code} ${text}`.match(/\bSQLITE_([A-Z]+)/);+ if (named) {+ const primary = `SQLITE_${named[1]}`;+ if (ERROR_CODES.has(primary)) return primary;+ const base = Object.values(SQLITE_PRIMARY).find((value) => primary.startsWith(`${value}_`));+ if (base) return base;+ }+ for (const [pattern, value] of SQLITE_MESSAGES) if (pattern.test(text)) return value;+ return null;+}++// Terminal colours the engine prints around its error banner.+const ANSI = /\u001b\[[0-9;?]*[ -\/]*[@-~]/g;++function stripAnsi(text) {+ return String(text ?? "").replace(ANSI, "");+}++/**+ * The engine's own error line from its exit output: the line after its+ * "Error: Unexpected error" banner (the engine prints the thrown message+ * there), else the first line that reads like an error. Null when none.+ */+export function engineErrorLine(message) {+ const lines = stripAnsi(message).split(/\r?\n/).map((line) => line.trim()).filter(Boolean);+ if (!/exited with code/.test(lines[0] ?? "")) return null;+ const rest = lines.slice(1);+ const banner = rest.findIndex((line) => /^(?:Error:\s*)?Unexpected error\b/i.test(line));+ if (banner >= 0) return rest.slice(banner + 1).find((line) => !/^at\s/.test(line)) ?? null;+ return rest.find((line) => /error|lacks|illegal|EADDRINUSE|SQLITE|denied|permission|readonly|database|EPERM|EACCES|EBUSY|ENOENT/i.test(line)) ?? rest[0] ?? null;+}++/**+ * What kind of error the engine's line is: an impersonal enum the report+ * carries next to the scrubbed line.+ */+export function engineErrorKind(line) {+ const text = String(line ?? "");+ if (!text) return "none";+ const sqlite = sqliteCodeOf(null, text);+ if (sqlite) return sqlite.toLowerCase();+ if (/migrat/i.test(text)) return "migration";+ if (/\bEPERM\b|operation not permitted/i.test(text)) return "eperm";+ if (/\bEACCES\b|permission denied|access is denied/i.test(text)) return "eacces";+ if (/\bEBUSY\b|resource busy|being used by another process/i.test(text)) return "ebusy";+ if (/\bENOENT\b|no such file/i.test(text)) return "enoent";+ if (/\bENOSPC\b|no space left/i.test(text)) return "enospc";+ if (/JSON|Unexpected token|parse/i.test(text)) return "json";+ if (/config/i.test(text)) return "config";+ if (/plugin|npm|install/i.test(text)) return "plugin";+ if (/\bE(?:CONNREFUSED|CONNRESET|TIMEDOUT|NOTFOUND|AI_AGAIN)\b|fetch failed|network/i.test(text)) return "network";+ if (/is not a function|undefined is not|cannot read propert|null is not/i.test(text)) return "internal";+ return "other";+}function innermost(error) {let current = error;@@ -103,12 +180,15 @@ export function classifyStartFailure(rawError, { fallbackPhase = "unknown" } = {const exitCode = exitCodeOf(error, message);const status = unsigned(exitCode);const signal = typeof error?.signal === "string" && /^SIG[A-Z0-9]{2,10}$/.test(error.signal) ? error.signal : null;- const sqlite = message.match(SQLITE_PATTERN);+ const plain = stripAnsi(message);+ const engineLine = engineErrorLine(plain);+ const sqliteCode = sqliteCodeOf(error, engineLine ?? plain);+ const sqlite = sqliteCode || SQLITE_PATTERN.test(plain) ? [null, sqliteCode] : null;const result = {category: "unknown",phase: fallbackPhase,errorName: name && ERROR_NAMES.has(name) ? name : (rawError instanceof Error ? "Error" : "none"),- errorCode: knownCode(code),+ errorCode: knownCode(code) ?? (code === "ERR_SQLITE_ERROR" ? sqliteCode : null),exitCode: Number.isInteger(exitCode) ? exitCode : null,signal,avHint: "none",@@ -144,6 +224,7 @@ export function classifyStartFailure(rawError, { fallbackPhase = "unknown" } = {if (/ConfigJsonError|ConfigInvalidError|configuration is invalid|JSON Parse error/i.test(message)) {return set("config_invalid", "engine_ready");}+ if (sqliteCode === "SQLITE_READONLY") return set("store_readonly", "engine_ready", { errorCode: "SQLITE_READONLY" });if (sqlite) return set("store_error", "engine_ready", { errorCode: knownCode(sqlite[1]) ?? result.errorCode });if ((status !== null && status >= 0xc0000000) || signal) return set("engine_crash", "engine_ready");return set("engine_exit", "engine_ready");@@ -154,6 +235,7 @@ export function classifyStartFailure(rawError, { fallbackPhase = "unknown" } = {if (/did not stay running|did not report a base URL|did not report an access token|did not finish starting/i.test(message)) {return set("server_not_ready", "server_ready");}+ if (sqliteCode === "SQLITE_READONLY") return set("store_readonly", "server", { errorCode: "SQLITE_READONLY" });if (sqlite) return set("store_error", "server", { errorCode: knownCode(sqlite[1]) ?? result.errorCode });return result;}@@ -189,7 +271,7 @@ const IPV6 = /(?:\b[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{0,4}){3,7}\b|\b[0-9A-Fa-f]{1,* @param {{ roots?: Array<string | undefined>; userName?: string; hostName?: string; category?: string }} [options]*/export function scrubStartMessage(rawError, { roots = [], userName = "", hostName = "", category = "" } = {}) {- const message = messageOf(innermost(rawError));+ const message = stripAnsi(messageOf(innermost(rawError)));if (!message.trim()) return null;if (category === "config_invalid" || category === "config_incompatible") {const errorName = innermost(rawError) instanceof Error ? innermost(rawError).name : "";@@ -198,8 +280,14 @@ export function scrubStartMessage(rawError, { roots = [], userName = "", hostNam}const lines = message.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);const picked = [lines[0]];- const diagnostic = lines.slice(1).find((line) => /error|lacks|illegal|EADDRINUSE|SQLITE|denied|permission/i.test(line));- if (diagnostic) picked.push(diagnostic);+ // An engine exit: its own error line (after the "Unexpected error" banner) and what kind it is.+ const engineLine = engineErrorLine(message);+ if (engineLine) {+ picked.push(`engine_error=${engineErrorKind(engineLine)}`, engineLine);+ } else {+ const diagnostic = lines.slice(1).find((line) => /error|lacks|illegal|EADDRINUSE|SQLITE|denied|permission|readonly/i.test(line));+ if (diagnostic) picked.push(diagnostic);+ }let text = picked.join(" | ");const knownRoots = [...new Set(roots.filter((root) => typeof root === "string" && root.trim().length >= 3))].sort((left, right) => right.length - left.length);@@ -403,7 +491,7 @@ export function buildStartFailureReport({}/** What the start screen tells the user for a category (null: the generic text). */-export function startFailureHint(category, { platform = process.platform, avHint = "none" } = {}) {+export function startFailureHint(category, { platform = process.platform, avHint = "none", storeCheck = null } = {}) {const windows = platform === "win32";if (category === "engine_missing" || avHint === "binary_missing") {return {@@ -455,6 +543,24 @@ export function startFailureHint(category, { platform = process.platform, avHint: "It may be on a disconnected drive or no longer exist. Reconnect it, or use Reset app data.",};}+ if (category === "store_readonly") {+ if (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.",+ };+ }+ return {+ title: "omnirush.ai can't write its local data",+ body: storeCheck?.repairable+ ? (windows+ ? "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."),+ };+ }if (category === "store_error") {return {title: "omnirush.ai's local data is damaged",@@ -538,6 +644,9 @@ export function createStartReporter({ filePath, send, now = Date.now, maxPerDay}if (!response) return "retry";if (response.ok) return "sent";+ if (response.status === 422 && LEGACY_CATEGORIES[body?.category]) {+ return deliver({ ...body, category: LEGACY_CATEGORIES[body.category] });+ }if (response.status === 401 || response.status === 408 || response.status >= 500) return "retry";return "drop";}diff --git a/apps/desktop/electron/start-report.test.mjs b/apps/desktop/electron/start-report.test.mjsindex c6a2c65a..9bb26da5 100644--- a/apps/desktop/electron/start-report.test.mjs+++ b/apps/desktop/electron/start-report.test.mjs@@ -14,7 +14,10 @@ import {osBuild,profileFlags,reportVersion,+ engineErrorKind,+ engineErrorLine,scrubStartMessage,+ sqliteCodeOf,startFailureHint,} from "./start-report.mjs";@@ -95,7 +98,7 @@ test("messages keep no paths, names, addresses or tokens", () => {}assert.equal(scrubStartMessage(spawnError("ENOENT"), { roots }), "spawn <path>");assert.equal(scrubStartMessage(new Error(" ")), null);- assert.match(scrubStartMessage(exitError(1, "line two\nerror: database is locked")), /exited with code 1 \| error: database is locked/);+ assert.match(scrubStartMessage(exitError(1, "line two\nerror: database is locked")), /exited with code 1 \| engine_error=sqlite_busy \| error: database is locked/);});// The server's last check (omnirush/crash_reports.py _PERSONAL): a message@@ -315,3 +318,83 @@ test("reporter: once sent, queued while signed out, capped per day, flushed lateconst failing = createStartReporter({ filePath: path.join(dir, "other.json"), send: async () => { throw new TypeError("fetch failed"); } });assert.equal(await failing.report(body("g")), "queued");});++/** node:sqlite's error for a write to a read-only file, or a read-only read that met a hot journal (776). */+function nodeSqliteError(errcode, errstr) {+ return Object.assign(new Error(errstr), { code: "ERR_SQLITE_ERROR", errcode, errstr });+}++test("a read-only store is its own category, in the server and in the engine", () => {+ // The 3.5.4 reports: phase/category "unknown", error_code null.+ for (const errcode of [8, 776, 1032]) {+ const result = classifyStartFailure(nodeSqliteError(errcode, "attempt to write a readonly database"));+ assert.deepEqual(+ { category: result.category, phase: result.phase, errorCode: result.errorCode },+ { category: "store_readonly", phase: "server", errorCode: "SQLITE_READONLY" },+ );+ }+ const tagged = Object.assign(new Error("attempt to write a readonly database (runtime store)"), { code: "SQLITE_READONLY" });+ assert.equal(classifyStartFailure(tagged).category, "store_readonly");+ // Only the text left (the window's message): still recognised.+ assert.equal(classifyStartFailure(new Error("attempt to write a readonly database")).category, "store_readonly");+ const engine = exitError(1, "\u001b[91m\u001b[1mError: \u001b[0mUnexpected error\nattempt to write a readonly database");+ assert.deepEqual(+ (({ category, phase, errorCode }) => ({ category, phase, errorCode }))(classifyStartFailure(engine)),+ { category: "store_readonly", phase: "engine_ready", errorCode: "SQLITE_READONLY" },+ );+ assert.equal(classifyStartFailure(nodeSqliteError(5, "database is locked")).errorCode, "SQLITE_BUSY");+ assert.equal(classifyStartFailure(nodeSqliteError(11, "database disk image is malformed")).category, "store_error");+ assert.equal(sqliteCodeOf(null, "SQLiteError: SQLITE_READONLY_ROLLBACK"), "SQLITE_READONLY");+ assert.equal(sqliteCodeOf(null, "nothing"), null);+});++test("an engine exit keeps the engine's own error line and its kind", () => {+ // Report B: the banner was kept and the engine's line after it was lost.+ const banner = "\u001b[91m\u001b[1mError: \u001b[0mUnexpected error";+ const cases = [+ ["attempt to write a readonly database", "sqlite_readonly"],+ ["database is locked", "sqlite_busy"],+ ["EPERM: operation not permitted, rename 'C:\\Users\\Ana\\AppData\\Roaming\\ai.omnirush.desktop\\engine-data\\omnirush\\x.tmp'", "eperm"],+ ["Migration 20260101_session failed", "migration"],+ ["JSON Parse error: Unexpected EOF", "json"],+ ["undefined is not an object (evaluating 'x.y')", "internal"],+ ["something unusual", "other"],+ ];+ for (const [line, kind] of cases) {+ const error = exitError(1, `${banner}\n${line}\n at foo (C:\\x\\y.js:1:2)`);+ assert.equal(engineErrorLine(error.message), line);+ assert.equal(engineErrorKind(line), kind);+ const text = scrubStartMessage(error, { roots: ["C:\\Users\\Ana"], userName: "Ana" });+ assert.ok(text.startsWith(`OmniRush server exited with code 1 | engine_error=${kind} | `), text);+ assert.doesNotMatch(text, /\u001b|Unexpected error|Ana|\\/, text);+ assert.doesNotMatch(text, SERVER_DROP, text);+ }+ assert.equal(engineErrorLine("boom"), null);+ assert.equal(engineErrorKind(null), "none");+});++test("the read-only hint names the fix", () => {+ const plain = startFailureHint("store_readonly", { platform: "win32", storeCheck: { repairable: true, elevated: false } });+ 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, /Run as administrator/);+ const admin = startFailureHint("store_readonly", { platform: "win32", storeCheck: { repairable: false, elevated: true } });+ assert.match(admin.title, /running as administrator/);+ assert.ok(startFailureHint("store_readonly", { platform: "linux" }));+});++test("a server that does not know store_readonly gets store_error", async () => {+ const dir = await mkdtemp(path.join(os.tmpdir(), "start-report-legacy-"));+ const sent = [];+ const reporter = createStartReporter({+ filePath: path.join(dir, "start-reports.json"),+ send: async (body) => {+ sent.push(body.category);+ return body.category === "store_readonly" ? { ok: false, status: 422 } : { ok: true, status: 200 };+ },+ });+ assert.equal(await reporter.report({ category: "store_readonly", occurred_at: new Date().toISOString() }), "sent");+ assert.deepEqual(sent, ["store_readonly", "store_error"]);+});diff --git a/apps/desktop/electron/start-reset.mjs b/apps/desktop/electron/start-reset.mjsindex cf2c54b9..8bc5a218 100644--- a/apps/desktop/electron/start-reset.mjs+++ b/apps/desktop/electron/start-reset.mjs@@ -7,7 +7,7 @@* history and sessions not yet uploaded) stays too, unless the failure* points at the engine's store.*- * Files that belong together (runtime.sqlite with its -wal/-shm) move all+ * Files that belong together (runtime.sqlite with its -journal/-wal/-shm) move all* together or not at all. "Restore previous app data" moves a backup back.** Both happen on the next launch, before anything opens those files@@ -51,7 +51,8 @@ export function startResetTargets({ userDataPath, env = process.env, homedir, plconfig("server.json"),{label: "config/runtime.sqlite",- paths: ["runtime.sqlite", "runtime.sqlite-wal", "runtime.sqlite-shm"].map((name) => path.join(configDir, name)),+ // The journal too: a hot one left next to a fresh store would be played into it.+ paths: ["runtime.sqlite", "runtime.sqlite-journal", "runtime.sqlite-wal", "runtime.sqlite-shm"].map((name) => path.join(configDir, name)),},config("runtime-opencode-config.json"),config("engine-instances.json"),diff --git a/apps/desktop/electron/start-reset.test.mjs b/apps/desktop/electron/start-reset.test.mjsindex e6a95cdc..6d3516b5 100644--- a/apps/desktop/electron/start-reset.test.mjs+++ b/apps/desktop/electron/start-reset.test.mjs@@ -27,6 +27,7 @@ async function fixture() {await writeFile(path.join(configDir, "server.json"), "{}");await writeFile(path.join(configDir, "runtime.sqlite"), "sqlite");await writeFile(path.join(configDir, "runtime.sqlite-wal"), "wal");+ await writeFile(path.join(configDir, "runtime.sqlite-journal"), "journal");await writeFile(path.join(configDir, "runtime.sqlite-shm"), "shm");await writeFile(path.join(configDir, "env.json"), "{}");const env = { OMNIRUSH_SERVER_CONFIG: path.join(configDir, "server.json") };@@ -44,7 +45,7 @@ test("targets: start state only; engine data only when asked; the runtime databaassert.ok(all.includes(path.join(configDir, "server.json")));assert.ok(!all.some((entry) => /engine-data|omnirush-account|env\.json|private-credentials/.test(entry)));assert.deepEqual(plain.find((target) => target.label === "config/runtime.sqlite").paths.map((entry) => path.basename(entry)),- ["runtime.sqlite", "runtime.sqlite-wal", "runtime.sqlite-shm"]);+ ["runtime.sqlite", "runtime.sqlite-journal", "runtime.sqlite-wal", "runtime.sqlite-shm"]);assert.ok(targetsFor({ includeEngineData: true }).some((target) => target.label === "app/engine-data"));});@@ -63,6 +64,8 @@ test("a reset moves the start state into the announced backup folder and keeps cassert.deepEqual(result.failed, []);assert.deepEqual(new Set(result.moved), new Set(["app/omnirush-workspaces.json", "config/server.json", "config/runtime.sqlite"]));assert.equal(await readFile(path.join(backupDir, "config", "runtime.sqlite-wal"), "utf8"), "wal");+ assert.equal(await readFile(path.join(backupDir, "config", "runtime.sqlite-journal"), "utf8"), "journal");+ assert.ok(!existsSync(path.join(configDir, "runtime.sqlite-journal")));assert.ok(!existsSync(path.join(configDir, "runtime.sqlite")));assert.equal(await readFile(path.join(userDataPath, "engine-data", "omnirush", "opencode.db"), "utf8"), "chats");assert.ok(existsSync(path.join(userDataPath, "omnirush-account.bin")));diff --git a/apps/desktop/electron/start-store-check.mjs b/apps/desktop/electron/start-store-check.mjsnew file mode 100644index 00000000..84ebb651--- /dev/null+++ b/apps/desktop/electron/start-store-check.mjs@@ -0,0 +1,161 @@+/**+ * Whether omnirush.ai can write its local databases, for the couldn't-start+ * screen: the runtime store (`<config>/runtime.sqlite`, the embedded+ * server's) and the engine's store (`<userData>/engine-data/omnirush/+ * opencode.db`), each with its journal files.+ *+ * SQLite opens a file it cannot write read-only without saying so, and the+ * first write then fails with "attempt to write a readonly database". On+ * Windows that is a file with the read-only attribute set, or one whose+ * permissions do not let this user write it (copied or restored from+ * elsewhere, made by another account). Files an elevated ("Run as+ * administrator") start creates inherit the folder's permissions and stay+ * writable; the elevated flag is still reported so the screen can say not+ * to start omnirush.ai that way.+ *+ * Nothing here leaves the computer: the report keeps only the category.+ */+import { execFile } from "node:child_process";+import { chmod, open, stat } from "node:fs/promises";+import path from "node:path";+import { omnirushConfigDir } from "@omnirush/paths";++const SUFFIXES = ["", "-journal", "-wal", "-shm"];++/**+ * The store files, by store.+ *+ * @param {{ userDataPath: string; env?: NodeJS.ProcessEnv; homedir?: string; platform?: NodeJS.Platform }} options+ * @returns {{ runtime: string[]; engine: string[] }}+ */+export function storeFiles({ userDataPath, env = process.env, homedir, platform = process.platform }) {+ const configDir = omnirushConfigDir({ env, homeDir: homedir, platform });+ const runtimeDb = String(env.OMNIRUSH_RUNTIME_DB ?? "").trim() || path.join(configDir, "runtime.sqlite");+ const engineDb = path.join(userDataPath, "engine-data", "omnirush", "opencode.db");+ return {+ runtime: SUFFIXES.map((suffix) => `${runtimeDb}${suffix}`),+ engine: SUFFIXES.map((suffix) => `${engineDb}${suffix}`),+ };+}++/**+ * One file: absent, or present with its read-only flag (Windows' read-only+ * attribute shows as no write bit) and whether opening it for writing works.+ */+async function checkFile(file, { openImpl = open, statImpl = stat } = {}) {+ let info;+ try {+ info = await statImpl(file);+ } catch {+ return { present: false, readOnlyFlag: false, writable: true, code: null };+ }+ if (!info.isFile()) return { present: false, readOnlyFlag: false, writable: true, code: null };+ const readOnlyFlag = (info.mode & 0o222) === 0;+ let handle = null;+ try {+ handle = await openImpl(file, "r+");+ return { present: true, readOnlyFlag, writable: true, code: null };+ } catch (error) {+ const code = typeof error?.code === "string" ? error.code : "UNKNOWN";+ // EBUSY: another program holds it without sharing (rare for SQLite files).+ return { present: true, readOnlyFlag, writable: false, code };+ } finally {+ await handle?.close().catch(() => undefined);+ }+}++/**+ * @param {string[]} files+ * @param {{ openImpl?: typeof open; statImpl?: typeof stat }} [impl]+ */+async function checkStore(files, impl) {+ const checks = await Promise.all(files.map((file) => checkFile(file, impl)));+ const present = checks.filter((check) => check.present);+ return {+ present: present.length > 0,+ readOnlyFlags: present.filter((check) => check.readOnlyFlag).length,+ notWritable: present.filter((check) => !check.writable).length,+ hotJournal: checks[1]?.present === true,+ codes: [...new Set(present.map((check) => check.code).filter(Boolean))],+ };+}++/**+ * Is this process elevated (Windows: an administrator token, "Run as+ * administrator"; elsewhere: root)? Windows asks `whoami /groups` for the+ * High (S-1-16-12288) or System (S-1-16-16384) integrity label. Null when+ * that cannot be told.+ *+ * @param {{ platform?: NodeJS.Platform; run?: (file: string, args: string[]) => Promise<string>; getuid?: () => number }} [options]+ */+export async function isElevated({ platform = process.platform, run = runText, getuid = process.getuid?.bind(process) } = {}) {+ if (platform !== "win32") return typeof getuid === "function" ? getuid() === 0 : null;+ try {+ const output = await run("whoami", ["/groups", "/fo", "csv", "/nh"]);+ if (/S-1-16-(?:12288|16384)\b/.test(output)) return true;+ if (/S-1-16-\d+/.test(output)) return false;+ return null;+ } catch {+ return null;+ }+}++function runText(file, args) {+ return new Promise((resolve, reject) => {+ execFile(file, args, { windowsHide: true, timeout: 5_000, maxBuffer: 1 << 20 }, (error, stdout) => {+ if (error) reject(error);+ else resolve(String(stdout));+ });+ });+}++/**+ * What stops omnirush.ai writing its stores.+ *+ * @param {{ files: { runtime: string[]; engine: string[] }; elevated?: () => Promise<boolean | null>; openImpl?: typeof open; statImpl?: typeof stat }} options+ */+export async function checkStoreAccess({ files, elevated = () => isElevated(), openImpl, statImpl }) {+ const impl = { openImpl, statImpl };+ const [runtime, engine, admin] = await Promise.all([+ checkStore(files.runtime, impl),+ checkStore(files.engine, impl),+ elevated().catch(() => null),+ ]);+ const blocked = (store) => store.readOnlyFlags > 0 || store.notWritable > 0;+ return {+ runtime,+ engine,+ elevated: admin,+ /** Stores with a file that is read-only or cannot be opened for writing. */+ blockedStores: [blocked(runtime) ? "runtime" : null, blocked(engine) ? "engine" : null].filter(Boolean),+ /** Clearing the read-only flag can fix it in place. */+ repairable: runtime.readOnlyFlags + engine.readOnlyFlags > 0,+ };+}++/**+ * Clear the read-only flag (Windows: the read-only attribute) of every store+ * file that has it. Never throws; returns how many were fixed and failed.+ *+ * @param {{ files: { runtime: string[]; engine: string[] }; chmodImpl?: typeof chmod; statImpl?: typeof stat }} options+ */+export async function repairStoreAccess({ files, chmodImpl = chmod, statImpl = stat }) {+ let fixed = 0;+ let failed = 0;+ for (const file of [...files.runtime, ...files.engine]) {+ let info;+ try {+ info = await statImpl(file);+ } catch {+ continue;+ }+ if (!info.isFile() || (info.mode & 0o200) !== 0) continue;+ try {+ await chmodImpl(file, (info.mode & 0o777) | 0o600);+ fixed += 1;+ } catch {+ failed += 1;+ }+ }+ return { fixed, failed };+}diff --git a/apps/desktop/electron/start-store-check.test.mjs b/apps/desktop/electron/start-store-check.test.mjsnew file mode 100644index 00000000..b992157e--- /dev/null+++ b/apps/desktop/electron/start-store-check.test.mjs@@ -0,0 +1,91 @@+import assert from "node:assert/strict";+import { chmod, mkdir, mkdtemp, rm, stat, writeFile } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import test from "node:test";++import { checkStoreAccess, isElevated, repairStoreAccess, storeFiles } from "./start-store-check.mjs";++async function fixture() {+ const root = await mkdtemp(path.join(os.tmpdir(), "start-store-check-"));+ const userDataPath = path.join(root, "ai.omnirush.desktop");+ const configDir = path.join(root, "omnirush");+ await mkdir(path.join(userDataPath, "engine-data", "omnirush"), { recursive: true });+ await mkdir(configDir, { recursive: true });+ const env = { OMNIRUSH_SERVER_CONFIG: path.join(configDir, "server.json") };+ const files = storeFiles({ userDataPath, env, homedir: root });+ return { root, configDir, userDataPath, files };+}++test("store files: the runtime store and the engine's, each with its journal files", async () => {+ const { root, configDir, userDataPath, files } = await fixture();+ try {+ assert.deepEqual(files.runtime.map((file) => path.relative(configDir, file)), [+ "runtime.sqlite", "runtime.sqlite-journal", "runtime.sqlite-wal", "runtime.sqlite-shm",+ ]);+ assert.equal(path.relative(userDataPath, files.engine[0]), path.join("engine-data", "omnirush", "opencode.db"));+ assert.equal(files.engine.length, 4);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});++test("a read-only store file is found and Fix clears it", async (t) => {+ if (process.platform !== "win32" && process.getuid?.() === 0) {+ t.skip("root opens read-only files for writing");+ return;+ }+ const { root, files } = await fixture();+ try {+ await writeFile(files.runtime[0], "db");+ await writeFile(files.runtime[1], "journal");+ await writeFile(files.engine[0], "db");+ await chmod(files.runtime[0], 0o444);+ await chmod(files.runtime[1], 0o444);++ const before = await checkStoreAccess({ files, elevated: async () => false });+ assert.deepEqual(before.blockedStores, ["runtime"]);+ assert.equal(before.runtime.readOnlyFlags, 2);+ assert.equal(before.runtime.notWritable, 2);+ assert.equal(before.runtime.hotJournal, true);+ assert.equal(before.engine.readOnlyFlags, 0);+ assert.equal(before.repairable, true);+ assert.equal(before.elevated, false);++ assert.deepEqual(await repairStoreAccess({ files }), { fixed: 2, failed: 0 });+ assert.ok(((await stat(files.runtime[0])).mode & 0o200) !== 0);+ const after = await checkStoreAccess({ files, elevated: async () => null });+ assert.deepEqual(after.blockedStores, []);+ assert.equal(after.repairable, false);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});++test("a store file that cannot be opened for writing without a read-only mark: blocked, not repairable", async () => {+ const { root, files } = await fixture();+ try {+ await writeFile(files.engine[0], "db");+ const denied = async () => {+ throw Object.assign(new Error("EPERM"), { code: "EPERM" });+ };+ const result = await checkStoreAccess({ files, elevated: async () => true, openImpl: denied });+ assert.deepEqual(result.blockedStores, ["engine"]);+ assert.deepEqual(result.engine.codes, ["EPERM"]);+ assert.equal(result.repairable, false);+ assert.equal(result.elevated, true);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});++test("elevated: Windows integrity label from whoami, root elsewhere", async () => {+ const high = "\"Mandatory Label\\High Mandatory Level\",\"Label\",\"S-1-16-12288\",\"\"";+ const medium = "\"Mandatory Label\\Medium Mandatory Level\",\"Label\",\"S-1-16-8192\",\"\"";+ assert.equal(await isElevated({ platform: "win32", run: async () => high }), true);+ assert.equal(await isElevated({ platform: "win32", run: async () => medium }), false);+ assert.equal(await isElevated({ platform: "win32", run: async () => "" }), null);+ assert.equal(await isElevated({ platform: "win32", run: async () => { throw new Error("no whoami"); } }), null);+ assert.equal(await isElevated({ platform: "linux", getuid: () => 0 }), true);+ assert.equal(await isElevated({ platform: "linux", getuid: () => 1000 }), false);+});diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 811ec54c..e9c3ecbc 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -27,7 +27,7 @@"prepare:sidecar": "node ./scripts/prepare-sidecar.mjs","pretest": "pnpm --filter @omnirush/headless-threads build","test:omnirush-account": "node --test electron/omnirush-account.test.mjs",- "test": "node --test scripts/prepare-server-constants.test.mjs scripts/verify-update-manifest.test.mjs electron/after-pack-paths.test.mjs electron/agent-context-diagnostics-fetch.test.mjs electron/automation-runner.test.mjs electron/binary-transfer.test.mjs electron/blank-slate-profile.test.mjs electron/blank-slate-profile-isolation.test.mjs electron/brand-app-name.test.mjs electron/brand-icon-darwin.test.mjs electron/brand-icon-windows.test.mjs electron/browser-login-sync.test.mjs electron/browser-panel.test.mjs electron/connect-link.test.mjs electron/desktop-distribution.test.mjs electron/dev-profile.test.mjs electron/electron-builder-config.test.mjs electron/linux-desktop-integration.test.mjs electron/linux-password-store.test.mjs electron/logs-folder.test.mjs electron/media-permissions.test.mjs electron/no-bare-external-fetch.test.mjs electron/nuke.test.mjs electron/omnirush-account.test.mjs electron/omnirush-ui-mcp.test.mjs electron/open-external.test.mjs electron/process-resilience.test.mjs electron/runtime.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/sentry.test.mjs electron/server-dependency-mirror.test.mjs electron/skill-folder.test.mjs electron/secure-vault-key.test.mjs electron/stdio-errors.test.mjs electron/terminal-sessions.test.mjs electron/ui-control-server.test.mjs electron/updater.test.mjs electron/update-gate.test.mjs electron/quality.test.mjs electron/buildathon.test.mjs electron/turn-guard.test.mjs electron/keep-awake.test.mjs electron/remote-workspace.test.mjs electron/workspace-archive.test.mjs electron/workspace-store.test.mjs electron/start-report.test.mjs electron/start-reset.test.mjs",+ "test": "node --test scripts/prepare-server-constants.test.mjs scripts/verify-update-manifest.test.mjs electron/after-pack-paths.test.mjs electron/agent-context-diagnostics-fetch.test.mjs electron/automation-runner.test.mjs electron/binary-transfer.test.mjs electron/blank-slate-profile.test.mjs electron/blank-slate-profile-isolation.test.mjs electron/brand-app-name.test.mjs electron/brand-icon-darwin.test.mjs electron/brand-icon-windows.test.mjs electron/browser-login-sync.test.mjs electron/browser-panel.test.mjs electron/connect-link.test.mjs electron/desktop-distribution.test.mjs electron/dev-profile.test.mjs electron/electron-builder-config.test.mjs electron/linux-desktop-integration.test.mjs electron/linux-password-store.test.mjs electron/logs-folder.test.mjs electron/media-permissions.test.mjs electron/no-bare-external-fetch.test.mjs electron/nuke.test.mjs electron/omnirush-account.test.mjs electron/omnirush-ui-mcp.test.mjs electron/open-external.test.mjs electron/process-resilience.test.mjs electron/runtime.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/sentry.test.mjs electron/server-dependency-mirror.test.mjs electron/skill-folder.test.mjs electron/secure-vault-key.test.mjs electron/stdio-errors.test.mjs electron/terminal-sessions.test.mjs electron/ui-control-server.test.mjs electron/updater.test.mjs electron/update-gate.test.mjs electron/quality.test.mjs electron/buildathon.test.mjs electron/turn-guard.test.mjs electron/keep-awake.test.mjs electron/remote-workspace.test.mjs electron/workspace-archive.test.mjs electron/workspace-store.test.mjs electron/start-report.test.mjs electron/start-reset.test.mjs electron/start-store-check.test.mjs","test:core": "node --test scripts/prepare-server-constants.test.mjs electron/workspace-store.test.mjs electron/workspace-archive.test.mjs electron/connect-link.test.mjs electron/open-external.test.mjs electron/secure-vault-key.test.mjs electron/process-resilience.test.mjs electron/stdio-errors.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/automation-runner.test.mjs","pretest:core": "pnpm --filter @omnirush/headless-threads build"},