A desktop coding agent with free access to frontier models.
TypeScript
fix: windows start
ogsamrate8ce0ba53c62
diff --git a/apps/app/src/react-app/shell/loading-overlay.tsx b/apps/app/src/react-app/shell/loading-overlay.tsxindex b3dbd5ee..3b77b973 100644--- a/apps/app/src/react-app/shell/loading-overlay.tsx+++ b/apps/app/src/react-app/shell/loading-overlay.tsx@@ -111,11 +111,18 @@ 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">Return to a version that works on this computer.</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"+ onClick={() => window.location.reload()}+ >+ Try again+ </button><buttontype="button"disabled={!releases.some((release) => release.marking === "previous")}- className="rounded-md bg-dls-accent px-3 py-2 font-medium text-dls-accent-foreground disabled:opacity-50"+ className="rounded-md border border-dls-border px-3 py-2 font-medium text-dls-primary disabled:opacity-50"onClick={() => void runRecovery(window.__OMNIRUSH_ELECTRON__?.recovery?.restorePrevious)}>Restore previous versiondiff --git a/apps/desktop/electron/main.mjs b/apps/desktop/electron/main.mjsindex 7cdc17d4..f41b1df3 100644--- a/apps/desktop/electron/main.mjs+++ b/apps/desktop/electron/main.mjs@@ -1592,14 +1592,22 @@ async function bootRuntimeForSelectedWorkspace() {return { ok: true, skipped: false, engine, omnirushServer, workspaceId: bootWorkspace.id ?? null };}+function startRuntimeBootstrap() {+ const pending = bootRuntimeForSelectedWorkspace().catch((error) => ({+ 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.+ void pending.then((result) => {+ if (result?.ok === false && runtimeBootstrapPromise === pending) runtimeBootstrapPromise = null;+ });+ return pending;+}+function ensureRuntimeBootstrap() {- if (!runtimeBootstrapPromise) {- runtimeBootstrapPromise = bootRuntimeForSelectedWorkspace().catch((error) => ({- ok: false,- error: error instanceof Error ? error.message : String(error),- }));- }- return runtimeBootstrapPromise;+ return runtimeBootstrapPromise ?? startRuntimeBootstrap();}function resolveOpencodeConfigPath(scope, projectDir) {@@ -3140,10 +3148,7 @@ or use: pnpm dev:worktree`);});}if (!desktopActivationRequired(DESKTOP_DISTRIBUTION, bootstrapConfig)) {- runtimeBootstrapPromise = bootRuntimeForSelectedWorkspace().catch((error) => ({- ok: false,- error: error instanceof Error ? error.message : String(error),- }));+ startRuntimeBootstrap();}queueDeepLinks(forwardedDeepLinks(process.argv));diff --git a/apps/server/src/embedded.ts b/apps/server/src/embedded.tsindex bdba86c9..55b2c657 100644--- a/apps/server/src/embedded.ts+++ b/apps/server/src/embedded.ts@@ -25,7 +25,7 @@ import {type EnginePoolSnapshot,type EngineSpawnTemplate,} from "./engine-pool.js";-import { createManagedOpencodeServer, type ManagedOpencodeServer, type OpencodeExecutionSnapshot } from "./managed-opencode.js";+import { createManagedOpencodeServer, pluginsNoDepsEnv, type ManagedOpencodeServer, type OpencodeExecutionSnapshot } from "./managed-opencode.js";import {clearTrustedOpencodeProcess,collectBusyEngineSessions,@@ -38,7 +38,7 @@ import {} from "./server.js";import { ensureLocalWorkspaceFiles } from "./workspace-init.js";import { findManagedEngineWorkspace } from "./workspaces.js";-import { keepOmniRushRuntimeConfigFileFresh, writeOmniRushRuntimeConfigFile } from "./omnirush-runtime-config.js";+import { keepOmniRushRuntimeConfigFileFresh, omnirushOwnPluginPaths, writeOmniRushRuntimeConfigFile } from "./omnirush-runtime-config.js";import { migrateOmniRushCloudMcpRuntimeConfig } from "./cloud-mcp-health.js";import { migrateWorkspaceRuntimeConfigToEngineGlobal } from "./runtime-opencode-config-store.js";import { migrateLegacyOmniRushUiMcpCommand, type OmniRushUiMcpLaunch } from "./omnirush-ui-mcp-migration.js";@@ -273,6 +273,7 @@ export async function startEmbeddedServer(options: EmbeddedServerOptions): PromiOMNIRUSH_POLICY_TOKEN: managedDesktopPolicy(config).evaluationToken,OPENCODE_CONFIG: runtimeConfigPath,...opencodeModelsEnv,+ ...pluginsNoDepsEnv(omnirushOwnPluginPaths()),};engineSpawnTemplate = {bin: opencodeBin,diff --git a/apps/server/src/managed-opencode.test.ts b/apps/server/src/managed-opencode.test.tsindex fb984043..d0993687 100644--- a/apps/server/src/managed-opencode.test.ts+++ b/apps/server/src/managed-opencode.test.ts@@ -3,7 +3,13 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, describe, expect, test } from "bun:test";-import { createManagedOpencodeServer } from "./managed-opencode.js";+import {+ createManagedOpencodeServer,+ createManagedProcessClose,+ engineStartTimeoutMs,+ pluginsNoDepsEnv,+ type ManagedChildProcess,+} from "./managed-opencode.js";import { createManagedOpencodeV2Server } from "./managed-opencode-v2.js";const roots: string[] = [];@@ -154,3 +160,56 @@ describe("managed OpenCode startup", () => {expect((await readFile(attemptsPath, "utf8")).trim().split("\n")).toEqual(["start"]);});});++describe("managed OpenCode on slow machines (Windows)", () => {+ test("the start wait is longer on Windows and can be set", () => {+ expect(engineStartTimeoutMs({}, "win32")).toBe(60_000);+ expect(engineStartTimeoutMs({}, "linux")).toBe(15_000);+ expect(engineStartTimeoutMs({ OMNIRUSH_ENGINE_START_TIMEOUT_MS: "90000" }, "linux")).toBe(90_000);+ expect(engineStartTimeoutMs({ OMNIRUSH_ENGINE_START_TIMEOUT_MS: "soon" }, "darwin")).toBe(15_000);+ });++ test("a start that never listens fails with the start timeout", async () => {+ const root = await createRoot();+ const bin = await writeExecutable(root, "never-listens.mjs", ["setInterval(() => {}, 1000);"]);+ const error = await createManagedOpencodeServer({ bin, cwd: root, env: { OMNIRUSH_ENGINE_START_TIMEOUT_MS: "300" } })+ .then(() => null, (thrown: unknown) => thrown);+ expect(error).toBeInstanceOf(Error);+ expect(error instanceof Error ? error.message : "").toBe("Timeout waiting for OmniRush server after 300ms");+ });++ function stubbornChild(): ManagedChildProcess & { signals: (NodeJS.Signals | number | undefined)[] } {+ const signals: (NodeJS.Signals | number | undefined)[] = [];+ return {+ pid: 4242,+ exitCode: null,+ signalCode: null,+ killed: false,+ signals,+ kill: (signal) => { signals.push(signal); return true; },+ once: () => undefined,+ };+ }++ test("close succeeds when the process is gone but its exit event has not arrived", async () => {+ const child = stubbornChild();+ const lifecycle = createManagedProcessClose(child, { termTimeoutMs: 5, killTimeoutMs: 5, processExists: () => false });+ await lifecycle.close();+ expect(child.signals).toEqual(["SIGTERM", "SIGKILL"]);+ });++ test("close still reports a process that is really still running", async () => {+ const child = stubbornChild();+ const lifecycle = createManagedProcessClose(child, { termTimeoutMs: 5, killTimeoutMs: 5, processExists: () => true });+ await expect(lifecycle.close()).rejects.toThrow("Managed OmniRush process did not exit after SIGKILL");+ });++ test("our bundled plugins are named to the engine, also by their real path", () => {+ const env = pluginsNoDepsEnv(["/app/link/a.js", "/app/b.js", "/gone/c.js"], (file) => {+ if (file === "/gone/c.js") throw new Error("ENOENT");+ return file.replace("/link", "/real");+ });+ expect(env.OMNIRUSH_PLUGINS_NO_DEPS?.split("\n")).toEqual(["/app/link/a.js", "/app/real/a.js", "/app/b.js", "/gone/c.js"]);+ expect(pluginsNoDepsEnv([])).toEqual({});+ });+});diff --git a/apps/server/src/managed-opencode.ts b/apps/server/src/managed-opencode.tsindex dffa6238..1dbc9b97 100644--- a/apps/server/src/managed-opencode.ts+++ b/apps/server/src/managed-opencode.ts@@ -1,4 +1,5 @@import { spawn, type ChildProcess } from "node:child_process";+import { realpathSync } from "node:fs";import net from "node:net";import { randomUUID } from "node:crypto";import { globalOpencodeConfigDir } from "@omnirush/paths";@@ -7,6 +8,7 @@ import { repairEngineStoreBeforeStart } from "./engine-store-repair.js";import { engineInstallLogEnv } from "./install-log-host.js";export type ManagedChildProcess = {+ pid?: number;exitCode: number | null;signalCode: NodeJS.Signals | null;killed: boolean;@@ -17,8 +19,56 @@ export type ManagedChildProcess = {export type ManagedProcessCloseOptions = {termTimeoutMs?: number;killTimeoutMs?: number;+ /** Whether the OS still has the process (default: signal 0 to child.pid). */+ processExists?: () => boolean;};+/**+ * The engine reads OMNIRUSH_PLUGINS_NO_DEPS (one file per line): when every+ * configured plugin is one of these files, it does not wait for its config+ * folders' npm installs before serving a project. Each file is named as given+ * and as its real path, since the engine compares resolved real paths.+ */+export function pluginsNoDepsEnv(+ files: string[],+ realpath: (file: string) => string = realpathSync.native,+): Record<string, string> {+ const names = new Set<string>();+ for (const file of files) {+ names.add(file);+ try {+ names.add(realpath(file));+ } catch {+ // A plugin that is not on disk is never loaded; its name is enough.+ }+ }+ return names.size ? { OMNIRUSH_PLUGINS_NO_DEPS: [...names].join("\n") } : {};+}++/**+ * How long the engine may take to print its listening line. On Windows the+ * first start after an install or update also waits for the antivirus scan of+ * the new engine binary, which pushed past 15 s and failed the app's start.+ */+export function engineStartTimeoutMs(+ env: Record<string, string | undefined> = process.env,+ platform: NodeJS.Platform = process.platform,+): number {+ const asked = Number(env.OMNIRUSH_ENGINE_START_TIMEOUT_MS);+ if (Number.isFinite(asked) && asked > 0) return asked;+ return platform === "win32" ? 60_000 : 15_000;+}++function pidExists(pid: number | undefined): boolean {+ if (!pid) return false;+ try {+ process.kill(pid, 0);+ return true;+ } catch (error) {+ return error instanceof Error && "code" in error && error.code === "EPERM";+ }+}+export type ManagedOpencodeServer = {url: string;username: string;@@ -83,7 +133,11 @@ export function createManagedProcessClose(} catch {// Re-check below; kill can race a natural exit.}- if (!await waitForExit(options.killTimeoutMs ?? 500)) {+ if (await waitForExit(options.killTimeoutMs ?? (process.platform === "win32" ? 3_000 : 500))) return;+ // A busy main thread can see its timer before the exit event of a+ // process that is already gone (seen on Windows): ask the OS.+ const exists = options.processExists ?? (() => pidExists(child.pid));+ if (exists()) {throw new Error("Managed OmniRush process did not exit after SIGKILL");}})();@@ -216,7 +270,8 @@ async function startManagedOpencodeServer(let url: string;try {url = await new Promise<string>((resolve, reject) => {- const timeout = setTimeout(() => reject(new Error(`Timeout waiting for OmniRush server after ${options.timeoutMs ?? 15000}ms`)), options.timeoutMs ?? 15000);+ const timeoutMs = options.timeoutMs ?? engineStartTimeoutMs(env);+ const timeout = setTimeout(() => reject(new Error(`Timeout waiting for OmniRush server after ${timeoutMs}ms`)), timeoutMs);let output = "";const done = (value: string) => {clearTimeout(timeout);@@ -244,7 +299,11 @@ async function startManagedOpencodeServer(child.once("close", (code) => fail(new ManagedOpencodeExitError(code, output)));});} catch (error) {- await processLifecycle.close();+ // The start failure is the error to report; a failed cleanup only adds to it.+ const cleanup = await processLifecycle.close().then(() => null, (closeError: unknown) => closeError);+ if (cleanup && error instanceof Error) {+ error.message += ` (and the engine process could not be stopped: ${cleanup instanceof Error ? cleanup.message : String(cleanup)})`;+ }throw error;}diff --git a/apps/server/src/omnirush-runtime-config.test.ts b/apps/server/src/omnirush-runtime-config.test.tsindex 64a88d58..bd83ffda 100644--- a/apps/server/src/omnirush-runtime-config.test.ts+++ b/apps/server/src/omnirush-runtime-config.test.ts@@ -7,6 +7,7 @@ import {buildOmniRushRuntimeConfig,buildOmniRushRuntimeConfigObjectFromSnapshot,keepOmniRushRuntimeConfigFileFresh,+ omnirushOwnPluginPaths,omnirushRuntimeConfigFilePath,omnirushRuntimeSkillsDir,writeOmniRushRuntimeConfigFile,@@ -97,6 +98,14 @@ describe("omnirush runtime config file", () => {expect(String(plugins.at(-1))).toContain("omnirush-mcp-policy");});+ test("every plugin omnirush.ai configures is named as its own, so the engine never holds a project for their install", () => {+ const parsed = buildOmniRushRuntimeConfigObjectFromSnapshot({ plugin: ["[email protected]"] }, undefined, {}, undefined, undefined, undefined);+ const plugins = Array.isArray(parsed.plugin) ? parsed.plugin.map(String) : [];+ const own = new Set(omnirushOwnPluginPaths());+ expect(plugins.filter((plugin) => !own.has(plugin))).toEqual(["[email protected]"]);+ expect([...own].some((plugin) => /omnirush-box\.(?:ts|js)$/.test(plugin))).toBe(true);+ });+test("managed browser restrictions use scalar actions in global and agent permissions", () => {const parsed = buildOmniRushRuntimeConfigObjectFromSnapshot({managedPolicy: {diff --git a/apps/server/src/omnirush-runtime-config.ts b/apps/server/src/omnirush-runtime-config.tsindex b52e6110..25e13e04 100644--- a/apps/server/src/omnirush-runtime-config.ts+++ b/apps/server/src/omnirush-runtime-config.ts@@ -32,6 +32,7 @@ import {omnirushBuildathonPluginPath,omnirushChromeDevtoolsPluginPath,omnirushPdfAttachmentsPluginPath,+ omnirushPluginPath,} from "./omnirush-extensions-plugin-path.js";import type { ServerConfig } from "./types.js";import { runtimeStorageDir } from "./runtime-db.js";@@ -148,6 +149,47 @@ export async function buildOmniRushRuntimeConfigObject(return config ? withBoxEngineConfig(await boxServiceFor(config).engineBits(), built) : built;}+/** omnirush.ai's own engine plugins that go before the user's, in registration order. */+function omnirushLeadingPluginPaths(): string[] {+ return [+ managedPolicyPluginPath(),+ omnirushChromeDevtoolsPluginPath(),+ // Registration order is prompt order: the knowledge plugin appends the+ // operating rules first, then the extensions plugin adds app-control+ // mechanics, live Connect steering, and the remote skill and Automation+ // catalogs, so rules precede state and state precedes data.+ omnirushCapabilitiesKnowledgePluginPath(),+ omnirushExtensionsPreviewPluginPath(),+ omnirushBudgetWrapPluginPath(),+ omnirushOfficeAttachmentsPluginPath(),+ omnirushSpreadsheetsPluginPath(),+ omnirushPdfAttachmentsPluginPath(),+ omnirushAnthropicAdaptiveThinkingPluginPath(),+ omnirushAnthropicToolSchemaPluginPath(),+ omnirushReasoningEffortPluginPath(),+ omnirushTitleRecoveryPluginPath(),+ omnirushSwarmPluginPath(),+ // Buildathon projects only (the app lists them): the event's reproducibility rules.+ omnirushBuildathonPluginPath(),+ ];+}++/**+ * Every engine plugin file omnirush.ai ships. They are bundled and need no+ * npm install, so the engine is told (OMNIRUSH_PLUGINS_NO_DEPS) not to hold a+ * project's first request until its `.opencode` folder's background install+ * of @opencode-ai/plugin ends: on Windows that install took minutes, and+ * every prompt in a new project failed meanwhile. User plugins still wait.+ */+export function omnirushOwnPluginPaths(): string[] {+ return [+ ...omnirushLeadingPluginPaths(),+ managedPolicyPluginPath(true),+ omnirushMcpPolicyPluginPath(),+ omnirushPluginPath("omnirush-box"),+ ];+}+/*** The folder of omnirush.ai's own on-demand skills (the omnirush-swarm skill),* handed to the engine through `skills.paths`. It lives beside the runtime@@ -256,25 +298,7 @@ export function buildOmniRushRuntimeConfigObjectFromSnapshot(},},plugin: [- managedPolicyPluginPath(),- omnirushChromeDevtoolsPluginPath(),- // Registration order is prompt order: the knowledge plugin appends the- // operating rules first, then the extensions plugin adds app-control- // mechanics, live Connect steering, and the remote skill and Automation- // catalogs, so rules precede state and state precedes data.- omnirushCapabilitiesKnowledgePluginPath(),- omnirushExtensionsPreviewPluginPath(),- omnirushBudgetWrapPluginPath(),- omnirushOfficeAttachmentsPluginPath(),- omnirushSpreadsheetsPluginPath(),- omnirushPdfAttachmentsPluginPath(),- omnirushAnthropicAdaptiveThinkingPluginPath(),- omnirushAnthropicToolSchemaPluginPath(),- omnirushReasoningEffortPluginPath(),- omnirushTitleRecoveryPluginPath(),- omnirushSwarmPluginPath(),- // Buildathon projects only (the app lists them): the event's reproducibility rules.- omnirushBuildathonPluginPath(),+ ...omnirushLeadingPluginPaths(),...runtimePluginList(runtimeConfig),// This must be last: user/runtime plugins may not reintroduce MCP// configuration or replace the deny rules.diff --git a/apps/server/src/opencode-models-url.test.ts b/apps/server/src/opencode-models-url.test.tsindex f5b264cb..be26e9dd 100644--- a/apps/server/src/opencode-models-url.test.ts+++ b/apps/server/src/opencode-models-url.test.ts@@ -20,7 +20,7 @@ async function writeFakeOpencodeBin(root: string): Promise<string> {"const portIndex = process.argv.indexOf(\"--port\");","const port = portIndex >= 0 ? process.argv[portIndex + 1] : \"0\";","const capturePath = process.env.OMNIRUSH_CAPTURE_MODELS_URL_FILE;",- "if (capturePath) await Bun.write(capturePath, JSON.stringify({ url: process.env.OPENCODE_MODELS_URL ?? null, disableFetch: process.env.OPENCODE_DISABLE_MODELS_FETCH ?? null }));",+ "if (capturePath) await Bun.write(capturePath, JSON.stringify({ url: process.env.OPENCODE_MODELS_URL ?? null, disableFetch: process.env.OPENCODE_DISABLE_MODELS_FETCH ?? null, ownPluginsNoDeps: /omnirush-mcp-policy\\.(?:ts|js)$/m.test(process.env.OMNIRUSH_PLUGINS_NO_DEPS ?? \"\") }));","console.log(`opencode server listening on http://127.0.0.1:${port}`);","process.on(\"SIGTERM\", () => process.exit(0));","setInterval(() => undefined, 1_000);",@@ -128,10 +128,10 @@ describe("startEmbeddedServer managed OpenCode models URL", () => {expect(await captureEngineModelsEnv({devMode: "1",modelsUrl: "https://catalog.example.test/models",- })).toEqual({ url: "https://catalog.example.test/models", disableFetch: null });+ })).toEqual({ url: "https://catalog.example.test/models", disableFetch: null, ownPluginsNoDeps: true });});test("gives the engine no catalog URL and turns catalog fetches off by default", async () => {- expect(await captureEngineModelsEnv({})).toEqual({ url: null, disableFetch: "1" });+ expect(await captureEngineModelsEnv({})).toEqual({ url: null, disableFetch: "1", ownPluginsNoDeps: true });});});diff --git a/evals/specs/reliable-app-recovery.e2e.test.ts b/evals/specs/reliable-app-recovery.e2e.test.tsindex ab9f53a9..86a99120 100644--- a/evals/specs/reliable-app-recovery.e2e.test.ts+++ b/evals/specs/reliable-app-recovery.e2e.test.ts@@ -7,6 +7,7 @@ const verifiedArtifact = "https://releases.omnirush.test/v1.8.2/OmniRush.ai-darwtest("a fatal desktop bootstrap failure offers one-click verified recovery without losing the profile", async ({ world, user, seed, probe }) => {await user.see({ text: /OmniRush.ai (couldn't|could not) start/i });+ await user.see("Try again");await user.see("Restore previous version");await user.notSee({ text: /EVAL_FATAL_DESKTOP_BOOTSTRAP_FAILURE|invalid code signature/ });await user.notSee({ text: /GitHub|open an issue|download.*manually/i });@@ -35,4 +36,10 @@ test("a fatal desktop bootstrap failure offers one-click verified recovery withoexpect(requests).toEqual([{ version: "1.8.2", artifactUrl: verifiedArtifact }]);const final = await world.snapshot();expect(typeof final === "object" && final !== null ? Reflect.get(final, "quitRequested") : null).toBe(false);++ // Try again boots once more instead of replaying the first failure; this world's failure is permanent.+ await user.click("Try again");+ await user.see({ text: /OmniRush.ai (couldn't|could not) start/i });+ await user.see("Restore previous version");+ expect(await world.workspaceNames()).toContain("reliable-recovery-profile-marker");});