Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

feat: start failure help and reset

ogsamrat0ca6fa148fee
diff --git a/apps/app/src/app/lib/desktop.ts b/apps/app/src/app/lib/desktop.ts
index 6c6ef3d8..ad612d0b 100644
--- a/apps/app/src/app/lib/desktop.ts
+++ b/apps/app/src/app/lib/desktop.ts
@@ -137,6 +137,13 @@ export type RecoveryRelease = {
marking: "current" | "previous" | null;
};
+/** What the main process tells the couldn't-start screen (start-report.mjs). */
+export type StartFailureAnswer = {
+ category: string;
+ avHint: string;
+ hint: { title: string; body: string } | null;
+};
+
export type RecoveryActionResult = {
ok: boolean;
action?: "install" | "installer" | "eval";
@@ -218,6 +225,10 @@ declare global {
dev?: {
evalRelaunch?: () => Promise<EvalRelaunchResult>;
};
+ startup?: {
+ reportFailure?: (input: { message?: string | null }) => Promise<StartFailureAnswer>;
+ resetAppData?: () => Promise<{ ok: boolean }>;
+ };
nuke?: {
preview?: (options?: NukeOptions) => Promise<NukeManifestPreview>;
execute?: (options?: NukeOptions) => Promise<NukeReceipt>;
diff --git a/apps/app/src/react-app/shell/desktop-runtime-boot.ts b/apps/app/src/react-app/shell/desktop-runtime-boot.ts
index e9b328ec..2237c281 100644
--- a/apps/app/src/react-app/shell/desktop-runtime-boot.ts
+++ b/apps/app/src/react-app/shell/desktop-runtime-boot.ts
@@ -118,16 +118,21 @@ export function useDesktopRuntimeBoot() {
const startServerWithoutDesktopWorkspace = async () => {
setPhase("starting-engine", "Starting omnirush.ai server");
+ let restartError = "";
const serverInfo = await omnirushServerRestart({
reason: "renderer_boot_without_local_workspace",
source: "desktop-runtime-boot",
remoteAccessEnabled: preferredRemoteAccess,
}).catch((error) => {
console.warn("[desktop-boot] omnirushServerRestart failed:", error);
+ restartError = error instanceof Error ? error.message : safeStringify(error);
return null;
});
if (!isOmniRushServerInfoLike(serverInfo) || !isOmniRushServerReady(serverInfo)) {
- setError("omnirush.ai server did not finish starting. Please restart omnirush.ai.");
+ // Technical details shows the cause, not only that it failed.
+ setError(restartError
+ ? `omnirush.ai server did not finish starting: ${restartError}`
+ : "omnirush.ai server did not finish starting. Please restart omnirush.ai.");
return;
}
publishOmniRushServerInfo(serverInfo);
diff --git a/apps/app/src/react-app/shell/loading-overlay.tsx b/apps/app/src/react-app/shell/loading-overlay.tsx
index 3b77b973..0064b805 100644
--- a/apps/app/src/react-app/shell/loading-overlay.tsx
+++ b/apps/app/src/react-app/shell/loading-overlay.tsx
@@ -1,6 +1,6 @@
/** @jsxImportSource react */
import { useEffect, useState } from "react";
-import type { RecoveryActionResult, RecoveryRelease } from "@/app/lib/desktop";
+import type { RecoveryActionResult, RecoveryRelease, StartFailureAnswer } from "@/app/lib/desktop";
import type { DenAppVersionMetadata, DenDesktopConfig } from "@/app/lib/den";
import { readFreshDenAppVersionMetadata } from "@/app/lib/version-gate";
import { useDesktopConfig } from "@/react-app/domains/cloud/desktop-config-provider";
@@ -21,6 +21,12 @@ async function loadRecoveryPolicy(
]);
}
+// One start-failure report per page load (Try again reloads the page).
+let startFailureReported: Promise<StartFailureAnswer | null> | null = null;
+
+export const RESET_APP_DATA_CONFIRM =
+ "Reset app data?\n\nomnirush.ai moves its local data (workspace list, chats, local settings) into a backup folder, nothing is deleted, and restarts. You stay signed in and your project files are not touched.";
+
/**
* Quiet, opaque boot overlay. Solid surface fill so nothing bleeds through.
* A minimal typographic beat plus a small dot ticker. Fades once both the
@@ -39,6 +45,21 @@ export function LoadingOverlay() {
const [releases, setReleases] = useState<RecoveryRelease[]>([]);
const [showPicker, setShowPicker] = useState(false);
const [actionState, setActionState] = useState<string | null>(null);
+ const [failureAnswer, setFailureAnswer] = useState<StartFailureAnswer | null>(null);
+
+ useEffect(() => {
+ if (!error) return;
+ const report = window.__OMNIRUSH_ELECTRON__?.startup?.reportFailure;
+ if (!report) return;
+ let cancelled = false;
+ startFailureReported ??= report({ message: error }).catch(() => null);
+ void startFailureReported.then((answer) => {
+ if (!cancelled) setFailureAnswer(answer);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [error]);
useEffect(() => {
if (!error) return;
@@ -93,6 +114,8 @@ export function LoadingOverlay() {
};
const useRelease = window.__OMNIRUSH_ELECTRON__?.recovery?.use;
+ const resetAppData = window.__OMNIRUSH_ELECTRON__?.startup?.resetAppData;
+ const hint = failureAnswer?.hint ?? null;
if (!visible || (suppressForGateway && !error)) return null;
@@ -111,7 +134,14 @@ export function LoadingOverlay() {
{error ? (
<div className="flex w-full flex-col gap-3 text-[12px] leading-5">
<div className="text-base font-medium text-dls-primary">omnirush.ai couldn't start</div>
- <div className="text-dls-secondary">Try again. If it keeps failing, return to a version that works on this computer.</div>
+ {hint ? (
+ <div className="flex flex-col gap-1 rounded-md border border-dls-border px-3 py-2 text-left" data-testid="start-failure-hint">
+ <div className="font-medium text-dls-primary">{hint.title}</div>
+ <div className="text-dls-secondary">{hint.body}</div>
+ </div>
+ ) : (
+ <div className="text-dls-secondary">Try again. If it keeps failing, return to a version that works on this computer.</div>
+ )}
<button
type="button"
className="rounded-md bg-dls-accent px-3 py-2 font-medium text-dls-accent-foreground"
@@ -160,6 +190,19 @@ 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={() => {
+ if (!window.confirm(RESET_APP_DATA_CONFIRM)) return;
+ setActionState("Restarting with fresh app data…");
+ void resetAppData().catch(() => setActionState("Reset could not be started. Please retry."));
+ }}
+ >
+ Reset app data
+ </button>
+ ) : 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-overlay.test.tsx b/apps/app/tests/start-failure-overlay.test.tsx
new file mode 100644
index 00000000..db73e94f
--- /dev/null
+++ b/apps/app/tests/start-failure-overlay.test.tsx
@@ -0,0 +1,86 @@
+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: one report, the hint it answers with, and Reset app data after a confirm", 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 });
+
+ mock.module("@/react-app/domains/cloud/desktop-config-provider", () => ({
+ useDesktopConfig: () => ({ config: {}, refreshFresh: async () => ({}) }),
+ }));
+ mock.module("@/react-app/shell/cloud-workspace-overlay", () => ({
+ useCloudWorkspaceStatus: () => ({ gatewayMode: false, visible: false, viewModel: { variant: "hidden" } }),
+ }));
+ const technical = "spawn C:\\Program Files\\omnirush.ai\\resources\\sidecars\\opencode.exe ENOENT";
+ mock.module("@/react-app/shell/boot-state", () => ({
+ bootOverlayCanHide: () => false,
+ useBootOverlayVisible: () => true,
+ useBootState: () => ({ phase: "error", routeReady: false, message: "Something went wrong", error: technical }),
+ }));
+
+ const reportFailure = mock(async (_input: { message?: string | null }) => ({
+ category: "engine_missing",
+ avHint: "binary_missing",
+ hint: { title: "Your antivirus may have removed omnirush.ai's engine", body: "Open Windows Security > Protection history." },
+ }));
+ const resetAppData = mock(async () => ({ ok: true }));
+ let confirmAnswer = false;
+ const confirms: string[] = [];
+ Object.assign(window, {
+ __OMNIRUSH_ELECTRON__: {
+ startup: { reportFailure, resetAppData },
+ recovery: { list: async () => ({ ok: true, releases: [] }) },
+ },
+ __omnirushRecoveryControl: {},
+ confirm: (text: string) => {
+ confirms.push(text);
+ return confirmAnswer;
+ },
+ });
+
+ const { LoadingOverlay, RESET_APP_DATA_CONFIRM } = 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.textContent).toContain("omnirush.ai couldn't start");
+ expect(container.querySelector("[data-testid=start-failure-hint]")?.textContent).toContain("Your antivirus may have removed");
+ expect(container.textContent).toContain(technical);
+ expect(reportFailure).toHaveBeenCalledTimes(1);
+ expect(reportFailure.mock.calls[0]?.[0]).toEqual({ message: technical });
+
+ // A second render on the same page does not report again.
+ await act(async () => {
+ root.render(<LoadingOverlay key="again" />);
+ });
+ expect(reportFailure).toHaveBeenCalledTimes(1);
+
+ const reset = [...container.querySelectorAll("button")].find((button) => button.textContent === "Reset app data");
+ expect(reset).toBeTruthy();
+ await act(async () => {
+ reset?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ expect(confirms).toEqual([RESET_APP_DATA_CONFIRM]);
+ expect(RESET_APP_DATA_CONFIRM).toContain("nothing is deleted");
+ expect(resetAppData).toHaveBeenCalledTimes(0);
+ confirmAnswer = true;
+ await act(async () => {
+ reset?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ expect(resetAppData).toHaveBeenCalledTimes(1);
+ expect(container.textContent).toContain("Restarting with fresh app data");
+ } 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.mjs
index f41b1df3..0c6bc8e6 100644
--- a/apps/desktop/electron/main.mjs
+++ b/apps/desktop/electron/main.mjs
@@ -39,6 +39,18 @@ import { applyBrandAppName } from "./brand-app-name.mjs";
import { createBrowserLoginSync } from "./browser-login-sync.mjs";
import { createBrowserPanel } from "./browser-panel.mjs";
import { createWorkspaceStore } from "./workspace-store.mjs";
+import {
+ START_REPORT_FILE,
+ antivirusHint,
+ buildStartFailureReport,
+ classifyStartFailure,
+ cpuHasAvx2,
+ createStartReporter,
+ inspectEngineBinary,
+ scrubStartMessage,
+ startFailureHint,
+} from "./start-report.mjs";
+import { applyPendingStartReset, scheduleStartReset, startResetTargets } from "./start-reset.mjs";
import { createTerminalSessions, terminalShells } from "./terminal-sessions.mjs";
import {
buildNukeManifest,
@@ -1430,6 +1442,104 @@ const runtimeManager = createRuntimeManager({
// Session upload envelopes report environment.app_version from the desktop build, not the server package.
appVersion: app.getVersion(),
});
+
+// One impersonal report when the app cannot start (start-report.mjs).
+const startReporter = createStartReporter({
+ filePath: path.join(app.getPath("userData"), START_REPORT_FILE),
+ send: (body) => omnirushAccountStore.sendDiagnostic(body),
+ log: (message) => console.warn(message),
+});
+let startAttempt = 0;
+let startAttemptStartedAt = Date.now();
+/** The current start attempt's error, until the window reports the failure. */
+let pendingStartFailure = null;
+/** The attempt last reported, and what the window was told for it. */
+let reportedStart = { attempt: -1, answer: null };
+
+function noteStartAttempt() {
+ startAttempt += 1;
+ startAttemptStartedAt = Date.now();
+ pendingStartFailure = null;
+}
+
+function noteStartFailure(error) {
+ pendingStartFailure = { error, attempt: Math.max(1, startAttempt), elapsedMs: Date.now() - startAttemptStartedAt };
+}
+
+async function readSidecarVersions(files) {
+ for (const file of files) {
+ try {
+ return JSON.parse(await readFile(file, "utf8"));
+ } catch {
+ // Next candidate.
+ }
+ }
+ return null;
+}
+
+function startReportScrubRoots() {
+ const roots = [os.homedir(), os.tmpdir(), process.resourcesPath, process.env.USERPROFILE, process.env.LOCALAPPDATA, process.env.APPDATA];
+ for (const name of ["userData", "appData", "home", "temp"]) {
+ try {
+ roots.push(app.getPath(name));
+ } catch {
+ // Not every path exists on every platform.
+ }
+ }
+ try {
+ roots.push(path.dirname(app.getPath("exe")));
+ } catch {
+ // Ignore.
+ }
+ return roots;
+}
+
+/**
+ * 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
+ * the attempt in the background, and answer with the hint to show.
+ */
+async function reportStartFailure(input = {}) {
+ const failure = pendingStartFailure ?? {
+ error: new Error(String(input?.message ?? "").slice(0, 2000)),
+ attempt: Math.max(1, startAttempt),
+ elapsedMs: Date.now() - startAttemptStartedAt,
+ fromWindow: true,
+ };
+ if (reportedStart.attempt === failure.attempt && reportedStart.answer) return reportedStart.answer;
+ const classified = classifyStartFailure(failure.error, { fallbackPhase: failure.fromWindow ? "renderer" : "unknown" });
+ if (failure.fromWindow && classified.category === "unknown") classified.category = "renderer";
+ const binary = runtimeManager.engineBinaryInfo();
+ const versions = await readSidecarVersions(binary.versionsFiles);
+ const engine = await inspectEngineBinary({ resolved: binary.resolved, bundledCandidates: binary.bundledCandidates, versions });
+ const avHint = antivirusHint(classified, engine, { packaged: app.isPackaged });
+ let userName = "";
+ try {
+ userName = os.userInfo().username;
+ } catch {
+ // No user name to scrub.
+ }
+ const draft = {
+ classified,
+ engine,
+ avHint,
+ message: scrubStartMessage(failure.error, { roots: startReportScrubRoots(), userName }),
+ appVersion: app.getVersion(),
+ engineVersion: versions?.opencode?.version,
+ elapsedMs: failure.elapsedMs,
+ attempt: failure.attempt,
+ };
+ const category = buildStartFailureReport(draft).category;
+ const answer = { category, avHint, hint: startFailureHint(category, { avHint }) };
+ reportedStart = { attempt: failure.attempt, answer };
+ void (async () => {
+ const cpuAvx2 = await cpuHasAvx2().catch(() => null);
+ const outcome = await startReporter.report(buildStartFailureReport({ ...draft, cpuAvx2 }));
+ console.info(`[start-report] ${category}: ${outcome}`);
+ })().catch((error) => console.warn("[start-report] failed", error instanceof Error ? error.name : "error"));
+ return answer;
+}
+
const initialRunnerBootstrap = workspaceStore.readDesktopBootstrapConfigSync();
const legacyRunnerBaseUrls = [
initialRunnerBootstrap.apiBaseUrl,
@@ -1593,10 +1703,14 @@ async function bootRuntimeForSelectedWorkspace() {
}
function startRuntimeBootstrap() {
- const pending = bootRuntimeForSelectedWorkspace().catch((error) => ({
- ok: false,
- error: error instanceof Error ? error.message : String(error),
- }));
+ noteStartAttempt();
+ const pending = bootRuntimeForSelectedWorkspace().catch((error) => {
+ noteStartFailure(error);
+ return {
+ ok: false,
+ error: error instanceof Error ? error.message : String(error),
+ };
+ });
runtimeBootstrapPromise = pending;
// A failed boot is not kept: the next request (the window's Try again)
// boots again instead of being handed the same failure.
@@ -1984,6 +2098,16 @@ const desktopCommandHandlers = {
"runtimeBootstrap": async (event, ...args) => {
return ensureRuntimeBootstrap();
},
+ "startupReportFailure": async (event, ...args) => {
+ return reportStartFailure(args[0] ?? {});
+ },
+ "startupResetAppData": async () => {
+ await scheduleStartReset({ userDataPath: app.getPath("userData") });
+ turnGuard.allowQuit();
+ app.relaunch();
+ app.quit();
+ return { ok: true };
+ },
"runtimeStatus": async (event, ...args) => {
return runtimeManager.runtimeStatus();
},
@@ -2250,7 +2374,13 @@ const desktopCommandHandlers = {
return desktopAutomationRunner.configure(args[0] ?? null);
},
"omnirushServerRestart": async (event, ...args) => {
- return runtimeManager.omnirushServerRestart({ source: "renderer", ...(args[0] ?? {}) });
+ try {
+ return await runtimeManager.omnirushServerRestart({ source: "renderer", ...(args[0] ?? {}) });
+ } catch (error) {
+ // Kept for the start report if the window then shows "couldn't start".
+ noteStartFailure(error);
+ throw error;
+ }
},
"pickDirectory": async (event, ...args) => {
const options = args[0] ?? {};
@@ -3101,6 +3231,15 @@ or use: pnpm dev:worktree`);
}).catch((error) => {
console.warn("[nuke] pending cleanup failed", error);
});
+ await applyPendingStartReset({
+ userDataPath: app.getPath("userData"),
+ targets: startResetTargets({ userDataPath: app.getPath("userData"), env: process.env, homedir: os.homedir() }),
+ log: (message) => console.info(message),
+ });
+ // Start-failure reports queued while signed out or offline.
+ setTimeout(() => {
+ void startReporter.flush().catch(() => undefined);
+ }, 20_000).unref?.();
const bootstrapConfig = await workspaceStore.getDesktopBootstrapConfig();
currentDisplayAppName = applyBrandAppName(
BLANK_SLATE_LAUNCH.enabled || DESKTOP_DISTRIBUTION.flavor === "enterprise"
diff --git a/apps/desktop/electron/omnirush-account.mjs b/apps/desktop/electron/omnirush-account.mjs
index 20e1c88e..e8cebf32 100644
--- a/apps/desktop/electron/omnirush-account.mjs
+++ b/apps/desktop/electron/omnirush-account.mjs
@@ -1164,6 +1164,18 @@ export function createDesktopOmniRushAccountStore({
return response;
}
+ /**
+ * One diagnostic report (POST /diagnostics/crashes, start-report.mjs).
+ * Null while signed out, so the caller queues it.
+ */
+ async function sendDiagnostic(body) {
+ return sendAuthorized("/diagnostics/crashes", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ });
+ }
+
/**
* The wheel's segments, the expected payout and the recent sessions with
* why each did or did not earn spins (GET /me/quality), for the spin
@@ -1398,6 +1410,7 @@ export function createDesktopOmniRushAccountStore({
authorize,
status,
clear,
+ sendDiagnostic,
qualityDetails,
qualitySpinTotals,
spinQuality,
diff --git a/apps/desktop/electron/omnirush-account.test.mjs b/apps/desktop/electron/omnirush-account.test.mjs
index 10e91ade..eddb714e 100644
--- a/apps/desktop/electron/omnirush-account.test.mjs
+++ b/apps/desktop/electron/omnirush-account.test.mjs
@@ -1552,3 +1552,26 @@ test("no client version, no client header", async () => {
await createDesktopOmniRushAccountStore(options).status();
assert.equal(client, null);
});
+
+test("a diagnostic report goes to the crash endpoint with the device credential, and is null while signed out", async () => {
+ const requests = [];
+ const { store } = await connectedStore(async (url, init = {}) => {
+ requests.push({ url: String(url), method: init.method, authorization: new Headers(init.headers).get("authorization"), body: JSON.parse(init.body) });
+ return Response.json({ accepted: true }, { status: 201 });
+ });
+ const response = await store.sendDiagnostic({ product: "gui", kind: "start_failure" });
+ assert.equal(response.status, 201);
+ assert.deepEqual(requests, [{
+ url: "https://gateway.example/omnirush/diagnostics/crashes",
+ method: "POST",
+ authorization: "Bearer access-1",
+ body: { product: "gui", kind: "start_failure" },
+ }]);
+
+ const signedOut = createDesktopOmniRushAccountStore(await storeOptions({
+ fetchImpl: async () => {
+ throw new Error("no request while signed out");
+ },
+ }));
+ assert.equal(await signedOut.sendDiagnostic({ product: "gui" }), null);
+});
diff --git a/apps/desktop/electron/preload.mjs b/apps/desktop/electron/preload.mjs
index e2aa256e..91d39ec7 100644
--- a/apps/desktop/electron/preload.mjs
+++ b/apps/desktop/electron/preload.mjs
@@ -136,6 +136,16 @@ contextBridge.exposeInMainWorld("__OMNIRUSH_ELECTRON__", {
return ipcRenderer.invoke("omnirush:desktop", "__evalRelaunch");
},
},
+ startup: {
+ /** The window shows "couldn't start": one report per attempt, answered with the hint to show. */
+ reportFailure(input) {
+ return ipcRenderer.invoke("omnirush:desktop", "startupReportFailure", input ?? {});
+ },
+ /** Move the local start state into a backup folder on restart, then restart. */
+ resetAppData() {
+ return ipcRenderer.invoke("omnirush:desktop", "startupResetAppData");
+ },
+ },
nuke: {
preview(options) {
return ipcRenderer.invoke("omnirush:desktop", "nukeOmniRushAndOpencodeConfigPreview", options);
diff --git a/apps/desktop/electron/runtime.mjs b/apps/desktop/electron/runtime.mjs
index 23698804..fbd13a39 100644
--- a/apps/desktop/electron/runtime.mjs
+++ b/apps/desktop/electron/runtime.mjs
@@ -2671,6 +2671,12 @@ export function createRuntimeManager({
runtimeStatus,
engineInfo,
engineDoctor,
+ /** The engine binary a start would use and where the bundled copy belongs (start-report.mjs). */
+ engineBinaryInfo: () => ({
+ resolved: resolveOpencodeBinary(),
+ bundledCandidates: sidecarDirs.flatMap((directory) => binaryFileNames("opencode").map((name) => path.join(directory, name))),
+ versionsFiles: sidecarDirs.map((directory) => path.join(directory, "versions.json")),
+ }),
engineInstall,
omnirushServerInfo,
omnirushServerRestart: (options) => withRuntimeLifecycle(() => omnirushServerRestart(options)),
diff --git a/apps/desktop/electron/start-report.mjs b/apps/desktop/electron/start-report.mjs
new file mode 100644
index 00000000..19ccbe55
--- /dev/null
+++ b/apps/desktop/electron/start-report.mjs
@@ -0,0 +1,589 @@
+/**
+ * One small, impersonal report when the desktop cannot start
+ * (POST /omnirush/diagnostics/crashes, `product: "gui"`, `kind:
+ * "start_failure"`), plus the hint the start screen shows for it.
+ *
+ * A report carries enums, numbers and booleans: the failure's category,
+ * phase, error name/code, exit code or signal, versions, OS build, the time
+ * to failure, checks of the engine binary (present, size, header, sha256
+ * against the bundled versions.json, readable) and of the profile folder
+ * (non-ASCII, spaces, UNC, long: booleans only), whether the CPU has AVX2,
+ * and an antivirus hint. Never a path, user name, file contents or prompt;
+ * the one free-text field is the error's first line with every path,
+ * address and long token replaced, and the server drops it if anything
+ * personal is left.
+ *
+ * Sent with the device credential when signed in; otherwise (or offline)
+ * queued and sent on a later start. At most MAX_REPORTS_PER_DAY a day.
+ */
+import { execFile } from "node:child_process";
+import { createHash, randomBytes } from "node:crypto";
+import { createReadStream } from "node:fs";
+import { mkdir, open, readFile, rename, stat, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+export const START_REPORT_FILE = "start-reports.json";
+export const MAX_REPORTS_PER_DAY = 3;
+const MAX_QUEUE = 5;
+// The server takes reports up to 7 days old.
+const MAX_QUEUE_AGE_MS = 6 * 24 * 60 * 60 * 1000;
+const MESSAGE_LIMIT = 300;
+
+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",
+];
+
+const ERROR_NAMES = new Set([
+ "Error", "TypeError", "ReferenceError", "SyntaxError", "RangeError",
+ "URIError", "EvalError", "AggregateError", "SystemError",
+]);
+const ERROR_CODES = new Set([
+ "ENOMEM", "ENOSPC", "EMFILE", "ENFILE", "EACCES", "EPERM", "ENOENT",
+ "EIO", "ECONNRESET", "ETIMEDOUT", "EBUSY", "EADDRINUSE", "ECONNREFUSED",
+ "ENOTDIR", "EISDIR", "ENAMETOOLONG", "EROFS", "EXDEV", "UNKNOWN",
+ "ERR_MODULE_NOT_FOUND", "workspace_inaccessible", "SQLITE_CORRUPT",
+ "SQLITE_NOTADB", "SQLITE_BUSY", "SQLITE_CANTOPEN", "SQLITE_FULL",
+ "SQLITE_IOERR", "SQLITE_READONLY",
+]);
+
+// Windows NTSTATUS exit codes of a process the OS stopped.
+const STATUS_ACCESS_DENIED = 0xc0000022;
+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/;
+
+function innermost(error) {
+ let current = error;
+ for (let depth = 0; depth < 4; depth += 1) {
+ if (current && typeof current === "object" && Array.isArray(current.errors) && current.errors.length > 0) {
+ current = current.errors[0];
+ continue;
+ }
+ break;
+ }
+ return current;
+}
+
+function messageOf(error) {
+ if (error instanceof Error) return String(error.message ?? "");
+ if (typeof error === "string") return error;
+ if (error && typeof error === "object" && typeof error.message === "string") return error.message;
+ return "";
+}
+
+function exitCodeOf(error, message) {
+ if (Number.isInteger(error?.exitCode)) return error.exitCode;
+ const match = message.match(/exited with code (-?\d{1,10})\b/);
+ return match ? Number(match[1]) : null;
+}
+
+function unsigned(code) {
+ return Number.isInteger(code) && code < 0 ? code >>> 0 : code;
+}
+
+function knownCode(value) {
+ return typeof value === "string" && ERROR_CODES.has(value) ? value : null;
+}
+
+/**
+ * The failure's category, phase, error name/code, exit code, signal and
+ * antivirus hint, from the error the start threw (in-process, so spawn
+ * errors keep `code`/`syscall` and engine exits keep `exitCode`).
+ */
+export function classifyStartFailure(rawError, { fallbackPhase = "unknown" } = {}) {
+ const error = innermost(rawError);
+ const message = messageOf(error);
+ const name = error instanceof Error ? error.name : null;
+ const code = typeof error?.code === "string" ? error.code : null;
+ const syscall = typeof error?.syscall === "string" ? error.syscall : "";
+ 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 result = {
+ category: "unknown",
+ phase: fallbackPhase,
+ errorName: name && ERROR_NAMES.has(name) ? name : (rawError instanceof Error ? "Error" : "none"),
+ errorCode: knownCode(code),
+ exitCode: Number.isInteger(exitCode) ? exitCode : null,
+ signal,
+ avHint: "none",
+ };
+ const set = (category, phase, extra = {}) => Object.assign(result, { category, phase }, extra);
+
+ if (code === "workspace_inaccessible") {
+ return set("workspace_inaccessible", "workspace", {
+ errorCode: knownCode(error?.cause?.code) ?? "workspace_inaccessible",
+ });
+ }
+ if (name === "OpencodeConfigCompatError" || /uses V2 permissions|refuses user-owned config/i.test(message)) {
+ return set("config_incompatible", "server");
+ }
+ if (syscall.startsWith("spawn") || /^spawn\b/.test(message)) {
+ if (code === "ENOENT") return set("engine_missing", "engine_spawn", { avHint: "binary_missing" });
+ if (/virus/i.test(message)) return set("engine_blocked", "engine_spawn", { avHint: "virus_detected" });
+ if (code === "EPERM" || code === "EACCES" || code === "UNKNOWN") {
+ return set("engine_blocked", "engine_spawn", { avHint: "spawn_blocked" });
+ }
+ }
+ if (code === "ENOSPC" || /\bENOSPC\b|no space left|SQLITE_FULL|database or disk is full/i.test(message)) {
+ return set("disk_full", fallbackPhase === "unknown" ? "server" : fallbackPhase, { errorCode: knownCode(code) ?? "ENOSPC" });
+ }
+ if (/Timeout waiting for OmniRush server/.test(message)) return set("engine_timeout", "engine_ready");
+ if (/exited with code/.test(message) || result.exitCode !== null) {
+ if (/CPU lacks AVX|Illegal instruction/i.test(message) || status === STATUS_ILLEGAL_INSTRUCTION) {
+ return set("engine_cpu_unsupported", "engine_ready");
+ }
+ if (VIRUS_CODES.has(status)) return set("engine_blocked", "engine_ready", { avHint: "virus_detected" });
+ if (status === STATUS_ACCESS_DENIED) return set("engine_blocked", "engine_ready", { avHint: "exec_status_blocked" });
+ if (/\bEADDRINUSE\b/.test(message)) return set("port_in_use", "engine_ready", { errorCode: "EADDRINUSE" });
+ if (/ConfigJsonError|ConfigInvalidError|configuration is invalid|JSON Parse error/i.test(message)) {
+ return set("config_invalid", "engine_ready");
+ }
+ 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");
+ }
+ if (/did not exit after SIGKILL/.test(message)) return set("engine_stuck", "engine_ready");
+ if (code === "EADDRINUSE" || /\bEADDRINUSE\b/.test(message)) return set("port_in_use", "server", { errorCode: "EADDRINUSE" });
+ if (/Cannot find OmniRush\.ai embedded server bundle/.test(message)) return set("server_bundle_missing", "server");
+ 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 (sqlite) return set("store_error", "server", { errorCode: knownCode(sqlite[1]) ?? result.errorCode });
+ return result;
+}
+
+function escapeRegExp(value) {
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+}
+
+/**
+ * The error's first line (and, for an engine exit, its first diagnostic
+ * line) with every path, address, URL, long token and the user's name
+ * replaced. Null when nothing useful is left.
+ */
+export function scrubStartMessage(rawError, { roots = [], userName = "" } = {}) {
+ const message = messageOf(innermost(rawError));
+ if (!message.trim()) return null;
+ 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|config|denied|permission/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);
+ for (const root of knownRoots) {
+ for (const variant of new Set([root, root.replace(/\\/g, "/"), root.replace(/\//g, "\\")])) {
+ text = text.replace(new RegExp(escapeRegExp(variant), "gi"), "<path>");
+ }
+ }
+ text = text
+ .replace(/https?:\/\/\S+/gi, "<url>")
+ .replace(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g, "<email>")
+ .replace(/\\\\[^\s"'<>|]+/g, "<path>")
+ .replace(/\b[A-Za-z]:[\\/][^\s"'<>|]*/g, "<path>")
+ .replace(/~[\\/][^\s"'<>|]*/g, "<path>")
+ .replace(/(^|[\s(="'])\/[^\s"'<>|]+/g, "$1<path>")
+ .replace(/[A-Za-z0-9+/_-]{32,}/g, "<id>")
+ .replace(/@/g, " at ");
+ const name = String(userName ?? "").trim();
+ if (name.length >= 3) text = text.replace(new RegExp(escapeRegExp(name), "gi"), "<user>");
+ text = text.replace(/\s+/g, " ").trim();
+ if (!text) return null;
+ return text.length > MESSAGE_LIMIT ? `${text.slice(0, MESSAGE_LIMIT - 1)}…` : text;
+}
+
+/** Booleans about the profile folder: never the folder itself. */
+export function profileFlags(home) {
+ const value = String(home ?? "");
+ return {
+ non_ascii: /[^\x00-\x7f]/.test(value),
+ has_space: /\s/.test(value),
+ unc: /^(?:\\\\|\/\/)/.test(value),
+ long: value.length > 80,
+ };
+}
+
+/** The OS build: `10.0.26100` on Windows, the kernel's numeric prefix elsewhere. */
+export function osBuild(release = os.release()) {
+ const match = String(release ?? "").match(/^\d{1,5}(?:\.\d{1,6}){0,3}/);
+ return match ? match[0] : "unknown";
+}
+
+function platformOf(value = process.platform) {
+ return ["linux", "darwin", "win32", "freebsd"].includes(value) ? value : "other";
+}
+
+function archOf(value = process.arch) {
+ return ["x64", "arm64", "ia32", "arm", "riscv64"].includes(value) ? value : "other";
+}
+
+const VERSION = /^\d{1,6}\.\d{1,6}\.\d{1,6}(?:[-+][A-Za-z0-9.-]{1,50})?$/;
+export function reportVersion(value) {
+ const text = String(value ?? "").trim().replace(/^v/, "");
+ return VERSION.test(text) ? text : "unknown";
+}
+
+function execText(file, args, timeoutMs) {
+ return new Promise((resolve) => {
+ execFile(file, args, { timeout: timeoutMs, windowsHide: true, encoding: "utf8" }, (error, stdout) => {
+ resolve(error ? null : String(stdout ?? ""));
+ });
+ });
+}
+
+/**
+ * Whether the CPU has AVX2 (the bundled engine's x64 build needs it), or
+ * null when unknown or not applicable (arm64).
+ */
+export async function cpuHasAvx2({ platform = process.platform, arch = process.arch, release = os.release(), readText = readFile, run = execText } = {}) {
+ if (arch !== "x64") return null;
+ try {
+ if (platform === "linux") {
+ const info = await readText("/proc/cpuinfo", "utf8");
+ return /^flags\s*:.*\bavx2\b/m.test(info);
+ }
+ if (platform === "darwin") {
+ const out = await run("/usr/sbin/sysctl", ["-n", "machdep.cpu.leaf7_features"], 3000);
+ return out === null ? null : /\bAVX2\b/.test(out);
+ }
+ if (platform === "win32") {
+ // PF_AVX2_INSTRUCTIONS_AVAILABLE (40) is reported from Windows 10 2004 (build 19041).
+ const build = Number(osBuild(release).split(".")[2] ?? 0);
+ if (!(build >= 19041)) return null;
+ const script = "Add-Type -Namespace W -Name K -MemberDefinition '[DllImport(\"kernel32.dll\")] public static extern bool IsProcessorFeaturePresent(uint f);'; [W.K]::IsProcessorFeaturePresent(40)";
+ const out = await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", script], 8000);
+ if (out === null) return null;
+ if (/\bTrue\b/.test(out)) return true;
+ if (/\bFalse\b/.test(out)) return false;
+ }
+ } catch {
+ return null;
+ }
+ return null;
+}
+
+async function sha256Of(filePath) {
+ return new Promise((resolve, reject) => {
+ const hash = createHash("sha256");
+ createReadStream(filePath)
+ .on("data", (chunk) => hash.update(chunk))
+ .on("error", reject)
+ .on("end", () => resolve(hash.digest("hex")));
+ });
+}
+
+function headerMatches(bytes, platform) {
+ if (bytes.length < 4) return false;
+ if (platform === "win32") return bytes[0] === 0x4d && bytes[1] === 0x5a;
+ if (platform === "linux" || platform === "freebsd") return bytes[0] === 0x7f && bytes[1] === 0x45 && bytes[2] === 0x4c && bytes[3] === 0x46;
+ if (platform === "darwin") {
+ const magic = bytes.readUInt32BE(0);
+ return [0xcffaedfe, 0xcefaedfe, 0xfeedfacf, 0xfeedface, 0xcafebabe].includes(magic);
+ }
+ return true;
+}
+
+/**
+ * Checks of the engine binary the start used: where it came from, whether
+ * it is there, its size, header and sha256 against the bundled
+ * versions.json, and whether it can be opened. Also whether the bundled
+ * copy is there at all (a missing one in an installed app points at an
+ * antivirus quarantine).
+ */
+export async function inspectEngineBinary({ resolved = null, bundledCandidates = [], versions = null, platform = process.platform, hash = sha256Of } = {}) {
+ const check = { source: "missing", present: false, bundled_present: false, size: null, header_ok: null, hash_ok: null, readable: null };
+ for (const candidate of bundledCandidates) {
+ try {
+ if ((await stat(candidate)).isFile()) {
+ check.bundled_present = true;
+ break;
+ }
+ } catch {
+ // Not this one.
+ }
+ }
+ const binary = resolved?.path ? String(resolved.path) : "";
+ if (!binary) return check;
+ check.source = ["bundled", "path", "known-location", "custom"].includes(resolved.source) ? resolved.source : "unknown";
+ try {
+ const info = await stat(binary);
+ check.present = info.isFile();
+ check.size = info.isFile() ? info.size : null;
+ } catch {
+ return check;
+ }
+ if (!check.present) return check;
+ let handle = null;
+ try {
+ handle = await open(binary, "r");
+ const header = Buffer.alloc(4);
+ const { bytesRead } = await handle.read(header, 0, 4, 0);
+ check.readable = true;
+ check.header_ok = headerMatches(header.subarray(0, bytesRead), platform);
+ } catch {
+ check.readable = false;
+ } finally {
+ await handle?.close().catch(() => undefined);
+ }
+ const expected = typeof versions?.opencode?.sha256 === "string" ? versions.opencode.sha256.toLowerCase() : "";
+ if (check.readable && check.source === "bundled" && /^[a-f0-9]{64}$/.test(expected)) {
+ try {
+ check.hash_ok = (await hash(binary)) === expected;
+ } catch {
+ check.hash_ok = null;
+ }
+ }
+ return check;
+}
+
+/** The antivirus hint: the error's own, else what the binary checks show. */
+export function antivirusHint(classified, engine, { packaged = true } = {}) {
+ if (classified.avHint !== "none") return classified.avHint;
+ if (packaged && !engine.bundled_present) return "binary_missing";
+ if (engine.readable === false) return "open_blocked";
+ if (engine.hash_ok === false) return "binary_modified";
+ return "none";
+}
+
+/** The report body (the server's GuiStartFailureRequest). */
+export function buildStartFailureReport({
+ classified,
+ engine,
+ avHint,
+ cpuAvx2 = null,
+ message = null,
+ appVersion,
+ engineVersion,
+ electronVersion = process.versions.electron,
+ platform = process.platform,
+ arch = process.arch,
+ release = os.release(),
+ home = os.homedir(),
+ elapsedMs = 0,
+ attempt = 1,
+ occurredAt = new Date(),
+ eventId = randomBytes(32).toString("hex"),
+}) {
+ let category = classified.category;
+ if (category === "engine_missing" && engine.present) category = "engine_blocked";
+ if ((category === "unknown" || category === "engine_exit" || category === "engine_crash") && avHint === "binary_modified") {
+ category = "engine_modified";
+ }
+ return {
+ schema_version: 1,
+ product: "gui",
+ kind: "start_failure",
+ event_id: eventId,
+ occurred_at: occurredAt.toISOString(),
+ app_version: reportVersion(appVersion),
+ engine_version: reportVersion(engineVersion),
+ runtime: "electron",
+ runtime_version: reportVersion(electronVersion),
+ platform: platformOf(platform),
+ arch: archOf(arch),
+ os_build: osBuild(release),
+ phase: classified.phase,
+ category: START_FAILURE_CATEGORIES.includes(category) ? category : "unknown",
+ error_name: classified.errorName,
+ error_code: classified.errorCode,
+ exit_code: classified.exitCode,
+ signal: classified.signal,
+ elapsed_ms: Math.max(0, Math.min(86_400_000, Math.round(elapsedMs))),
+ attempt: Math.max(1, Math.min(1000, Math.round(attempt))),
+ engine: {
+ source: engine.source,
+ present: engine.present,
+ bundled_present: engine.bundled_present,
+ size: engine.size,
+ header_ok: engine.header_ok,
+ hash_ok: engine.hash_ok,
+ readable: engine.readable,
+ },
+ profile: profileFlags(home),
+ cpu_avx2: cpuAvx2,
+ av_hint: avHint,
+ message,
+ };
+}
+
+/** What the start screen tells the user for a category (null: the generic text). */
+export function startFailureHint(category, { platform = process.platform, avHint = "none" } = {}) {
+ const windows = platform === "win32";
+ if (category === "engine_missing" || avHint === "binary_missing") {
+ return {
+ title: "Your antivirus may have removed omnirush.ai's engine",
+ body: windows
+ ? "Open Windows Security > Virus & threat protection > Protection history, restore or allow the omnirush.ai item (opencode.exe), add the omnirush.ai install folder as an exclusion, then reinstall omnirush.ai and press Try again."
+ : "Allow omnirush.ai's engine (opencode) in your antivirus, reinstall omnirush.ai, then press Try again.",
+ };
+ }
+ if (category === "engine_blocked") {
+ return {
+ title: "omnirush.ai's engine was blocked",
+ body: windows
+ ? "Windows Security, Smart App Control or your antivirus stopped opencode.exe. Allow it (Protection history > Allow, or add the omnirush.ai install folder as an exclusion), then press Try again."
+ : "Your antivirus or system policy stopped the engine (opencode). Allow it, then press Try again.",
+ };
+ }
+ if (category === "engine_modified") {
+ return {
+ title: "omnirush.ai's engine file is damaged",
+ body: "The engine no longer matches the one that was installed, which usually means an antivirus changed it. Reinstall omnirush.ai, allow it in your antivirus, then press Try again.",
+ };
+ }
+ if (category === "engine_timeout") {
+ return {
+ title: "The engine took too long to start",
+ body: windows
+ ? "This often happens while an antivirus scans the engine. Wait a minute and press Try again. If it keeps happening, add the omnirush.ai install folder as an exclusion in Windows Security."
+ : "Wait a minute and press Try again. If it keeps happening, restart your computer.",
+ };
+ }
+ if (category === "engine_cpu_unsupported") {
+ return {
+ title: "This processor isn't supported by the engine yet",
+ body: "omnirush.ai's engine needs a processor with AVX2. We've been sent a report. The omnirush CLI (npm i -g omnirush) works on this computer meanwhile.",
+ };
+ }
+ if (category === "config_incompatible" || category === "config_invalid") {
+ return {
+ title: "A configuration file stops the engine",
+ body: "Technical details below names the file. Rename or fix it, then press Try again.",
+ };
+ }
+ if (category === "workspace_inaccessible") {
+ return {
+ title: "Your workspace folder can't be opened",
+ body: windows
+ ? "It may be on a disconnected drive, offline in OneDrive, or blocked by Controlled folder access (Windows Security > Ransomware protection: allow omnirush.ai). Reconnect it, or use Reset app data."
+ : "It may be on a disconnected drive or no longer exist. Reconnect it, or use Reset app data.",
+ };
+ }
+ if (category === "store_error") {
+ return {
+ title: "omnirush.ai's local data is damaged",
+ body: "Use Reset app data: it moves the local data to a backup folder (nothing is deleted) and restarts omnirush.ai.",
+ };
+ }
+ if (category === "disk_full") {
+ return { title: "Your disk is full", body: "Free some space on the system drive, then press Try again." };
+ }
+ if (category === "port_in_use") {
+ return { title: "A local port is busy", body: "Press Try again. If it keeps happening, restart your computer." };
+ }
+ return null;
+}
+
+function today(nowMs) {
+ return new Date(nowMs).toISOString().slice(0, 10);
+}
+
+/**
+ * Sends at most `maxPerDay` reports a day; a report that cannot be sent now
+ * (signed out, offline, server error) is queued (at most MAX_QUEUE, none
+ * older than six days) and sent by `flush()` on a later start.
+ *
+ * `send(body)` resolves to a fetch Response, or null while signed out.
+ */
+export function createStartReporter({ filePath, send, now = Date.now, maxPerDay = MAX_REPORTS_PER_DAY, log = () => {} }) {
+ let chain = Promise.resolve();
+ const serialize = (task) => {
+ const run = chain.then(task, task);
+ chain = run.then(() => undefined, () => undefined);
+ return run;
+ };
+
+ async function readState() {
+ try {
+ const parsed = JSON.parse(await readFile(filePath, "utf8"));
+ return {
+ day: typeof parsed?.day === "string" ? parsed.day : "",
+ count: Number.isInteger(parsed?.count) ? parsed.count : 0,
+ queue: Array.isArray(parsed?.queue) ? parsed.queue.filter((item) => item && typeof item === "object") : [],
+ };
+ } catch {
+ return { day: "", count: 0, queue: [] };
+ }
+ }
+
+ async function writeState(state) {
+ await mkdir(path.dirname(filePath), { recursive: true });
+ const temporary = `${filePath}.${process.pid}.tmp`;
+ await writeFile(temporary, `${JSON.stringify(state)}\n`, { mode: 0o600 });
+ await rename(temporary, filePath);
+ }
+
+ function fresh(queue, nowMs) {
+ return queue
+ .filter((item) => {
+ const at = Date.parse(item.occurred_at);
+ return Number.isFinite(at) && nowMs - at < MAX_QUEUE_AGE_MS;
+ })
+ .slice(-MAX_QUEUE);
+ }
+
+ /** "sent" | "retry" (keep queued) | "drop" (the server refused it). */
+ async function deliver(body) {
+ let response;
+ try {
+ response = await send(body);
+ } catch (error) {
+ log(`[start-report] not sent (${error instanceof Error ? error.name : "error"})`);
+ return "retry";
+ }
+ if (!response) return "retry";
+ if (response.ok) return "sent";
+ if (response.status === 401 || response.status === 408 || response.status >= 500) return "retry";
+ return "drop";
+ }
+
+ return {
+ report: (body) => serialize(async () => {
+ const nowMs = now();
+ const state = await readState();
+ if (state.day !== today(nowMs)) {
+ state.day = today(nowMs);
+ state.count = 0;
+ }
+ if (state.count >= maxPerDay) return "skipped";
+ state.count += 1;
+ state.queue = fresh(state.queue, nowMs);
+ await writeState(state);
+ const outcome = await deliver(body);
+ if (outcome === "retry") {
+ state.queue = fresh([...state.queue, body], nowMs);
+ await writeState(state);
+ return "queued";
+ }
+ return outcome === "sent" ? "sent" : "dropped";
+ }),
+ flush: () => serialize(async () => {
+ const nowMs = now();
+ const state = await readState();
+ const queue = fresh(state.queue, nowMs);
+ const kept = [];
+ let sent = 0;
+ for (let index = 0; index < queue.length; index += 1) {
+ const outcome = await deliver(queue[index]);
+ if (outcome === "sent") sent += 1;
+ if (outcome === "retry") {
+ kept.push(...queue.slice(index));
+ break;
+ }
+ }
+ if (kept.length !== state.queue.length || sent > 0) {
+ state.queue = kept;
+ await writeState(state);
+ }
+ return { sent, queued: kept.length };
+ }),
+ };
+}
diff --git a/apps/desktop/electron/start-report.test.mjs b/apps/desktop/electron/start-report.test.mjs
new file mode 100644
index 00000000..56bbe25f
--- /dev/null
+++ b/apps/desktop/electron/start-report.test.mjs
@@ -0,0 +1,277 @@
+import assert from "node:assert/strict";
+import { createHash } from "node:crypto";
+import { mkdtemp, readFile, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+import {
+ antivirusHint,
+ buildStartFailureReport,
+ classifyStartFailure,
+ cpuHasAvx2,
+ createStartReporter,
+ inspectEngineBinary,
+ osBuild,
+ profileFlags,
+ reportVersion,
+ scrubStartMessage,
+ startFailureHint,
+} from "./start-report.mjs";
+
+function spawnError(code, errno = -2) {
+ return Object.assign(new Error(`spawn C:\\Users\\Ana\\AppData\\Local\\Programs\\omnirush.ai\\resources\\sidecars\\opencode.exe ${code}`), {
+ code,
+ errno,
+ syscall: "spawn C:\\Users\\Ana\\AppData\\Local\\Programs\\omnirush.ai\\resources\\sidecars\\opencode.exe",
+ path: "C:\\Users\\Ana\\AppData\\Local\\Programs\\omnirush.ai\\resources\\sidecars\\opencode.exe",
+ });
+}
+
+function exitError(exitCode, output = "") {
+ return Object.assign(new Error(`OmniRush server exited with code ${exitCode}${output ? `\n${output}` : ""}`), { exitCode });
+}
+
+test("start failures are classified from the error the start threw", () => {
+ const cases = [
+ [spawnError("ENOENT"), "engine_missing", "engine_spawn", "ENOENT", "binary_missing"],
+ [spawnError("EPERM"), "engine_blocked", "engine_spawn", "EPERM", "spawn_blocked"],
+ [spawnError("UNKNOWN", -4094), "engine_blocked", "engine_spawn", "UNKNOWN", "spawn_blocked"],
+ [new Error("Timeout waiting for OmniRush server after 60000ms"), "engine_timeout", "engine_ready", null, "none"],
+ [exitError(3221225501), "engine_cpu_unsupported", "engine_ready", null, "none"],
+ [exitError(1, "CPU lacks AVX support. Please consider upgrading to a newer CPU."), "engine_cpu_unsupported", "engine_ready", null, "none"],
+ [exitError(3221225506), "engine_blocked", "engine_ready", null, "exec_status_blocked"],
+ [exitError(225), "engine_blocked", "engine_ready", null, "virus_detected"],
+ [exitError(3221225477), "engine_crash", "engine_ready", null, "none"],
+ [exitError(1, "error: Failed to start server. Is port 4096 in use? EADDRINUSE"), "port_in_use", "engine_ready", "EADDRINUSE", "none"],
+ [exitError(1, "ConfigJsonError: C:\\Users\\Ana\\.config\\opencode\\opencode.json is not valid JSON"), "config_invalid", "engine_ready", null, "none"],
+ [exitError(1, "SQLITE_CORRUPT: database disk image is malformed"), "store_error", "engine_ready", "SQLITE_CORRUPT", "none"],
+ [exitError(1, "something else"), "engine_exit", "engine_ready", null, "none"],
+ [new Error("Managed OmniRush process did not exit after SIGKILL"), "engine_stuck", "engine_ready", null, "none"],
+ [new Error("Cannot find OmniRush.ai embedded server bundle. Checked: C:\\x"), "server_bundle_missing", "server", null, "none"],
+ [new Error("OmniRush.ai server did not stay running after startup."), "server_not_ready", "server_ready", null, "none"],
+ [Object.assign(new Error("ENOSPC: no space left on device, write"), { code: "ENOSPC" }), "disk_full", "server", "ENOSPC", "none"],
+ [Object.assign(new Error("Configuration is invalid"), { name: "OpencodeConfigCompatError" }), "config_incompatible", "server", null, "none"],
+ [new Error("boom"), "unknown", "unknown", null, "none"],
+ ];
+ for (const [error, category, phase, errorCode, avHint] of cases) {
+ const result = classifyStartFailure(error);
+ assert.deepEqual(
+ { category: result.category, phase: result.phase, errorCode: result.errorCode, avHint: result.avHint },
+ { category, phase, errorCode, avHint },
+ error.message,
+ );
+ }
+ const workspace = Object.assign(new Error("Workspace path is not accessible: D:\\Clients\\Acme"), {
+ code: "workspace_inaccessible",
+ cause: Object.assign(new Error("EPERM"), { code: "EPERM" }),
+ });
+ assert.deepEqual(
+ (({ category, phase, errorCode }) => ({ category, phase, errorCode }))(classifyStartFailure(workspace)),
+ { category: "workspace_inaccessible", phase: "workspace", errorCode: "EPERM" },
+ );
+ // A failed cleanup wraps the start error: the start error decides.
+ const wrapped = new AggregateError([spawnError("ENOENT"), new Error("stop failed")], "startup failed");
+ assert.equal(classifyStartFailure(wrapped).category, "engine_missing");
+ assert.equal(classifyStartFailure(exitError(3221225477)).exitCode, 3221225477);
+ assert.equal(classifyStartFailure("text").errorName, "none");
+});
+
+test("messages keep no paths, names, addresses or tokens", () => {
+ const roots = ["C:\\Users\\Ana Lucía", "C:\\Users\\Ana Lucía\\AppData\\Roaming\\ai.omnirush.desktop"];
+ const samples = [
+ spawnError("ENOENT"),
+ new Error("Workspace path is not accessible: C:\\Users\\Ana Lucía\\OneDrive\\Documents\\work"),
+ new Error("EPERM: operation not permitted, open 'C:/Users/Ana Lucía/AppData/Roaming/omnirush/server.json'"),
+ new Error("read \\\\fileserver\\profiles$\\ana\\x failed for [email protected]"),
+ new Error("cannot open /home/ana/.config/opencode/opencode.json (see https://example.com/help)"),
+ new Error("token sk-abcdefghijklmnopqrstuvwxyz0123456789ABCD rejected for user anaLucia"),
+ exitError(1, "ConfigJsonError: ~/.config/opencode/opencode.json bad\nnpm error @opencode-ai/plugin failed"),
+ ];
+ for (const error of samples) {
+ const text = scrubStartMessage(error, { roots, userName: "anaLucia" });
+ assert.ok(text, error.message);
+ assert.doesNotMatch(text, /[A-Za-z]:[\\/]|\\\\|\/home\/|~[\\/]|@|https?:|Ana|ana|[A-Za-z0-9+/_-]{32,}/, text);
+ assert.ok(text.length <= 300);
+ }
+ assert.equal(scrubStartMessage(spawnError("ENOENT"), { roots }), "spawn <path> ENOENT");
+ assert.equal(scrubStartMessage(new Error(" ")), null);
+ assert.match(scrubStartMessage(exitError(1, "line two\nerror: ConfigJsonError")), /exited with code 1 \| error: ConfigJsonError/);
+});
+
+test("profile, OS build and version fields are booleans or numbers only", () => {
+ assert.deepEqual(profileFlags("C:\\Users\\José"), { non_ascii: true, has_space: false, unc: false, long: false });
+ assert.deepEqual(profileFlags("C:\\Users\\Ana Lucia"), { non_ascii: false, has_space: true, unc: false, long: false });
+ assert.equal(profileFlags("\\\\server\\profiles\\ana").unc, true);
+ assert.equal(profileFlags(`C:\\Users\\${"x".repeat(90)}`).long, true);
+ assert.equal(osBuild("10.0.26100"), "10.0.26100");
+ assert.equal(osBuild("6.8.0-139-generic"), "6.8.0");
+ assert.equal(osBuild("weird"), "unknown");
+ assert.equal(reportVersion("v1.18.32"), "1.18.32");
+ assert.equal(reportVersion("3.5.3-beta.1"), "3.5.3-beta.1");
+ assert.equal(reportVersion(undefined), "unknown");
+});
+
+test("AVX2 detection per platform", async () => {
+ assert.equal(await cpuHasAvx2({ platform: "linux", arch: "x64", readText: async () => "flags\t\t: fpu sse2 avx avx2 bmi2\n" }), true);
+ assert.equal(await cpuHasAvx2({ platform: "linux", arch: "x64", readText: async () => "flags\t\t: fpu sse2 sse4_2\n" }), false);
+ assert.equal(await cpuHasAvx2({ platform: "linux", arch: "arm64" }), null);
+ const calls = [];
+ const run = async (file, args) => {
+ calls.push([file, args.at(-1)]);
+ return "False\r\n";
+ };
+ assert.equal(await cpuHasAvx2({ platform: "win32", arch: "x64", release: "10.0.22631", run }), false);
+ assert.match(calls[0][1], /IsProcessorFeaturePresent\(40\)/);
+ assert.equal(await cpuHasAvx2({ platform: "win32", arch: "x64", release: "10.0.17763", run }), null);
+ assert.equal(await cpuHasAvx2({ platform: "win32", arch: "x64", release: "10.0.26100", run: async () => null }), null);
+ assert.equal(await cpuHasAvx2({ platform: "darwin", arch: "x64", run: async () => "AVX2 BMI2 ERMS" }), true);
+});
+
+test("engine binary checks: missing, present and matching, modified", async () => {
+ const dir = await mkdtemp(path.join(os.tmpdir(), "start-report-"));
+ const binary = path.join(dir, "opencode.exe");
+ const body = Buffer.concat([Buffer.from("MZ\x90\x00"), Buffer.alloc(64, 1)]);
+ await writeFile(binary, body);
+ const sha256 = createHash("sha256").update(body).digest("hex");
+
+ const missing = await inspectEngineBinary({ resolved: null, bundledCandidates: [binary + ".gone"], platform: "win32" });
+ assert.deepEqual(missing, { source: "missing", present: false, bundled_present: false, size: null, header_ok: null, hash_ok: null, readable: null });
+ assert.equal(antivirusHint(classifyStartFailure(new Error("x")), missing), "binary_missing");
+ assert.equal(antivirusHint(classifyStartFailure(new Error("x")), missing, { packaged: false }), "none");
+
+ const ok = await inspectEngineBinary({
+ resolved: { path: binary, source: "bundled" },
+ bundledCandidates: [binary],
+ versions: { opencode: { version: "1.18.32", sha256 } },
+ platform: "win32",
+ });
+ assert.deepEqual(ok, { source: "bundled", present: true, bundled_present: true, size: body.length, header_ok: true, hash_ok: true, readable: true });
+ assert.equal(antivirusHint(classifyStartFailure(new Error("x")), ok), "none");
+
+ const modified = await inspectEngineBinary({
+ resolved: { path: binary, source: "bundled" },
+ bundledCandidates: [binary],
+ versions: { opencode: { sha256: "0".repeat(64) } },
+ platform: "linux",
+ });
+ assert.equal(modified.hash_ok, false);
+ assert.equal(modified.header_ok, false);
+ assert.equal(antivirusHint(classifyStartFailure(exitError(1)), modified), "binary_modified");
+});
+
+test("the report body carries only the server's fields", () => {
+ const classified = classifyStartFailure(spawnError("ENOENT"));
+ const engine = { source: "missing", present: false, bundled_present: false, size: null, header_ok: null, hash_ok: null, readable: null };
+ const report = buildStartFailureReport({
+ classified,
+ engine,
+ avHint: antivirusHint(classified, engine),
+ cpuAvx2: true,
+ message: "spawn <path> ENOENT",
+ appVersion: "3.5.3",
+ engineVersion: "1.18.32",
+ electronVersion: "38.2.0",
+ platform: "win32",
+ arch: "x64",
+ release: "10.0.26100",
+ home: "C:\\Users\\José Ñ",
+ elapsedMs: 1234.4,
+ attempt: 2,
+ occurredAt: new Date("2026-10-17T10:00:00Z"),
+ eventId: "a".repeat(64),
+ });
+ assert.deepEqual(report, {
+ schema_version: 1,
+ product: "gui",
+ kind: "start_failure",
+ event_id: "a".repeat(64),
+ occurred_at: "2026-10-17T10:00:00.000Z",
+ app_version: "3.5.3",
+ engine_version: "1.18.32",
+ runtime: "electron",
+ runtime_version: "38.2.0",
+ platform: "win32",
+ arch: "x64",
+ os_build: "10.0.26100",
+ phase: "engine_spawn",
+ category: "engine_missing",
+ error_name: "Error",
+ error_code: "ENOENT",
+ exit_code: null,
+ signal: null,
+ elapsed_ms: 1234,
+ attempt: 2,
+ engine,
+ profile: { non_ascii: true, has_space: true, unc: false, long: false },
+ cpu_avx2: true,
+ av_hint: "binary_missing",
+ message: "spawn <path> ENOENT",
+ });
+ assert.doesNotMatch(JSON.stringify(report), /José|Users/);
+ // ENOENT although the binary is there: something stopped it.
+ const blocked = buildStartFailureReport({ classified, engine: { ...engine, present: true, bundled_present: true }, avHint: "spawn_blocked", appVersion: "3.5.3" });
+ assert.equal(blocked.category, "engine_blocked");
+ const modified = buildStartFailureReport({ classified: classifyStartFailure(exitError(1)), engine, avHint: "binary_modified", appVersion: "x" });
+ assert.equal(modified.category, "engine_modified");
+ assert.equal(modified.app_version, "unknown");
+});
+
+test("hints name the antivirus fix on Windows and stay null for unknown failures", () => {
+ assert.match(startFailureHint("engine_missing", { platform: "win32" }).body, /Protection history/);
+ assert.match(startFailureHint("unknown", { platform: "win32", avHint: "binary_missing" }).title, /antivirus/);
+ assert.match(startFailureHint("engine_timeout", { platform: "win32" }).body, /exclusion/);
+ assert.match(startFailureHint("store_error").body, /Reset app data/);
+ assert.equal(startFailureHint("unknown"), null);
+ assert.equal(startFailureHint("renderer"), null);
+});
+
+function response(status) {
+ return { ok: status >= 200 && status < 300, status };
+}
+
+test("reporter: once sent, queued while signed out, capped per day, flushed later", async () => {
+ const dir = await mkdtemp(path.join(os.tmpdir(), "start-reporter-"));
+ const filePath = path.join(dir, "start-reports.json");
+ let nowMs = Date.parse("2026-10-17T10:00:00Z");
+ const sent = [];
+ let answer = null;
+ const reporter = createStartReporter({
+ filePath,
+ now: () => nowMs,
+ maxPerDay: 3,
+ send: async (body) => {
+ sent.push(body.event_id);
+ return answer;
+ },
+ });
+ const body = (id) => ({ event_id: id, occurred_at: new Date(nowMs).toISOString() });
+
+ // Signed out: queued.
+ assert.equal(await reporter.report(body("a")), "queued");
+ answer = response(201);
+ assert.equal(await reporter.report(body("b")), "sent");
+ answer = response(400);
+ assert.equal(await reporter.report(body("c")), "dropped");
+ // The day's cap counts every attempt.
+ assert.equal(await reporter.report(body("d")), "skipped");
+ assert.deepEqual(JSON.parse(await readFile(filePath, "utf8")).queue.map((item) => item.event_id), ["a"]);
+
+ // Next day, offline: queued; the next start's flush sends both.
+ nowMs += 24 * 60 * 60 * 1000;
+ answer = null;
+ assert.equal(await reporter.report(body("e")), "queued");
+ answer = response(201);
+ assert.deepEqual(await reporter.flush(), { sent: 2, queued: 0 });
+ assert.deepEqual(sent, ["a", "b", "c", "e", "a", "e"]);
+
+ // A server error keeps the queue; reports older than six days are dropped.
+ answer = response(503);
+ assert.equal(await reporter.report(body("f")), "queued");
+ nowMs += 7 * 24 * 60 * 60 * 1000;
+ assert.deepEqual(await reporter.flush(), { sent: 0, queued: 0 });
+
+ // A failing transport never throws.
+ const failing = createStartReporter({ filePath: path.join(dir, "other.json"), send: async () => { throw new TypeError("fetch failed"); } });
+ assert.equal(await failing.report(body("g")), "queued");
+});
diff --git a/apps/desktop/electron/start-reset.mjs b/apps/desktop/electron/start-reset.mjs
new file mode 100644
index 00000000..308433d1
--- /dev/null
+++ b/apps/desktop/electron/start-reset.mjs
@@ -0,0 +1,101 @@
+/**
+ * "Reset app data" on the couldn't-start screen: the app's local start
+ * state (workspace list, embedded server registry and runtime database,
+ * engine data, port and token state) is moved into a backup folder, never
+ * deleted, and the app restarts with a fresh state. Sign-in, Chromium
+ * storage, the user's own config files and env.json stay.
+ *
+ * The move happens on the next launch, before anything opens those files
+ * (Windows cannot rename a folder a running engine or database holds), so
+ * the request only writes a marker and relaunches.
+ */
+import { existsSync } from "node:fs";
+import { mkdir, rename, rm, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { omnirushConfigDir } from "@omnirush/paths";
+
+export const START_RESET_PENDING = ".start-reset-pending.json";
+export const START_RESET_BACKUP_PREFIX = "start-reset-";
+
+const USERDATA_ENTRIES = [
+ "omnirush-workspaces.json",
+ "workspace-state.json",
+ "omnirush-server-tokens.json",
+ "omnirush-server-state.json",
+ "engine-data",
+ "managed-opencode-workdir",
+];
+const CONFIG_ENTRIES = [
+ "server.json",
+ "runtime.sqlite",
+ "runtime.sqlite-wal",
+ "runtime.sqlite-shm",
+ "runtime-opencode-config.json",
+ "engine-instances.json",
+];
+
+function stamp(date) {
+ return date.toISOString().replace(/[-:]/g, "").replace(/\..*$/, "").replace("T", "-");
+}
+
+/** What a reset moves: `{ label, path }`, the label naming it inside the backup. */
+export function startResetTargets({ userDataPath, env = process.env, homedir, platform = process.platform }) {
+ const configDir = omnirushConfigDir({ env, homeDir: homedir, platform });
+ return [
+ ...USERDATA_ENTRIES.map((name) => ({ label: `app/${name}`, path: path.join(userDataPath, name) })),
+ ...CONFIG_ENTRIES.map((name) => ({ label: `config/${name}`, path: path.join(configDir, name) })),
+ ];
+}
+
+/** Ask for a reset on the next launch. */
+export async function scheduleStartReset({ userDataPath, now = () => new Date() }) {
+ await mkdir(userDataPath, { recursive: true });
+ await writeFile(
+ path.join(userDataPath, START_RESET_PENDING),
+ `${JSON.stringify({ requestedAt: now().toISOString() })}\n`,
+ { mode: 0o600 },
+ );
+}
+
+/**
+ * On launch: when a reset was asked for, move every target that exists into
+ * `<userData>/start-reset-<time>/` (or, across drives, beside itself with a
+ * `.omnirush-reset-<time>` suffix). Never throws; returns what moved.
+ */
+export async function applyPendingStartReset({ userDataPath, targets, now = () => new Date(), renameImpl = rename, log = () => {} }) {
+ const marker = path.join(userDataPath, START_RESET_PENDING);
+ if (!existsSync(marker)) return { ran: false, moved: [], failed: [] };
+ const time = stamp(now());
+ const backupDir = path.join(userDataPath, `${START_RESET_BACKUP_PREFIX}${time}`);
+ const moved = [];
+ const failed = [];
+ try {
+ await mkdir(backupDir, { recursive: true });
+ } catch (error) {
+ log(`[start-reset] backup folder unavailable (${error?.code ?? "error"})`);
+ }
+ for (const target of targets) {
+ if (!existsSync(target.path)) continue;
+ const destination = path.join(backupDir, ...target.label.split("/"));
+ try {
+ await mkdir(path.dirname(destination), { recursive: true });
+ await renameImpl(target.path, destination);
+ moved.push(target.label);
+ } catch (error) {
+ try {
+ await renameImpl(target.path, `${target.path}.omnirush-reset-${time}`);
+ moved.push(target.label);
+ } catch (fallbackError) {
+ failed.push({ label: target.label, code: fallbackError?.code ?? error?.code ?? "error" });
+ }
+ }
+ }
+ await writeFile(
+ path.join(backupDir, "reset.json"),
+ `${JSON.stringify({ resetAt: now().toISOString(), moved, failed }, null, 2)}\n`,
+ ).catch(() => undefined);
+ await rm(marker, { force: true }).catch(() => undefined);
+ log(`[start-reset] moved ${moved.length} item(s) aside${failed.length ? `, ${failed.length} could not be moved` : ""}`);
+ return { ran: true, backupDir, moved, failed };
+}
+
diff --git a/apps/desktop/electron/start-reset.test.mjs b/apps/desktop/electron/start-reset.test.mjs
new file mode 100644
index 00000000..332ff047
--- /dev/null
+++ b/apps/desktop/electron/start-reset.test.mjs
@@ -0,0 +1,83 @@
+import assert from "node:assert/strict";
+import { existsSync } from "node:fs";
+import { mkdir, mkdtemp, readFile, readdir, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+import { START_RESET_PENDING, applyPendingStartReset, scheduleStartReset, startResetTargets } from "./start-reset.mjs";
+
+async function fixture() {
+ const root = await mkdtemp(path.join(os.tmpdir(), "start-reset-"));
+ const userDataPath = path.join(root, "ai.omnirush.desktop");
+ const configDir = path.join(root, "omnirush-config");
+ await mkdir(path.join(userDataPath, "engine-data", "omnirush"), { recursive: true });
+ await mkdir(configDir, { recursive: true });
+ await writeFile(path.join(userDataPath, "omnirush-workspaces.json"), "{\"workspaces\":[]}");
+ await writeFile(path.join(userDataPath, "engine-data", "omnirush", "opencode.db"), "db");
+ await writeFile(path.join(userDataPath, "omnirush-account.bin"), "signed in");
+ await writeFile(path.join(configDir, "server.json"), "{}");
+ await writeFile(path.join(configDir, "runtime.sqlite"), "sqlite");
+ await writeFile(path.join(configDir, "env.json"), "{}");
+ const env = { OMNIRUSH_SERVER_CONFIG: path.join(configDir, "server.json") };
+ const targets = startResetTargets({ userDataPath, env, homedir: root });
+ return { root, userDataPath, configDir, targets };
+}
+
+test("targets are the app's start state, never sign-in or the user's env", async () => {
+ const { userDataPath, configDir, targets } = await fixture();
+ const paths = targets.map((target) => target.path);
+ assert.ok(paths.includes(path.join(userDataPath, "engine-data")));
+ assert.ok(paths.includes(path.join(userDataPath, "omnirush-workspaces.json")));
+ assert.ok(paths.includes(path.join(configDir, "server.json")));
+ assert.ok(paths.includes(path.join(configDir, "runtime.sqlite")));
+ assert.ok(!paths.some((entry) => /omnirush-account|env\.json|private-credentials/.test(entry)));
+});
+
+test("nothing happens without a request", async () => {
+ const { userDataPath, targets } = await fixture();
+ assert.deepEqual(await applyPendingStartReset({ userDataPath, targets }), { ran: false, moved: [], failed: [] });
+ assert.ok(existsSync(path.join(userDataPath, "omnirush-workspaces.json")));
+});
+
+test("a requested reset moves the start state into a backup folder on the next launch", async () => {
+ const { userDataPath, configDir, targets } = await fixture();
+ await scheduleStartReset({ userDataPath, now: () => new Date("2026-10-17T10:00:00Z") });
+ assert.ok(existsSync(path.join(userDataPath, START_RESET_PENDING)));
+ const result = await applyPendingStartReset({ userDataPath, targets, now: () => new Date("2026-10-17T10:00:05Z") });
+ assert.equal(result.ran, true);
+ assert.deepEqual(result.failed, []);
+ assert.deepEqual(new Set(result.moved), new Set([
+ "app/omnirush-workspaces.json", "app/engine-data", "config/server.json", "config/runtime.sqlite",
+ ]));
+ const backup = path.join(userDataPath, "start-reset-20261017-100005");
+ assert.equal(result.backupDir, backup);
+ assert.equal(await readFile(path.join(backup, "app", "engine-data", "omnirush", "opencode.db"), "utf8"), "db");
+ assert.equal(await readFile(path.join(backup, "config", "server.json"), "utf8"), "{}");
+ assert.ok(!existsSync(path.join(userDataPath, "engine-data")));
+ assert.ok(!existsSync(path.join(configDir, "server.json")));
+ // Sign-in and the user's env stay; the request is consumed.
+ assert.ok(existsSync(path.join(userDataPath, "omnirush-account.bin")));
+ assert.ok(existsSync(path.join(configDir, "env.json")));
+ assert.ok(!existsSync(path.join(userDataPath, START_RESET_PENDING)));
+ assert.deepEqual(JSON.parse(await readFile(path.join(backup, "reset.json"), "utf8")).failed, []);
+ assert.equal((await applyPendingStartReset({ userDataPath, targets })).ran, false);
+});
+
+test("a move across drives falls back to a rename beside the file; a locked file is reported, not fatal", async () => {
+ const { userDataPath, configDir, targets } = await fixture();
+ await scheduleStartReset({ userDataPath });
+ const calls = [];
+ const renameImpl = async (from, to) => {
+ calls.push([from, to]);
+ if (from.endsWith("runtime.sqlite")) throw Object.assign(new Error("busy"), { code: "EBUSY" });
+ if (from.startsWith(configDir) && to.startsWith(userDataPath)) throw Object.assign(new Error("cross-device"), { code: "EXDEV" });
+ const { rename } = await import("node:fs/promises");
+ return rename(from, to);
+ };
+ const result = await applyPendingStartReset({ userDataPath, targets, renameImpl, now: () => new Date("2026-10-17T11:00:00Z") });
+ assert.deepEqual(result.failed, [{ label: "config/runtime.sqlite", code: "EBUSY" }]);
+ assert.ok(result.moved.includes("config/server.json"));
+ assert.ok((await readdir(configDir)).includes("server.json.omnirush-reset-20261017-110000"));
+ assert.ok(existsSync(path.join(configDir, "runtime.sqlite")));
+});
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index c0ae4b85..811ec54c 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",
+ "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: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"
},