A desktop coding agent with free access to frontier models.
TypeScript
fix: safer start messages and reset
ogsamrat7eef438fad4e
diff --git a/apps/app/src/app/lib/desktop.ts b/apps/app/src/app/lib/desktop.tsindex ad612d0b..652b06e5 100644--- a/apps/app/src/app/lib/desktop.ts+++ b/apps/app/src/app/lib/desktop.ts@@ -141,6 +141,8 @@ export type RecoveryRelease = {export type StartFailureAnswer = {category: string;avHint: string;+ /** Reset app data also moves the engine's data (chats): only when its store failed. */+ resetIncludesChats?: boolean;hint: { title: string; body: string } | null;};@@ -227,7 +229,7 @@ declare global {};startup?: {reportFailure?: (input: { message?: string | null }) => Promise<StartFailureAnswer>;- resetAppData?: () => Promise<{ ok: boolean }>;+ resetAppData?: () => Promise<{ ok: boolean; backupDir?: string }>;};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 0064b805..9a401784 100644--- a/apps/app/src/react-app/shell/loading-overlay.tsx+++ b/apps/app/src/react-app/shell/loading-overlay.tsx@@ -25,7 +25,9 @@ async function loadRecoveryPolicy(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.";+ "Reset app data?\n\nomnirush.ai moves its local settings (workspace list, local server data) into a backup folder, nothing is deleted, and restarts. Your chats, sign-in and project files stay. After the restart you can restore the previous data.";+export const RESET_APP_DATA_CONFIRM_WITH_CHATS =+ "Reset app data?\n\nomnirush.ai's local chat database looks damaged. omnirush.ai moves its local data, including chat history, into a backup folder, nothing is deleted, and restarts. Your sign-in and project files stay. After the restart you can restore the previous data.";/*** Quiet, opaque boot overlay. Solid surface fill so nothing bleeds through.@@ -195,9 +197,16 @@ export function LoadingOverlay() {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;+ const confirmText = failureAnswer?.resetIncludesChats ? RESET_APP_DATA_CONFIRM_WITH_CHATS : RESET_APP_DATA_CONFIRM;+ if (!window.confirm(confirmText)) return;setActionState("Restarting with fresh app data…");- void resetAppData().catch(() => setActionState("Reset could not be started. Please retry."));+ void resetAppData()+ .then((result) => {+ if (result.backupDir) {+ setActionState(`Restarting with fresh app data. Your previous app data is kept in ${result.backupDir}; after the restart, choose Restore previous app data to go back to it.`);+ }+ })+ .catch(() => setActionState("Reset could not be started. Please retry."));}}>Reset app datadiff --git a/apps/app/tests/start-failure-overlay.test.tsx b/apps/app/tests/start-failure-overlay.test.tsxindex d6d87c2d..059d907a 100644--- a/apps/app/tests/start-failure-overlay.test.tsx+++ b/apps/app/tests/start-failure-overlay.test.tsx@@ -30,7 +30,7 @@ test("couldn't start: one report, the hint it answers with, and Reset app data aavHint: "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 }));+ const resetAppData = mock(async () => ({ ok: true, backupDir: "C:\\Users\\Ana\\AppData\\Roaming\\ai.omnirush.desktop\\start-reset-20261017-100000" }));let confirmAnswer = false;const confirms: string[] = [];Object.assign(window, {@@ -75,13 +75,18 @@ test("couldn't start: one report, the hint it answers with, and Reset app data a});expect(confirms).toEqual([RESET_APP_DATA_CONFIRM]);expect(RESET_APP_DATA_CONFIRM).toContain("nothing is deleted");+ expect(RESET_APP_DATA_CONFIRM).toContain("Your chats");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");+ await act(async () => {+ await Promise.resolve();+ });+ expect(container.textContent).toContain("start-reset-20261017-100000");+ expect(container.textContent).toContain("Restore previous app data");} finally {await act(async () => root.unmount());container.remove();diff --git a/apps/desktop/electron/main.mjs b/apps/desktop/electron/main.mjsindex 15c32082..c769c818 100644--- a/apps/desktop/electron/main.mjs+++ b/apps/desktop/electron/main.mjs@@ -44,13 +44,18 @@ import {antivirusHint,buildStartFailureReport,classifyStartFailure,- cpuHasAvx2,createStartReporter,inspectEngineBinary,scrubStartMessage,startFailureHint,} from "./start-report.mjs";-import { applyPendingStartReset, scheduleStartReset, startResetTargets } from "./start-reset.mjs";+import {+ applyPendingStartReset,+ applyPendingStartRestore,+ scheduleStartReset,+ scheduleStartRestore,+ startResetTargets,+} from "./start-reset.mjs";import { createTerminalSessions, terminalShells } from "./terminal-sessions.mjs";import {buildNukeManifest,@@ -1524,18 +1529,24 @@ async function reportStartFailure(input = {}) {classified,engine,avHint,- message: scrubStartMessage(failure.error, { roots: startReportScrubRoots(), userName }),+ message: scrubStartMessage(failure.error, {+ roots: startReportScrubRoots(),+ userName,+ hostName: os.hostname(),+ category: classified.category,+ }),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 }) };+ // 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 }) };reportedStart = { attempt: failure.attempt, answer };void (async () => {- const cpuAvx2 = await cpuHasAvx2().catch(() => null);- const outcome = await startReporter.report(buildStartFailureReport({ ...draft, cpuAvx2 }));+ const outcome = await startReporter.report(buildStartFailureReport(draft));console.info(`[start-report] ${category}: ${outcome}`);})().catch((error) => console.warn("[start-report] failed", error instanceof Error ? error.name : "error"));return answer;@@ -2103,11 +2114,17 @@ const desktopCommandHandlers = {return reportStartFailure(args[0] ?? {});},"startupResetAppData": async () => {- await scheduleStartReset({ userDataPath: app.getPath("userData") });- turnGuard.allowQuit();- app.relaunch();- app.quit();- return { ok: true };+ const { backupDir } = await scheduleStartReset({+ userDataPath: app.getPath("userData"),+ includeEngineData: reportedStart.answer?.resetIncludesChats === true,+ });+ // A moment for the window to show where the backup goes.+ setTimeout(() => {+ turnGuard.allowQuit();+ app.relaunch();+ app.quit();+ }, 4_000).unref?.();+ return { ok: true, backupDir };},"runtimeStatus": async (event, ...args) => {return runtimeManager.runtimeStatus();@@ -3232,9 +3249,18 @@ or use: pnpm dev:worktree`);}).catch((error) => {console.warn("[nuke] pending cleanup failed", error);});- await applyPendingStartReset({+ const startRestore = await applyPendingStartRestore({userDataPath: app.getPath("userData"),- targets: startResetTargets({ userDataPath: app.getPath("userData"), env: process.env, homedir: os.homedir() }),+ log: (message) => console.info(message),+ });+ const startReset = await applyPendingStartReset({+ userDataPath: app.getPath("userData"),+ targetsFor: ({ includeEngineData }) => startResetTargets({+ userDataPath: app.getPath("userData"),+ env: process.env,+ homedir: os.homedir(),+ includeEngineData,+ }),log: (message) => console.info(message),});// Start-failure reports queued while signed out or offline.@@ -3293,6 +3319,36 @@ or use: pnpm dev:worktree`);queueDeepLinks(forwardedDeepLinks(process.argv));const win = await createMainWindow();+ if (startReset.ran && startReset.moved.length > 0) {+ runDetachedTask("show app data reset notice", async () => {+ const { response } = await dialog.showMessageBox(win, {+ type: "info",+ message: "omnirush.ai started with fresh app data",+ detail: `Your previous app data was moved, not deleted, to:\n${startReset.backupDir}\n\n`+ + "To go back to it, choose Restore previous app data: omnirush.ai restarts and moves it back."+ + (startReset.failed.length ? `\n\n${startReset.failed.length} item(s) were in use and stayed in place.` : ""),+ buttons: ["OK", "Open backup folder", "Restore previous app data"],+ defaultId: 0,+ cancelId: 0,+ });+ if (response === 1) await shell.openPath(startReset.backupDir);+ if (response === 2) {+ await scheduleStartRestore({ userDataPath: app.getPath("userData"), backupDir: startReset.backupDir });+ turnGuard.allowQuit();+ app.relaunch();+ app.quit();+ }+ });+ }+ if (startRestore.ran) {+ runDetachedTask("show app data restore notice", () => dialog.showMessageBox(win, {+ type: startRestore.failed.length ? "warning" : "info",+ message: startRestore.failed.length ? "Some previous app data could not be restored" : "Previous app data restored",+ detail: `Backup folder:\n${startRestore.backupDir}`+ + (startRestore.failed.length ? `\n\nNot restored: ${startRestore.failed.map((entry) => entry.label).join(", ")}` : ""),+ buttons: ["OK"],+ }));+ }if (firstLaunchWorkspaceFailure) {runDetachedTask("show default workspace warning", () => dialog.showMessageBox(win, {type: "warning",diff --git a/apps/desktop/electron/start-report.mjs b/apps/desktop/electron/start-report.mjsindex 46af17bc..9d4b044a 100644--- a/apps/desktop/electron/start-report.mjs+++ b/apps/desktop/electron/start-report.mjs@@ -7,8 +7,7 @@* 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;+ * (non-ASCII, spaces, UNC, long: booleans only) 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.@@ -16,7 +15,6 @@* 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";@@ -164,17 +162,43 @@ function escapeRegExp(value) {return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");}+/**+ * Secrets that can sit in an error line: API keys (sk-…, GitHub ghp_/gho_/+ * ghs_/ghu_/ghr_, AWS AKIA…), bearer credentials and JWT-like segments.+ */+const SECRET_PATTERNS = [+ /\bBearer\s+\S+/gi,+ /\bsk-[A-Za-z0-9_-]{4,}/g,+ /\bgh[opsur]_[A-Za-z0-9]{4,}/g,+ /\b(?:AKIA|ASIA)[0-9A-Z]{8,}/g,+ /\beyJ[A-Za-z0-9_-]{4,}(?:\.[A-Za-z0-9_-]*)*/g,+ /\b[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g,+];+const IPV4 = /\b(?:\d{1,3}\.){3}\d{1,3}\b/g;+const IPV6 = /(?:\b[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{0,4}){3,7}\b|\b[0-9A-Fa-f]{1,4}::(?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?|::1\b)/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.+ * line) with every path, address, URL, key, token, IP and the user's and+ * computer's names replaced. A path runs to its closing quote or the end of+ * the line, never only to the first space (`C:\\Users\\Bob Jones\\…`).+ * For a config error only the error's type name is kept: its diagnostic+ * quotes the file. Null when nothing useful is left.+ *+ * @param {unknown} rawError+ * @param {{ roots?: Array<string | undefined>; userName?: string; hostName?: string; category?: string }} [options]*/-export function scrubStartMessage(rawError, { roots = [], userName = "" } = {}) {+export function scrubStartMessage(rawError, { roots = [], userName = "", hostName = "", category = "" } = {}) {const message = messageOf(innermost(rawError));if (!message.trim()) return null;+ if (category === "config_invalid" || category === "config_incompatible") {+ const errorName = innermost(rawError) instanceof Error ? innermost(rawError).name : "";+ const named = message.match(/\b(Config[A-Za-z]*Error|OpencodeConfigCompatError|JSON Parse error)\b/);+ return named?.[1] ?? (errorName && errorName !== "Error" ? errorName : category);+ }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));+ const diagnostic = lines.slice(1).find((line) => /error|lacks|illegal|EADDRINUSE|SQLITE|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))]@@ -185,16 +209,21 @@ export function scrubStartMessage(rawError, { roots = [], userName = "" } = {})}}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(/[a-z][a-z0-9+.-]*:\/\/[^\s"'<>|]+/gi, "<url>")+ .replace(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g, "<email>");+ for (const pattern of SECRET_PATTERNS) text = text.replace(pattern, "<secret>");+ text = text.replace(IPV4, "<ip>").replace(IPV6, "<ip>");+ for (const name of [userName, hostName]) {+ const value = String(name ?? "").trim();+ if (value.length >= 3) text = text.replace(new RegExp(escapeRegExp(value), "gi"), name === hostName ? "<host>" : "<user>");+ }+ text = text+ // A quoted path: everything up to the closing quote.+ .replace(/(["'`])[^"'`]*[\\/][^"'`]*\1/g, "$1<path>$1")+ // An unquoted path (drive, UNC, \Device\…, \Users\…, Users/…, ~/…, /x/…): to the end of the line.+ .replace(/(^|[\s(=:|])[^\s"'`(=|]*[\\/][^"'`|]*/g, "$1<path>")+ .replace(/[A-Za-z0-9+_-]{24,}/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;@@ -231,54 +260,6 @@ export function reportVersion(value) {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).- */-/**- * @param {{- * platform?: string;- * arch?: string;- * release?: string;- * readText?: (file: string, encoding: "utf8") => Promise<string>;- * run?: (file: string, args: string[], timeoutMs: number) => Promise<string | null>;- * }} [options]- */-export async function cpuHasAvx2({ platform = process.platform, arch = process.arch, release = os.release(), readText = (file, encoding) => readFile(file, encoding), 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");@@ -367,7 +348,6 @@ export function buildStartFailureReport({classified,engine,avHint,- cpuAvx2 = null,message = null,appVersion = "unknown",engineVersion = "unknown",@@ -417,7 +397,6 @@ export function buildStartFailureReport({readable: engine.readable,},profile: profileFlags(home),- cpu_avx2: cpuAvx2,av_hint: avHint,message,};@@ -458,8 +437,8 @@ export function startFailureHint(category, { platform = process.platform, avHint}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.",+ title: "This computer's processor is too old for omnirush.ai's engine",+ body: "The engine stopped on an instruction this processor does not support. Please tell us in support which computer this is; the omnirush CLI (npm i -g omnirush) may work here meanwhile.",};}if (category === "config_incompatible" || category === "config_invalid") {diff --git a/apps/desktop/electron/start-report.test.mjs b/apps/desktop/electron/start-report.test.mjsindex 7ed931fc..c6a2c65a 100644--- a/apps/desktop/electron/start-report.test.mjs+++ b/apps/desktop/electron/start-report.test.mjs@@ -9,7 +9,6 @@ import {antivirusHint,buildStartFailureReport,classifyStartFailure,- cpuHasAvx2,createStartReporter,inspectEngineBinary,osBuild,@@ -94,9 +93,66 @@ test("messages keep no paths, names, addresses or tokens", () => {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(spawnError("ENOENT"), { roots }), "spawn <path>");assert.equal(scrubStartMessage(new Error(" ")), null);- assert.match(scrubStartMessage(exitError(1, "line two\nerror: ConfigJsonError")), /exited with code 1 \| error: ConfigJsonError/);+ assert.match(scrubStartMessage(exitError(1, "line two\nerror: database is locked")), /exited with code 1 \| error: database is locked/);+});++// The server's last check (omnirush/crash_reports.py _PERSONAL): a message+// matching it is dropped. Scrubbed messages must never match it.+const SERVER_DROP = new RegExp([+ String.raw`\\`,+ String.raw`/[^/\s]+/`,+ String.raw`[A-Za-z]:/`,+ String.raw`~/`,+ "@",+ String.raw`[a-z][a-z0-9+.-]*://`,+ String.raw`\b(?:\d{1,3}\.){3}\d{1,3}\b`,+ String.raw`\b[0-9a-f]{1,4}(?::[0-9a-f]{0,4}){3,7}\b`,+ "::",+ String.raw`\bBearer\s`,+ String.raw`\bsk-[A-Za-z0-9_-]{4,}`,+ String.raw`\bgh[opsur]_[A-Za-z0-9]{4,}`,+ String.raw`\b(?:AKIA|ASIA)[0-9A-Z]{8,}`,+ String.raw`\beyJ[A-Za-z0-9_-]{4,}`,+ String.raw`[A-Za-z0-9+/_-]{32,}`,+].join("|"), "i");++/** @type {Array<[string, string[]]>} */+const ADVERSARIAL = [+ ["Workspace path is not accessible: C:\\Users\\Bob Jones\\Work\\Acme Client Contract\\notes.txt", ["Bob", "Jones", "Acme", "Contract", "notes"]],+ ["EPERM: operation not permitted, open C:\\Users\\bob\\OneDrive - Acme Corp\\Documents\\plan.docx", ["bob", "Acme", "Corp", "plan"]],+ ["spawn \\Device\\HarddiskVolume3\\Users\\Bob Jones\\x.exe EPERM", ["Bob", "Jones", "Harddisk"]],+ ["cannot read \\Users\\bob\\AppData\\Local\\x", ["bob", "AppData"]],+ ["ENOENT: no such file, open Users/alice/Documents/secret.docx", ["alice", "secret"]],+ ["open '/Users/alice/My Projects/acme plan/x.json' failed", ["alice", "acme", "Projects"]],+ ["provider rejected key sk-live-abc123def456", ["abc123"]],+ ["token ghp_abcdEFGH1234 and gho_zzzz9999 and ghs_yyyy8888 rejected", ["EFGH", "zzzz", "yyyy"]],+ ["request failed: Authorization: Bearer abc.def", ["abc.def"]],+ ["bad token eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.c2ln", ["eyJ", "c2ln"]],+ ["aws key AKIAIOSFODNN7EXAMPLE denied", ["IOSFODNN"]],+ ["connect ECONNREFUSED 203.0.113.7:443", ["203.0.113"]],+ ["listen failed on fe80::1ff:fe23:4567:890a and 2001:db8:85a3:0:0:8a2e:370:7334", ["fe80", "2001", "8a2e"]],+ ["engine on DESKTOP-BOBPC exited", ["BOBPC"]],+];++test("adversarial messages: paths with spaces, single-backslash and driveless paths, keys, IPs and the computer name never survive", () => {+ for (const [raw, secrets] of ADVERSARIAL) {+ const text = scrubStartMessage(new Error(raw), { userName: "bob", hostName: "DESKTOP-BOBPC" });+ assert.ok(text, raw);+ for (const secret of secrets) assert.ok(!text.toLowerCase().includes(secret.toLowerCase()), `${raw} -> ${text} keeps ${secret}`);+ assert.doesNotMatch(text, SERVER_DROP, `${raw} -> ${text} would be dropped by the server`);+ }+ // Every raw string (except the computer name, which only the client knows) is dropped by the server's check.+ for (const [raw] of ADVERSARIAL.slice(0, -1)) assert.match(raw, SERVER_DROP, raw);+});++test("config errors send only the error's type name, never the quoted diagnostic", () => {+ const invalid = exitError(1, "ConfigJsonError: C:\\Users\\Bob Jones\\.config\\opencode\\opencode.json: Unexpected token at 'apiKey: sk-abc'");+ assert.equal(scrubStartMessage(invalid, { category: classifyStartFailure(invalid).category }), "ConfigJsonError");+ const compat = Object.assign(new Error("Configuration is invalid at C:\\Users\\Bob\\.config\\opencode\\opencode.json: permissions"), { name: "OpencodeConfigCompatError" });+ assert.equal(scrubStartMessage(compat, { category: "config_incompatible" }), "OpencodeConfigCompatError");+ assert.equal(scrubStartMessage(new Error("Configuration is invalid at x"), { category: "config_invalid" }), "config_invalid");});test("profile, OS build and version fields are booleans or numbers only", () => {@@ -112,22 +168,6 @@ test("profile, OS build and version fields are booleans or numbers only", () =>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");@@ -167,8 +207,7 @@ test("the report body carries only the server's fields", () => {classified,engine,avHint: antivirusHint(classified, engine),- cpuAvx2: true,- message: "spawn <path> ENOENT",+ message: "spawn <path>",appVersion: "3.5.3",engineVersion: "1.18.32",electronVersion: "38.2.0",@@ -204,9 +243,8 @@ test("the report body carries only the server's fields", () => {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",+ message: "spawn <path>",});assert.doesNotMatch(JSON.stringify(report), /José|Users/);// ENOENT although the binary is there: something stopped it.@@ -221,6 +259,8 @@ test("hints name the antivirus fix on Windows and stay null for unknown failuresassert.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("engine_cpu_unsupported").title, /processor is too old/);+ assert.doesNotMatch(JSON.stringify(startFailureHint("engine_cpu_unsupported")), /AVX/);assert.match(startFailureHint("store_error").body, /Reset app data/);assert.equal(startFailureHint("unknown"), null);assert.equal(startFailureHint("renderer"), null);diff --git a/apps/desktop/electron/start-reset.mjs b/apps/desktop/electron/start-reset.mjsindex c481bd0e..cf2c54b9 100644--- a/apps/desktop/electron/start-reset.mjs+++ b/apps/desktop/electron/start-reset.mjs@@ -1,110 +1,213 @@/*** "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.+ * 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 engine's data (chat+ * history and sessions not yet uploaded) stays too, unless the failure+ * points at the engine's store.*- * 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.+ * Files that belong together (runtime.sqlite with its -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+ * (Windows cannot rename what 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 { mkdir, readFile, 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_RESTORE_PENDING = ".start-restore-pending.json";export const START_RESET_BACKUP_PREFIX = "start-reset-";+export const START_RESET_RECEIPT = "reset.json";-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",-];+/** @typedef {{ label: string; paths: string[] }} StartResetTarget */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 }) {+/**+ * What a reset moves, in groups that move together. `engine-data` (chat+ * history, sessions not yet uploaded) only with `includeEngineData`.+ *+ * @param {{ userDataPath: string; env?: NodeJS.ProcessEnv; homedir?: string; platform?: NodeJS.Platform; includeEngineData?: boolean }} options+ * @returns {StartResetTarget[]}+ */+export function startResetTargets({ userDataPath, env = process.env, homedir, platform = process.platform, includeEngineData = false }) {const configDir = omnirushConfigDir({ env, homeDir: homedir, platform });+ const app = (name) => ({ label: `app/${name}`, paths: [path.join(userDataPath, name)] });+ const config = (name) => ({ label: `config/${name}`, paths: [path.join(configDir, name)] });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) })),+ app("omnirush-workspaces.json"),+ app("workspace-state.json"),+ app("omnirush-server-tokens.json"),+ app("omnirush-server-state.json"),+ app("managed-opencode-workdir"),+ ...(includeEngineData ? [app("engine-data")] : []),+ config("server.json"),+ {+ label: "config/runtime.sqlite",+ paths: ["runtime.sqlite", "runtime.sqlite-wal", "runtime.sqlite-shm"].map((name) => path.join(configDir, name)),+ },+ config("runtime-opencode-config.json"),+ config("engine-instances.json"),];}-/** Ask for a reset on the next launch. */-export async function scheduleStartReset({ userDataPath, now = () => new Date() }) {+/**+ * Ask for a reset on the next launch. Returns the backup folder it will use,+ * so the screen can name it before the restart.+ *+ * @param {{ userDataPath: string; includeEngineData?: boolean; now?: () => Date }} options+ */+export async function scheduleStartReset({ userDataPath, includeEngineData = false, now = () => new Date() }) {+ const backupDir = path.join(userDataPath, `${START_RESET_BACKUP_PREFIX}${stamp(now())}`);await mkdir(userDataPath, { recursive: true });await writeFile(path.join(userDataPath, START_RESET_PENDING),- `${JSON.stringify({ requestedAt: now().toISOString() })}\n`,+ `${JSON.stringify({ requestedAt: now().toISOString(), backupDir, includeEngineData })}\n`,{ mode: 0o600 },);+ return { backupDir };+}++async function readJson(filePath) {+ try {+ return JSON.parse(await readFile(filePath, "utf8"));+ } catch {+ return null;+ }}/**- * 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.+ * Move every file of a group, or none: a failure moves the ones already+ * moved back. Returns the moves made ({ from, to }), or throws with `code`.*/+async function moveGroup(moves, renameImpl) {+ const done = [];+ try {+ for (const move of moves) {+ await mkdir(path.dirname(move.to), { recursive: true });+ await renameImpl(move.from, move.to);+ done.push(move);+ }+ return done;+ } catch (error) {+ for (const move of done.reverse()) await renameImpl(move.to, move.from).catch(() => undefined);+ throw error;+ }+}+/**+ * On launch: when a reset was asked for, move each target group that+ * exists into the backup folder (or, across drives, beside itself with a+ * `.omnirush-reset-<time>` suffix). Never throws; returns what moved and+ * writes the receipt a restore reads.+ ** @param {{* userDataPath: string;- * targets: Array<{ label: string; path: string }>;+ * targetsFor: (options: { includeEngineData: boolean }) => StartResetTarget[];* now?: () => Date;* renameImpl?: (from: string, to: string) => Promise<void>;* log?: (message: string) => void;* }} options*/-export async function applyPendingStartReset({ userDataPath, targets, now = () => new Date(), renameImpl = rename, log = () => {} }) {+export async function applyPendingStartReset({ userDataPath, targetsFor, now = () => new Date(), renameImpl = rename, log = () => {} }) {const marker = path.join(userDataPath, START_RESET_PENDING);if (!existsSync(marker)) return { ran: false, moved: [], failed: [] };+ const request = await readJson(marker);const time = stamp(now());- const backupDir = path.join(userDataPath, `${START_RESET_BACKUP_PREFIX}${time}`);+ const backupDir = typeof request?.backupDir === "string" && path.dirname(request.backupDir) === userDataPath+ ? request.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("/"));+ await mkdir(backupDir, { recursive: true }).catch(() => undefined);+ for (const target of targetsFor({ includeEngineData: request?.includeEngineData === true })) {+ const present = target.paths.filter((entry) => existsSync(entry));+ if (present.length === 0) continue;+ const intoBackup = present.map((from) => ({+ from,+ to: path.join(backupDir, ...target.label.split("/").slice(0, -1), path.basename(from)),+ }));try {- await mkdir(path.dirname(destination), { recursive: true });- await renameImpl(target.path, destination);- moved.push(target.label);- } catch (error) {+ moved.push({ label: target.label, moves: await moveGroup(intoBackup, renameImpl) });+ } catch {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" });+ const beside = present.map((from) => ({ from, to: `${from}.omnirush-reset-${time}` }));+ moved.push({ label: target.label, moves: await moveGroup(beside, renameImpl) });+ } catch (error) {+ failed.push({ label: target.label, code: error?.code ?? "error" });}}}await writeFile(- path.join(backupDir, "reset.json"),+ path.join(backupDir, START_RESET_RECEIPT),`${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 };+ return { ran: true, backupDir, moved: moved.map((entry) => entry.label), failed };+}++/**+ * Ask to move a reset's backup back on the next launch.+ *+ * @param {{ userDataPath: string; backupDir: string }} options+ */+export async function scheduleStartRestore({ userDataPath, backupDir }) {+ await writeFile(path.join(userDataPath, START_RESTORE_PENDING), `${JSON.stringify({ backupDir })}\n`, { mode: 0o600 });}+/**+ * On launch: when a restore was asked for, put every group of the backup's+ * receipt back. What the fresh start created in its place is kept, in the+ * backup folder under `replaced-<time>/`. Never throws.+ *+ * @param {{+ * userDataPath: string;+ * now?: () => Date;+ * renameImpl?: (from: string, to: string) => Promise<void>;+ * log?: (message: string) => void;+ * }} options+ */+export async function applyPendingStartRestore({ userDataPath, now = () => new Date(), renameImpl = rename, log = () => {} }) {+ const marker = path.join(userDataPath, START_RESTORE_PENDING);+ if (!existsSync(marker)) return { ran: false, restored: [], failed: [] };+ const request = await readJson(marker);+ await rm(marker, { force: true }).catch(() => undefined);+ const backupDir = typeof request?.backupDir === "string" ? request.backupDir : "";+ const receipt = backupDir && path.dirname(backupDir) === userDataPath ? await readJson(path.join(backupDir, START_RESET_RECEIPT)) : null;+ if (!receipt || !Array.isArray(receipt.moved)) return { ran: true, backupDir, restored: [], failed: [{ label: "receipt", code: "missing" }] };+ const replacedDir = path.join(backupDir, `replaced-${stamp(now())}`);+ const restored = [];+ const failed = [];+ for (const entry of receipt.moved) {+ const moves = Array.isArray(entry?.moves) ? entry.moves.filter((move) => typeof move?.from === "string" && typeof move?.to === "string") : [];+ if (moves.length === 0 || !moves.every((move) => existsSync(move.to))) {+ failed.push({ label: String(entry?.label ?? "?"), code: "missing" });+ continue;+ }+ const current = moves+ .filter((move) => existsSync(move.from))+ .map((move) => ({ from: move.from, to: path.join(replacedDir, ...String(entry.label).split("/").slice(0, -1), path.basename(move.from)) }));+ try {+ const setAside = await moveGroup(current, renameImpl);+ try {+ await moveGroup(moves.map((move) => ({ from: move.to, to: move.from })), renameImpl);+ restored.push(entry.label);+ } catch (error) {+ for (const move of setAside.reverse()) await renameImpl(move.to, move.from).catch(() => undefined);+ throw error;+ }+ } catch (error) {+ failed.push({ label: String(entry.label), code: error?.code ?? "error" });+ }+ }+ log(`[start-reset] restored ${restored.length} item(s)${failed.length ? `, ${failed.length} could not be restored` : ""}`);+ return { ran: true, backupDir, restored, failed };+}diff --git a/apps/desktop/electron/start-reset.test.mjs b/apps/desktop/electron/start-reset.test.mjsindex 332ff047..e6a95cdc 100644--- a/apps/desktop/electron/start-reset.test.mjs+++ b/apps/desktop/electron/start-reset.test.mjs@@ -1,11 +1,19 @@import assert from "node:assert/strict";import { existsSync } from "node:fs";-import { mkdir, mkdtemp, readFile, readdir, writeFile } from "node:fs/promises";+import { mkdir, mkdtemp, readFile, readdir, rename, 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";+import {+ START_RESET_PENDING,+ START_RESTORE_PENDING,+ applyPendingStartReset,+ applyPendingStartRestore,+ scheduleStartReset,+ scheduleStartRestore,+ startResetTargets,+} from "./start-reset.mjs";async function fixture() {const root = await mkdtemp(path.join(os.tmpdir(), "start-reset-"));@@ -13,71 +21,118 @@ async function fixture() {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-workspaces.json"), "{\"workspaces\":[\"old\"]}");+ await writeFile(path.join(userDataPath, "engine-data", "omnirush", "opencode.db"), "chats");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, "runtime.sqlite-wal"), "wal");+ 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") };- const targets = startResetTargets({ userDataPath, env, homedir: root });- return { root, userDataPath, configDir, targets };+ const targetsFor = ({ includeEngineData }) => startResetTargets({ userDataPath, env, homedir: root, includeEngineData });+ return { root, userDataPath, configDir, targetsFor };}-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)));+const at = (iso) => () => new Date(iso);++test("targets: start state only; engine data only when asked; the runtime database with its -wal/-shm as one group", async () => {+ const { userDataPath, configDir, targetsFor } = await fixture();+ const plain = targetsFor({ includeEngineData: false });+ const all = plain.flatMap((target) => target.paths);+ assert.ok(all.includes(path.join(userDataPath, "omnirush-workspaces.json")));+ assert.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"]);+ assert.ok(targetsFor({ includeEngineData: true }).some((target) => target.label === "app/engine-data"));});test("nothing happens without a request", async () => {- const { userDataPath, targets } = await fixture();- assert.deepEqual(await applyPendingStartReset({ userDataPath, targets }), { ran: false, moved: [], failed: [] });+ const { userDataPath, targetsFor } = await fixture();+ assert.deepEqual(await applyPendingStartReset({ userDataPath, targetsFor }), { 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);+test("a reset moves the start state into the announced backup folder and keeps chats, sign-in and env", async () => {+ const { userDataPath, configDir, targetsFor } = await fixture();+ const { backupDir } = await scheduleStartReset({ userDataPath, now: at("2026-10-17T10:00:00Z") });+ assert.equal(backupDir, path.join(userDataPath, "start-reset-20261017-100000"));+ const result = await applyPendingStartReset({ userDataPath, targetsFor, now: at("2026-10-17T10:00:09Z") });+ assert.equal(result.backupDir, backupDir);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.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.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")));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();+test("engine data moves only when the reset asked for it (a failed engine store)", async () => {+ const { userDataPath, targetsFor } = await fixture();+ const { backupDir } = await scheduleStartReset({ userDataPath, includeEngineData: true });+ const result = await applyPendingStartReset({ userDataPath, targetsFor });+ assert.ok(result.moved.includes("app/engine-data"));+ assert.equal(await readFile(path.join(backupDir, "app", "engine-data", "omnirush", "opencode.db"), "utf8"), "chats");+});++test("the runtime database group moves all together or not at all", async () => {+ const { userDataPath, configDir, targetsFor } = 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");+ if (from.endsWith("runtime.sqlite-shm")) throw Object.assign(new Error("busy"), { code: "EBUSY" });return rename(from, to);};- const result = await applyPendingStartReset({ userDataPath, targets, renameImpl, now: () => new Date("2026-10-17T11:00:00Z") });+ const result = await applyPendingStartReset({ userDataPath, targetsFor, renameImpl });assert.deepEqual(result.failed, [{ label: "config/runtime.sqlite", code: "EBUSY" }]);+ for (const name of ["runtime.sqlite", "runtime.sqlite-wal", "runtime.sqlite-shm"]) {+ assert.ok(existsSync(path.join(configDir, name)), `${name} stays with its group`);+ }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")));+});++test("across drives a group moves beside itself", async () => {+ const { userDataPath, configDir, targetsFor } = await fixture();+ await scheduleStartReset({ userDataPath });+ const renameImpl = async (from, to) => {+ if (from.startsWith(configDir) && to.startsWith(userDataPath)) throw Object.assign(new Error("cross-device"), { code: "EXDEV" });+ return rename(from, to);+ };+ const result = await applyPendingStartReset({ userDataPath, targetsFor, renameImpl, now: at("2026-10-17T11:00:00Z") });+ assert.deepEqual(result.failed, []);+ const names = await readdir(configDir);+ assert.ok(names.includes("server.json.omnirush-reset-20261017-110000"));+ assert.ok(names.includes("runtime.sqlite-wal.omnirush-reset-20261017-110000"));+});++test("Restore previous app data moves the backup back and keeps what the fresh start made", async () => {+ const { userDataPath, configDir, targetsFor } = await fixture();+ const { backupDir } = await scheduleStartReset({ userDataPath });+ await applyPendingStartReset({ userDataPath, targetsFor });+ // The fresh start wrote new files.+ await writeFile(path.join(userDataPath, "omnirush-workspaces.json"), "{\"workspaces\":[\"fresh\"]}");+ await writeFile(path.join(configDir, "runtime.sqlite"), "fresh");++ await scheduleStartRestore({ userDataPath, backupDir });+ const result = await applyPendingStartRestore({ userDataPath, now: at("2026-10-17T12:00:00Z") });+ assert.deepEqual(result.failed, []);+ assert.deepEqual(new Set(result.restored), new Set(["app/omnirush-workspaces.json", "config/server.json", "config/runtime.sqlite"]));+ assert.equal(await readFile(path.join(userDataPath, "omnirush-workspaces.json"), "utf8"), "{\"workspaces\":[\"old\"]}");+ assert.equal(await readFile(path.join(configDir, "runtime.sqlite"), "utf8"), "sqlite");+ assert.equal(await readFile(path.join(configDir, "runtime.sqlite-shm"), "utf8"), "shm");+ const replaced = path.join(backupDir, "replaced-20261017-120000");+ assert.equal(await readFile(path.join(replaced, "app", "omnirush-workspaces.json"), "utf8"), "{\"workspaces\":[\"fresh\"]}");+ assert.equal(await readFile(path.join(replaced, "config", "runtime.sqlite"), "utf8"), "fresh");+ assert.ok(!existsSync(path.join(userDataPath, START_RESTORE_PENDING)));+ assert.equal((await applyPendingStartRestore({ userDataPath })).ran, false);+});++test("a restore outside the app's folder or without a receipt changes nothing", async () => {+ const { root, userDataPath } = await fixture();+ await scheduleStartRestore({ userDataPath, backupDir: path.join(root, "elsewhere") });+ const result = await applyPendingStartRestore({ userDataPath });+ assert.deepEqual(result.restored, []);+ assert.deepEqual(result.failed, [{ label: "receipt", code: "missing" }]);});