A desktop coding agent with free access to frontier models.
TypeScript
feat: keep the computer awake while the agent works
ogsamrat603ef36e32eb
diff --git a/apps/app/src/app/lib/desktop.ts b/apps/app/src/app/lib/desktop.tsindex 7af0c924..4f4f3b84 100644--- a/apps/app/src/app/lib/desktop.ts+++ b/apps/app/src/app/lib/desktop.ts@@ -782,6 +782,8 @@ const {omnirushAccountStatus,omnirushQualityDetails,omnirushQualitySpins,+ keepAwakeStatus,+ keepAwakeSet,omnirushSessionStatus,omnirushQualitySpin,omnirushAccountConnect,@@ -846,6 +848,8 @@ export {omnirushAccountStatus,omnirushQualityDetails,omnirushQualitySpins,+ keepAwakeStatus,+ keepAwakeSet,omnirushSessionStatus,omnirushQualitySpin,omnirushAccountConnect,diff --git a/apps/app/src/react-app/domains/settings/pages/general-view.tsx b/apps/app/src/react-app/domains/settings/pages/general-view.tsxindex fdd60065..32b22431 100644--- a/apps/app/src/react-app/domains/settings/pages/general-view.tsx+++ b/apps/app/src/react-app/domains/settings/pages/general-view.tsx@@ -2,6 +2,7 @@import { useEffect, useState } from "react";import {ArrowRight,+ Coffee,Cog,FolderLock,Mic,@@ -14,12 +15,14 @@ import {UserRoundCheck,} from "lucide-react";-import type { OmniRushAccountSignOutReason } from "@omnirush/types/desktop-ipc";+import type { KeepAwakeState, OmniRushAccountSignOutReason } from "@omnirush/types/desktop-ipc";import { Switch } from "@/components/ui/switch";import { t } from "../../../../i18n";import type { SettingsTab } from "../../../../app/types";import {+ keepAwakeSet,+ keepAwakeStatus,omnirushAccountConnect,omnirushAccountSignOut,omnirushAccountStatus,@@ -216,6 +219,66 @@ export function BestPracticesCard(props: {);}+export const KEEP_AWAKE_TITLE = "Keep this computer awake while the agent works";+export const KEEP_AWAKE_HELP = "Your computer won't go to sleep while a turn runs, or while the app finishes up as it quits. The screen can still turn off and lock.";++/** Settings > General > Keep awake: a desktop setting (keep-awake.mjs), on by default. */+export function KeepAwakeCard(props: {+ state: KeepAwakeState | null;+ busy: boolean;+ onToggle: (enabled: boolean) => void;+}) {+ const hint = props.state?.forcedOff+ ? "Off for this launch: OMNIRUSH_KEEP_AWAKE=0 is set."+ : props.state && !props.state.available+ ? "Not available in this session (remote login or CI)."+ : null;+ return (+ <div className="space-y-3">+ <div className="text-[11px] font-semibold uppercase tracking-[0.15em] text-dls-secondary">Power</div>+ <div className="flex items-center gap-4 rounded-2xl border border-dls-border bg-dls-surface p-4">+ <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-dls-border bg-dls-hover">+ <Coffee size={17} className="text-dls-secondary" />+ </div>+ <div className="min-w-0 flex-1">+ <div className="text-[13px] font-medium text-dls-text">{KEEP_AWAKE_TITLE}</div>+ <div id="keep-awake-help" className="text-[11px] text-dls-secondary">{KEEP_AWAKE_HELP}</div>+ {hint ? (+ <div className="mt-0.5 text-[11px] text-dls-secondary" role="status" data-testid="keep-awake-status">{hint}</div>+ ) : null}+ </div>+ <Switch+ aria-label={KEEP_AWAKE_TITLE}+ aria-describedby="keep-awake-help"+ checked={props.state?.enabled === true}+ disabled={props.busy || props.state === null}+ onCheckedChange={props.onToggle}+ />+ </div>+ </div>+ );+}++function useKeepAwake() {+ const [state, setState] = useState<KeepAwakeState | null>(null);+ const [busy, setBusy] = useState(false);+ useEffect(() => {+ if (!isElectronRuntime()) return;+ void keepAwakeStatus().then(setState).catch(() => setState(null));+ }, []);+ async function setEnabled(enabled: boolean) {+ setBusy(true);+ try {+ setState(await keepAwakeSet(enabled));+ } catch {+ setState(await keepAwakeStatus().catch(() => null));+ } finally {+ setBusy(false);+ }+ }+ return { state, busy, setEnabled };+}+export function GeneralSettingsView(props: GeneralSettingsViewProps) {const [account, setAccount] = useState<NativeAccountStatus | null>(null);const [accountBusy, setAccountBusy] = useState(false);@@ -226,6 +289,7 @@ export function GeneralSettingsView(props: GeneralSettingsViewProps) {const bestPractices = useBestPractices(bestPracticesClient);const linuxSandboxClient = props.linuxSandboxClient ?? null;const linuxSandbox = useLinuxSandbox(linuxSandboxClient, props.sandboxWorkspaceId ?? null);+ const keepAwake = useKeepAwake();useEffect(() => {if (!isElectronRuntime()) return;@@ -382,6 +446,14 @@ export function GeneralSettingsView(props: GeneralSettingsViewProps) {/>) : null}+ {isElectronRuntime() ? (+ <KeepAwakeCard+ state={keepAwake.state}+ busy={keepAwake.busy}+ onToggle={(enabled) => void keepAwake.setEnabled(enabled)}+ />+ ) : null}+{linuxSandboxClient && props.sandboxWorkspaceId ? (<LinuxSandboxCardbox={linuxSandbox.box}diff --git a/apps/desktop/electron/keep-awake.mjs b/apps/desktop/electron/keep-awake.mjsnew file mode 100644index 00000000..f42bd74b--- /dev/null+++ b/apps/desktop/electron/keep-awake.mjs@@ -0,0 +1,132 @@+// Keep the computer awake while the agent works.+//+// The local server says when the agent starts and stops working+// (apps/server/src/turn-activity.ts, `onTurnActivity`): from a prompt sent+// until no turn runs any more (finished, stopped or failed). Meanwhile, and+// while the uploads finish as the app quits, Electron's+// powerSaveBlocker 'prevent-app-suspension' holds off system sleep. The+// display still turns off and locks as usual, an idle open chat holds+// nothing, and the blocker goes with the app when it exits or crashes. No+// admin rights, no power setting is changed.+//+// On by default: Settings > General > "Keep this computer awake while the+// agent works" (<userData>/keep-awake.json), or OMNIRUSH_KEEP_AWAKE=0 for a+// launch. Skipped, silently, over SSH and in CI.++import { mkdir, readFile, rename, writeFile } from "node:fs/promises";+import path from "node:path";++export const KEEP_AWAKE_FILE = "keep-awake.json";+const OFF_WORDS = ["0", "off", "false", "no"];++/** Why keep awake never runs in this launch ("env", "ssh", "ci"), or null. */+export function keepAwakeSkipReason(env = process.env) {+ if (OFF_WORDS.includes(String(env.OMNIRUSH_KEEP_AWAKE ?? "").trim().toLowerCase())) return "env";+ if (env.SSH_CONNECTION || env.SSH_TTY || env.SSH_CLIENT) return "ssh";+ const ci = String(env.CI ?? "").trim().toLowerCase();+ if (ci && !OFF_WORDS.includes(ci)) return "ci";+ return null;+}++/** The saved setting: off only for { "enabled": false }. */+export async function readKeepAwakeSetting(file) {+ try {+ const parsed = JSON.parse(await readFile(file, "utf8"));+ return !(parsed && typeof parsed === "object" && parsed.enabled === false);+ } catch {+ return true;+ }+}++export async function writeKeepAwakeSetting(file, enabled) {+ await mkdir(path.dirname(file), { recursive: true });+ const temp = `${file}.${process.pid}.tmp`;+ await writeFile(temp, `${JSON.stringify({ enabled: enabled === true })}\n`, { mode: 0o600 });+ await rename(temp, file);+}++/**+ * @param {{+ * powerSaveBlocker: { start: (type: "prevent-app-suspension") => number, stop: (id: number) => void, isStarted: (id: number) => boolean },+ * settingFile: string,+ * env?: NodeJS.ProcessEnv,+ * log?: (line: string) => void,+ * }} deps+ */+export function createKeepAwake({ powerSaveBlocker, settingFile, env = process.env, log = (line) => console.log(line) }) {+ const skip = keepAwakeSkipReason(env);+ let enabled = true;+ let running = false;+ let holds = 0;+ let stopped = false;+ /** @type {number | null} */+ let blocker = null;+ if (skip) log(`[keep-awake] skipped (${skip})`);++ function sync() {+ const wanted = !stopped && !skip && enabled && (running || holds > 0);+ if (wanted && blocker === null) {+ try {+ blocker = powerSaveBlocker.start("prevent-app-suspension");+ log(`[keep-awake] started id=${blocker} isStarted=${powerSaveBlocker.isStarted(blocker)}`);+ } catch (error) {+ blocker = null;+ log(`[keep-awake] could not start: ${error instanceof Error ? error.message : String(error)}`);+ }+ } else if (!wanted && blocker !== null) {+ const id = blocker;+ blocker = null;+ try {+ powerSaveBlocker.stop(id);+ log(`[keep-awake] stopped id=${id} isStarted=${powerSaveBlocker.isStarted(id)}`);+ } catch (error) {+ log(`[keep-awake] could not stop: ${error instanceof Error ? error.message : String(error)}`);+ }+ }+ }++ const loaded = readKeepAwakeSetting(settingFile).then((value) => {+ enabled = value;+ sync();+ });++ function state() {+ return { enabled, active: blocker !== null, available: skip === null || skip === "env", forcedOff: skip === "env" };+ }++ return {+ loaded,+ /** The local server: the agent started (true) or stopped (false) working. */+ setTurnRunning(value) {+ running = value === true;+ sync();+ },+ /** Kept on for other work (the uploads as the app quits); returns its release. */+ hold() {+ holds += 1;+ sync();+ let released = false;+ return () => {+ if (released) return;+ released = true;+ holds -= 1;+ sync();+ };+ },+ async setEnabled(value) {+ await loaded;+ enabled = value === true;+ await writeKeepAwakeSetting(settingFile, enabled);+ sync();+ return state();+ },+ async status() {+ await loaded;+ return state();+ },+ stop() {+ stopped = true;+ sync();+ },+ };+}diff --git a/apps/desktop/electron/keep-awake.test.mjs b/apps/desktop/electron/keep-awake.test.mjsnew file mode 100644index 00000000..f700480e--- /dev/null+++ b/apps/desktop/electron/keep-awake.test.mjs@@ -0,0 +1,141 @@+import assert from "node:assert/strict";+import { mkdtemp, readFile, stat } from "node:fs/promises";+import { readFileSync } from "node:fs";+import os from "node:os";+import path from "node:path";+import test from "node:test";+import { fileURLToPath } from "node:url";++import { KEEP_AWAKE_FILE, createKeepAwake, keepAwakeSkipReason, readKeepAwakeSetting, writeKeepAwakeSetting } from "./keep-awake.mjs";++const here = path.dirname(fileURLToPath(import.meta.url));++/** Electron's powerSaveBlocker, recorded. */+function fakeBlocker() {+ const started = new Set();+ const calls = [];+ let next = 1;+ return {+ calls,+ started,+ start(type) {+ calls.push(["start", type]);+ const id = next++;+ started.add(id);+ return id;+ },+ stop(id) {+ calls.push(["stop", id]);+ started.delete(id);+ },+ isStarted: (id) => started.has(id),+ };+}++/** @param {{ env?: NodeJS.ProcessEnv, saved?: boolean }} [options] */+async function setup({ env = {}, saved } = {}) {+ const dir = await mkdtemp(path.join(os.tmpdir(), "keep-awake-"));+ const settingFile = path.join(dir, KEEP_AWAKE_FILE);+ if (saved !== undefined) await writeKeepAwakeSetting(settingFile, saved);+ const blocker = fakeBlocker();+ const lines = [];+ const awake = createKeepAwake({ powerSaveBlocker: blocker, settingFile, env, log: (line) => lines.push(line) });+ await awake.loaded;+ return { awake, blocker, lines, settingFile };+}++test("prevent-app-suspension only while a turn runs (system sleep only, never the display)", async () => {+ const { awake, blocker, lines } = await setup();+ assert.equal(blocker.calls.length, 0, "an idle open chat holds nothing");+ awake.setTurnRunning(true);+ assert.deepEqual(blocker.calls, [["start", "prevent-app-suspension"]]);+ assert.equal(blocker.started.size, 1);+ awake.setTurnRunning(true);+ assert.equal(blocker.calls.length, 1, "one blocker for every running turn");+ awake.setTurnRunning(false);+ assert.deepEqual(blocker.calls.at(-1), ["stop", 1]);+ assert.equal(blocker.started.size, 0);+ assert.deepEqual(lines, ["[keep-awake] started id=1 isStarted=true", "[keep-awake] stopped id=1 isStarted=false"]);+ assert.ok(!blocker.calls.some(([, type]) => type === "prevent-display-sleep"));+});++test("held while the app finishes as it quits, then released", async () => {+ const { awake, blocker } = await setup();+ awake.setTurnRunning(true);+ const release = awake.hold();+ awake.setTurnRunning(false);+ assert.equal(blocker.started.size, 1, "still held for the quit");+ release();+ release();+ assert.equal(blocker.started.size, 0);+ const again = awake.hold();+ assert.equal(blocker.started.size, 1, "a quit with no turn running holds it too");+ awake.stop();+ assert.equal(blocker.started.size, 0);+ again();+ awake.setTurnRunning(true);+ assert.equal(blocker.started.size, 0, "nothing after stop");+});++test("the setting: on by default, saved off, toggled live", async () => {+ const { awake, blocker, settingFile } = await setup();+ assert.deepEqual(await awake.status(), { enabled: true, active: false, available: true, forcedOff: false });+ awake.setTurnRunning(true);+ assert.equal((await awake.status()).active, true);+ // Turned off mid-turn: released at once, and saved.+ assert.deepEqual(await awake.setEnabled(false), { enabled: false, active: false, available: true, forcedOff: false });+ assert.equal(blocker.started.size, 0);+ assert.deepEqual(JSON.parse(await readFile(settingFile, "utf8")), { enabled: false });+ if (process.platform !== "win32") assert.equal((await stat(settingFile)).mode & 0o777, 0o600);+ // Back on while the turn still runs: held again.+ assert.equal((await awake.setEnabled(true)).active, true);+ assert.equal(await readKeepAwakeSetting(settingFile), true);++ const off = await setup({ saved: false });+ off.awake.setTurnRunning(true);+ off.awake.hold();+ assert.equal(off.blocker.calls.length, 0);+ assert.equal((await off.awake.status()).enabled, false);+ assert.equal(await readKeepAwakeSetting(path.join(os.tmpdir(), "missing-keep-awake.json")), true);+});++test("skipped over SSH, in CI and with OMNIRUSH_KEEP_AWAKE=0", async () => {+ assert.equal(keepAwakeSkipReason({}), null);+ assert.equal(keepAwakeSkipReason({ SSH_CONNECTION: "1 2 3 4" }), "ssh");+ assert.equal(keepAwakeSkipReason({ SSH_TTY: "/dev/pts/1" }), "ssh");+ assert.equal(keepAwakeSkipReason({ CI: "true" }), "ci");+ assert.equal(keepAwakeSkipReason({ CI: "false" }), null);+ assert.equal(keepAwakeSkipReason({ OMNIRUSH_KEEP_AWAKE: "0" }), "env");+ for (const env of [{ SSH_CONNECTION: "x" }, { CI: "1" }, { OMNIRUSH_KEEP_AWAKE: "off" }]) {+ const { awake, blocker } = await setup({ env });+ awake.setTurnRunning(true);+ awake.hold();+ assert.equal(blocker.calls.length, 0, JSON.stringify(env));+ }+ assert.deepEqual(await (await setup({ env: { SSH_CONNECTION: "x" } })).awake.status(), { enabled: true, active: false, available: false, forcedOff: false });+ assert.deepEqual(await (await setup({ env: { OMNIRUSH_KEEP_AWAKE: "0" } })).awake.status(), { enabled: true, active: false, available: true, forcedOff: true });+});++test("a blocker that cannot start never fails the turn", async () => {+ const dir = await mkdtemp(path.join(os.tmpdir(), "keep-awake-"));+ const lines = [];+ const awake = createKeepAwake({+ powerSaveBlocker: { start: () => { throw new Error("no power manager"); }, stop: () => undefined, isStarted: () => false },+ settingFile: path.join(dir, KEEP_AWAKE_FILE),+ env: {},+ log: (line) => lines.push(line),+ });+ await awake.loaded;+ assert.doesNotThrow(() => awake.setTurnRunning(true));+ assert.match(lines.join("\n"), /could not start: no power manager/);+});++test("main wires the server's turn activity, the quit and the settings commands", () => {+ const main = readFileSync(path.join(here, "main.mjs"), "utf8");+ assert.ok(main.includes("onTurnActivity: (running) => keepAwake.setTurnRunning(running)"));+ assert.ok(main.includes("const releaseKeepAwake = keepAwake.hold();"));+ assert.ok(main.includes('"keepAwakeStatus": async () => keepAwake.status()'));+ assert.ok(main.includes('"keepAwakeSet": async (event, ...args) => keepAwake.setEnabled(args[0] === true)'));+ const runtime = readFileSync(path.join(here, "runtime.mjs"), "utf8");+ assert.ok(runtime.includes('...(typeof onTurnActivity === "function" ? { onTurnActivity } : {}),'));+});diff --git a/apps/desktop/electron/main.mjs b/apps/desktop/electron/main.mjsindex c0fcf863..80e6ea0a 100644--- a/apps/desktop/electron/main.mjs+++ b/apps/desktop/electron/main.mjs@@ -94,6 +94,7 @@ import {} from "./sentry.mjs";import { installStdioErrorHandlers } from "./stdio-errors.mjs";import { createTurnGuard } from "./turn-guard.mjs";+import { KEEP_AWAKE_FILE, createKeepAwake } from "./keep-awake.mjs";import {createRendererCrashRecovery,installSocketTypeOfServiceGuard,@@ -116,6 +117,7 @@ const {nativeTheme,net: electronNet,powerMonitor,+ powerSaveBlocker,Notification: ElectronNotification,session,shell,@@ -1386,6 +1388,12 @@ function omnirushUiMcpLaunch() {});}+// The computer stays awake while the agent works (keep-awake.mjs): the local server says when.+const keepAwake = createKeepAwake({+ powerSaveBlocker,+ settingFile: path.join(app.getPath("userData"), KEEP_AWAKE_FILE),+});+const runtimeManager = createRuntimeManager({app,desktopRoot: path.resolve(__dirname, ".."),@@ -1416,6 +1424,8 @@ const runtimeManager = createRuntimeManager({omnirushGatewayCredentials: omnirushAccountStore,// The gateway's x-omnirush-update-required header and 426 refusals.onUpdateSignal: (signal) => updateGate.signal(signal),+ // The agent started or stopped working (apps/server/src/turn-activity.ts).+ onTurnActivity: (running) => keepAwake.setTurnRunning(running),// Session upload envelopes report environment.app_version from the desktop build, not the server package.appVersion: app.getVersion(),});@@ -2563,6 +2573,8 @@ const desktopCommandHandlers = {"__setApplicationMenuVisible": async (event, ...args) => {return applicationMenu.setVisible(args[0]);},+ "keepAwakeStatus": async () => keepAwake.status(),+ "keepAwakeSet": async (event, ...args) => keepAwake.setEnabled(args[0] === true),"__setTurnRunning": async (event, ...args) => {return turnGuard.setTurnRunning(args[0] === true);},@@ -2998,6 +3010,8 @@ or use: pnpm dev:worktree`);showShutdownScreen();desktopAutomationRunner.stop();browserLoginSync.shutdown();+ // The uploads finish as the services stop: the computer stays awake for them.+ const releaseKeepAwake = keepAwake.hold();runDetachedTask("stop services before quit", async () => {// Re-check the update feed while services stop, so a download staged// before newer releases shipped is replaced by the newest one instead@@ -3010,6 +3024,8 @@ or use: pnpm dev:worktree`);terminalSessions.killAll(),]);} finally {+ releaseKeepAwake();+ keepAwake.stop();scheduleBlankSlateProfileCleanup();const installUpdateAndQuit = await updateInstall;if (installUpdateAndQuit) installUpdateAndQuit();diff --git a/apps/desktop/electron/runtime.mjs b/apps/desktop/electron/runtime.mjsindex 3b7e441e..23698804 100644--- a/apps/desktop/electron/runtime.mjs+++ b/apps/desktop/electron/runtime.mjs@@ -1430,6 +1430,8 @@ export function createRuntimeManager({captureFileUpload = null,// Hears the gateway's mandatory-update header and 426 refusals (update-gate.mjs).onUpdateSignal = null,+ // Hears when the agent starts and stops working (keep-awake.mjs).+ onTurnActivity = null,}) {const inheritedProcessEnv = { ...process.env };let injectedUserEnvKeys = new Set();@@ -2225,6 +2227,7 @@ export function createRuntimeManager({appVersion: typeof appVersion === "string" && appVersion.trim() ? appVersion.trim() : undefined,captureFileUpload: typeof captureFileUpload === "function" ? captureFileUpload : undefined,clearUploadQueue,+ ...(typeof onTurnActivity === "function" ? { onTurnActivity } : {}),// Bundled UI-control MCP launch for the startup migration of persisted// `npx -y omnirush-ui-mcp` entries; null removes those entries instead.omnirushUiMcp: omnirushUiMcpLaunch() ?? null,diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 718f035c..e4a87e06 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/turn-guard.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/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: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"},diff --git a/apps/server/src/embedded.ts b/apps/server/src/embedded.tsindex 0487d0e3..bdba86c9 100644--- a/apps/server/src/embedded.ts+++ b/apps/server/src/embedded.ts@@ -30,6 +30,7 @@ import {clearTrustedOpencodeProcess,collectBusyEngineSessions,createEnginePoolForConfig,+ stopTurnActivity,createServerLogger,registerTrustedOpencodeProcess,startServer,@@ -65,6 +66,8 @@ export type EmbeddedServerOptions = CliArgs & {captureFileUpload?: CaptureFileUpload;/** The user signed out since the last start: queued uploads and archives are deleted first. */clearUploadQueue?: boolean;+ /** Called when the agent starts working (a prompt went out) and when no turn runs any more. */+ onTurnActivity?: (running: boolean) => void;/*** How the embedding desktop launches its bundled UI-control MCP. Persisted* entries still using `npx -y omnirush-ui-mcp` are rewritten to it before@@ -104,6 +107,7 @@ export async function startEmbeddedServer(options: EmbeddedServerOptions): Promiconfig.appVersion = typeof options.appVersion === "string" && options.appVersion.trim() ? options.appVersion.trim() : undefined;config.captureFileUpload = options.captureFileUpload;config.clearUploadQueue = options.clearUploadQueue === true;+ config.onTurnActivity = options.onTurnActivity;const logger = createServerLogger(config);// Spawn managed OpenCode if requested and no explicit base URL was provided.@@ -118,6 +122,7 @@ export async function startEmbeddedServer(options: EmbeddedServerOptions): Promiconst releaseResources = async (): Promise<void> => {const errors: unknown[] = [];+ stopTurnActivity(config);try { await stopTaskRecovery(config); } catch (error) { errors.push(error); }const identity = managedOpencodeIdentity;diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex 1bd86cc8..74d0d978 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -215,6 +215,7 @@ import pkg from "../package.json" with { type: "json" };import constants from "../../../constants.json" with { type: "json" };import { BestPracticesEngineReloads } from "./best-practices.js";import { BUNDLED_ENGINE_VERSION } from "./engine-identity.js";+import { createTurnActivity, type TurnActivity } from "./turn-activity.js";export {isSupportedWorkspaceTextFilePath,@@ -231,6 +232,25 @@ const agentDiagnosticsLastRunByServer = new WeakMap<ServerConfig, Map<string, nuconst agentDiagnosticsInFlightByServer = new WeakMap<ServerConfig, Set<string>>();const commandAdmissionsByServer = new WeakMap<ServerConfig, Map<string, { fingerprint: string; admittedAt: number }>>();const captureServicesByServer = new WeakMap<ServerConfig, CaptureService>();+const turnActivityByServer = new WeakMap<ServerConfig, TurnActivity>();++/** Whether the agent works on this server's engine (turn-activity.ts), for an embedding app that asked (onTurnActivity). */+function turnActivityFor(config: ServerConfig): TurnActivity | null {+ const onChange = config.onTurnActivity;+ if (!onChange) return null;+ let activity = turnActivityByServer.get(config);+ if (!activity) {+ activity = createTurnActivity({ busy: () => collectBusyEngineSessions(config), onChange });+ turnActivityByServer.set(config, activity);+ }+ return activity;+}++/** The server stops: no turn runs on it any more. */+export function stopTurnActivity(config: ServerConfig): void {+ turnActivityByServer.get(config)?.stop();+ turnActivityByServer.delete(config);+}/** Voice dictation's broker hop (omnirush-voice.ts), per server. */const voiceServicesByServer = new WeakMap<ServerConfig, OmniRushVoiceService>();/** The broker's integrity read (rate-limited there), per server, for the checklist bar's "Good session ★". */@@ -1716,6 +1736,9 @@ export async function proxyOpencodeV2Request(input: {}await awaitOmniRushModelCatalogSettled(input.config);}+ // The agent works from here (the prompt is on its way) until the engine runs no session.+ const turnActivity = promptDispatch && collectible && sessionId !== null ? turnActivityFor(input.config) : null;+ turnActivity?.promptDispatched();const target = new URL(input.connection.url);target.pathname = forwardedPath;target.search = input.url.search;@@ -1836,6 +1859,8 @@ export async function proxyOpencodeV2Request(input: {capture.archiveSessionStarted(uploadedSessionId, input.workspace.path, engine);}const response = await loopbackFetch(target.toString(), { method, headers, body, signal: input.recoverySignal });+ // The engine has the prompt: its session status says busy from now on.+ turnActivity?.promptDispatched();if (capture && uploadedSessionId && engine) {capture.recordTrace(uploadedSessionId, "engine.response", { method, path: routePath, status: response.status });if (response.ok) capture.observeSession(uploadedSessionId, engine);@@ -2188,6 +2213,11 @@ export async function proxyOpencodeRequest(input: {: await input.request.arrayBuffer().then((buf) => (buf.byteLength > 0 ? buf : undefined));const capture = workspace ? captureServicesByServer.get(input.config) : undefined;const uploadedSessionId = uploadSessionId(proxyPath);+ // The agent works from here (the prompt is on its way) until the engine runs no session.+ const turnActivity = workspace && workspace.workspaceType !== "remote" && uploadedSessionId && isUploadPromptDispatch(method, proxyPath)+ ? turnActivityFor(input.config)+ : null;+ turnActivity?.promptDispatched();const deletedUploadedSessionId = uploadDeletedSessionId(method, proxyPath);// A chat the engine does not have (a stale tab, a deleted chat) is not// started: its prompt is refused, and it would only leave an empty start@@ -2415,6 +2445,8 @@ export async function proxyOpencodeRequest(input: {const forwardAndUpload = async () => {const response = await forward();+ // The engine has the prompt: its session status says busy from now on.+ turnActivity?.promptDispatched();if (capture?.uploadEnabled && uploadedSessionId && steer) {if (workspace && response.ok) steered(capture, uploadedSessionId, engineTarget(served.baseUrl, served.headers, search));} else if (capture?.uploadEnabled && uploadedSessionId) {diff --git a/apps/server/src/turn-activity.test.ts b/apps/server/src/turn-activity.test.tsnew file mode 100644index 00000000..836d75cf--- /dev/null+++ b/apps/server/src/turn-activity.test.ts@@ -0,0 +1,87 @@+import { describe, expect, test } from "bun:test";++import { createTurnActivity } from "./turn-activity.js";++type Busy = { sessions: string[]; unknown: number };++function harness(initial: Busy | Error = { sessions: [], unknown: 0 }) {+ let clock = 1_000;+ let answer: Busy | Error = initial;+ const changes: boolean[] = [];+ const activity = createTurnActivity({+ busy: async () => {+ if (answer instanceof Error) throw answer;+ return answer;+ },+ onChange: (running) => changes.push(running),+ pollMs: 5,+ graceMs: 1_000,+ unknownLimitMs: 10_000,+ now: () => clock,+ });+ return {+ activity,+ changes,+ advance: (ms: number) => { clock += ms; },+ answer: (next: Busy | Error) => { answer = next; },+ };+}++const settle = () => new Promise((resolve) => setTimeout(resolve, 30));++describe("turn activity", () => {+ test("running from the prompt dispatch until the engine runs no session", async () => {+ const h = harness({ sessions: ["ses_1"], unknown: 0 });+ expect(h.activity.running).toBe(false);+ h.activity.promptDispatched();+ expect(h.changes).toEqual([true]);+ h.activity.promptDispatched();+ expect(h.changes).toEqual([true]);+ h.advance(5_000);+ await settle();+ expect(h.activity.running).toBe(true);+ // The turn ended (finished, stopped or failed: the engine is idle either way).+ h.answer({ sessions: [], unknown: 0 });+ await settle();+ expect(h.changes).toEqual([true, false]);+ h.activity.stop();+ });++ test("a prompt still on its way is not let go (grace after the last dispatch)", async () => {+ const h = harness({ sessions: [], unknown: 0 });+ h.activity.promptDispatched();+ await settle();+ expect(h.activity.running).toBe(true);+ h.advance(1_001);+ await settle();+ expect(h.changes).toEqual([true, false]);+ h.activity.stop();+ });++ test("an unreadable status counts as running, for a limited time", async () => {+ const h = harness(new Error("engine gone"));+ h.activity.promptDispatched();+ h.advance(2_000);+ await settle();+ expect(h.activity.running).toBe(true);+ h.advance(10_001);+ await settle();+ expect(h.changes).toEqual([true, false]);+ h.activity.stop();+ });++ test("stop ends it (the server stops)", () => {+ const h = harness({ sessions: ["ses_1"], unknown: 0 });+ h.activity.promptDispatched();+ h.activity.stop();+ expect(h.changes).toEqual([true, false]);+ h.activity.promptDispatched();+ expect(h.changes).toEqual([true, false]);+ });++ test("a listener that throws never stops the server", () => {+ const activity = createTurnActivity({ busy: async () => ({ sessions: [], unknown: 0 }), onChange: () => { throw new Error("boom"); } });+ expect(() => activity.promptDispatched()).not.toThrow();+ activity.stop();+ });+});diff --git a/apps/server/src/turn-activity.ts b/apps/server/src/turn-activity.tsnew file mode 100644index 00000000..1647833d--- /dev/null+++ b/apps/server/src/turn-activity.ts@@ -0,0 +1,89 @@+// Whether the agent is working: from a prompt dispatch until the engine+// reports no running session. The desktop keeps the computer awake while it+// is (apps/desktop/electron/keep-awake.mjs); the embedding app gets every+// change through `onTurnActivity`.+//+// A dispatch marks it running at once (before the prompt's hooks, so "from+// the prompt sent") and again when the engine has taken the prompt. While it+// runs, the engine's session status is read every `pollMs`; once no session+// runs and the last dispatch is older than `graceMs`, it stops. Unreadable+// status counts as running, for at most `unknownLimitMs`.++export type TurnActivityOptions = {+ busy: () => Promise<{ sessions: string[]; unknown: number }>;+ onChange: (running: boolean) => void;+ pollMs?: number;+ graceMs?: number;+ unknownLimitMs?: number;+ now?: () => number;+};++export type TurnActivity = {+ promptDispatched: () => void;+ readonly running: boolean;+ stop: () => void;+};++export function createTurnActivity(options: TurnActivityOptions): TurnActivity {+ const pollMs = options.pollMs ?? 2_000;+ const graceMs = options.graceMs ?? 5_000;+ const unknownLimitMs = options.unknownLimitMs ?? 120_000;+ const now = options.now ?? Date.now;+ let running = false;+ let stopped = false;+ let lastDispatch = 0;+ let unknownSince: number | null = null;+ let timer: ReturnType<typeof setTimeout> | null = null;++ const emit = (value: boolean) => {+ if (running === value) return;+ running = value;+ try {+ options.onChange(value);+ } catch {+ // The listener never stops the server.+ }+ };++ const schedule = () => {+ if (timer || stopped || !running) return;+ timer = setTimeout(() => void check(), pollMs);+ timer.unref?.();+ };++ const check = async () => {+ timer = null;+ if (stopped || !running) return;+ const busy = await options.busy().catch(() => null);+ const at = now();+ if (busy && busy.sessions.length > 0) {+ unknownSince = null;+ } else if (!busy || busy.unknown > 0) {+ unknownSince ??= at;+ if (at - unknownSince >= unknownLimitMs && at - lastDispatch >= graceMs) emit(false);+ } else if (at - lastDispatch >= graceMs) {+ unknownSince = null;+ emit(false);+ }+ schedule();+ };++ return {+ promptDispatched() {+ if (stopped) return;+ lastDispatch = now();+ unknownSince = null;+ emit(true);+ schedule();+ },+ get running() {+ return running;+ },+ stop() {+ stopped = true;+ if (timer) clearTimeout(timer);+ timer = null;+ emit(false);+ },+ };+}diff --git a/apps/server/src/types.ts b/apps/server/src/types.tsindex 5e90dfd6..81889101 100644--- a/apps/server/src/types.ts+++ b/apps/server/src/types.ts@@ -163,6 +163,8 @@ export interface ServerConfig {captureFileUpload?: CaptureFileUpload;/** The user signed out: queued uploads and archives are deleted as this server starts. */clearUploadQueue?: boolean;+ /** Called when the agent starts or stops working (turn-activity.ts); the desktop keeps the computer awake meanwhile. */+ onTurnActivity?: (running: boolean) => void;}export interface Capabilities {diff --git a/packages/types/src/desktop-ipc.ts b/packages/types/src/desktop-ipc.tsindex f87f56a0..64055758 100644--- a/packages/types/src/desktop-ipc.ts+++ b/packages/types/src/desktop-ipc.ts@@ -343,6 +343,12 @@ export type OmniRushQualitySpinRecord = {paidTokens: number | null;};+/**+ * Keep this computer awake while the agent works (apps/desktop/electron/keep-awake.mjs).+ * `available`: false over SSH or in CI, where it never runs; `forcedOff`: OMNIRUSH_KEEP_AWAKE=0 for this launch.+ */+export type KeepAwakeState = { enabled: boolean; active: boolean; available: boolean; forcedOff: boolean };+/** GET /me/quality/spins: totals and the newest spins (up to 10). */export type OmniRushQualitySpinTotals = { spun: number; paidTokens: number; recent: OmniRushQualitySpinRecord[] };@@ -823,6 +829,8 @@ export type DesktopCommandMap = {};omnirushQualityDetails: { args: []; result: OmniRushQualityDetails | null };omnirushQualitySpins: { args: []; result: OmniRushQualitySpinTotals | null };+ keepAwakeStatus: { args: []; result: KeepAwakeState };+ keepAwakeSet: { args: [enabled: boolean]; result: KeepAwakeState };omnirushSessionStatus: { args: [input: { sessionId: string }]; result: OmniRushSessionStatus | null };omnirushQualitySpin: {args: [input: { idempotencyKey: string }];