Skip to content

armgit / Orkas

Public Imported from GitHub
0

Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.

fix(local-agents): exclude system sleep from CLI idle time

CloudTianTianae99ea7c8507
diff --git a/src/main/features/local_agents/runner.ts b/src/main/features/local_agents/runner.ts
index 1b97545f..ec3ff1b4 100644
--- a/src/main/features/local_agents/runner.ts
+++ b/src/main/features/local_agents/runner.ts
@@ -1360,7 +1360,16 @@ export async function run(opts: RunCliAgentOpts): Promise<RunCliAgentResult> {
let remoteMediaScheduledCount = 0;
let remoteMediaReservedBytes = 0;
let remoteMediaDeadlineAt = 0;
- const activityClock = new AgentActivityClock();
+ let idleNow = () => Date.now();
+ try {
+ const { getSystemActivityClock } = await import('../system_activity');
+ idleNow = await getSystemActivityClock();
+ } catch {
+ // Preserve existing timeout behavior when the OS event source is absent;
+ // a quiet CLI or a clock jump is never evidence of system suspension.
+ log.warn('CLI system suspension clock unavailable; retaining wall-clock idle timeout');
+ }
+ const activityClock = new AgentActivityClock(idleNow);
let lastVisibleActivityAt = Date.now();
const bridgeSkillRefByCallId = new Map<string, string>();
let bridge: BridgeHandle | null = null;
diff --git a/src/main/features/system_activity.ts b/src/main/features/system_activity.ts
index 07410dda..ca543d68 100644
--- a/src/main/features/system_activity.ts
+++ b/src/main/features/system_activity.ts
@@ -22,7 +22,7 @@ export class SystemActivityTracker {
constructor(
private readonly monitor: PowerMonitorLike,
- private readonly now: () => number = Date.now,
+ private readonly now: () => number = () => Date.now(),
) {}
start(): void {
@@ -45,6 +45,13 @@ export class SystemActivityTracker {
};
}
+ /** Synchronous clock for idle budgets. Pending suspension is excluded even
+ * if a watchdog tick arrives before the OS resume event is delivered. */
+ awakeNow = (): number => {
+ const snapshot = this.snapshot();
+ return snapshot.wall_time_ms - snapshot.suspended_total_ms;
+ };
+
private onSuspend(): void {
if (this.suspendedAtMs != null) return;
this.suspendedAtMs = this.now();
@@ -61,10 +68,21 @@ export class SystemActivityTracker {
let trackerPromise: Promise<SystemActivityTracker> | null = null;
-export async function getSystemActivitySnapshot(): Promise<SystemActivitySnapshot> {
+async function getTracker(): Promise<SystemActivityTracker> {
if (!trackerPromise) {
trackerPromise = import('electron').then(({ powerMonitor }) => new SystemActivityTracker(powerMonitor));
}
const tracker = await trackerPromise;
- return tracker.snapshot();
+ tracker.start();
+ return tracker;
+}
+
+export async function getSystemActivitySnapshot(): Promise<SystemActivitySnapshot> {
+ return (await getTracker()).snapshot();
+}
+
+/** Register authoritative OS events before starting CLI idle measurement.
+ * One process-wide tracker serves all runs; no per-run listeners or polling. */
+export async function getSystemActivityClock(): Promise<() => number> {
+ return (await getTracker()).awakeNow;
}
diff --git a/src/main/util/agent-execution-budget.ts b/src/main/util/agent-execution-budget.ts
index 1d8395f0..78174cd7 100644
--- a/src/main/util/agent-execution-budget.ts
+++ b/src/main/util/agent-execution-budget.ts
@@ -10,24 +10,32 @@ export function agentExecutionDeadline(startedAt = Date.now()): number {
return startedAt + AGENT_EXECUTION_MAX_MS;
}
-/** Pause only the idle clock during an authoritative user interaction. Nested
- * waits are counted so one approval cannot resume another outstanding wait. */
+/** Measure idle time on the supplied clock (CLI hosts exclude OS suspension).
+ * Nested user waits pause that same clock, so sleep overlapping an approval is
+ * never deducted twice. Absolute execution deadlines remain wall-clock based. */
export class AgentActivityClock {
- private lastActivity = Date.now();
+ private lastActivity: number;
private waitStarted = 0;
private waits = 0;
- progress(): void { this.lastActivity = Date.now(); }
- lastEventAt = (): number => this.waits ? Date.now() : this.lastActivity;
+ constructor(private readonly now: () => number = () => Date.now()) {
+ this.lastActivity = now();
+ }
+
+ progress(): void { this.lastActivity = this.now(); }
+ // Preserve the watchdog's wall-timestamp contract without changing every
+ // backend: project only the remaining awake idle duration onto wall time.
+ lastEventAt = (): number => Date.now() - (this.waits ? 0 : Math.max(0, this.now() - this.lastActivity));
pause(): () => void {
- if (this.waits++ === 0) this.waitStarted = Date.now();
+ if (this.waits++ === 0) this.waitStarted = this.now();
let released = false;
return () => {
if (released) return;
released = true;
if (--this.waits === 0) {
- this.lastActivity = Math.min(Date.now(), this.lastActivity + Date.now() - this.waitStarted);
+ const now = this.now();
+ this.lastActivity = Math.min(now, this.lastActivity + now - this.waitStarted);
}
};
}
diff --git a/test/main/features/local_agents/runner.test.ts b/test/main/features/local_agents/runner.test.ts
index d7223b87..b3d14833 100644
--- a/test/main/features/local_agents/runner.test.ts
+++ b/test/main/features/local_agents/runner.test.ts
@@ -11,6 +11,14 @@ const mockDetect = vi.fn<[string], Promise<any>>();
const mockCliFallback = vi.fn<[any], any>();
const mockCliFailure = vi.fn();
const mockCliSuccess = vi.fn();
+const suspensionClock = vi.hoisted(() => ({ suspended: 0, unavailable: false }));
+vi.mock('../../../../src/main/features/system_activity', async (importOriginal) => ({
+ ...await importOriginal<typeof import('../../../../src/main/features/system_activity')>(),
+ getSystemActivityClock: async () => {
+ if (suspensionClock.unavailable) throw new Error('fixture power monitor unavailable');
+ return () => Date.now() - suspensionClock.suspended;
+ },
+}));
vi.mock('../../../../src/main/features/local_agents/registry', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../../../src/main/features/local_agents/registry')>();
return {
@@ -86,6 +94,8 @@ const PNG_1X1_BASE64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR4
const MP4_FTYP = Buffer.from('000000186674797069736f6d0000020069736f6d69736f32', 'hex');
beforeEach(async () => {
+ suspensionClock.suspended = 0;
+ suspensionClock.unavailable = false;
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-runner-'));
prevWs = process.env.ORKAS_WORKSPACE_ROOT;
process.env.ORKAS_WORKSPACE_ROOT = tmpDir;
@@ -154,6 +164,34 @@ async function callRunnerBridge(
}
describe('local_agents/runner', () => {
+ it.each([false, true])('wires OS-aware idle time into the CLI, retaining wall time if monitoring is unavailable: %s', async unavailable => {
+ suspensionClock.unavailable = unavailable;
+ mockDetect.mockResolvedValue({ type: 'claude', available: true, path: '/fake/claude', version: '2.0.0' });
+ let now = Date.now();
+ const date = vi.spyOn(Date, 'now').mockImplementation(() => now);
+ let backendCalls = 0;
+ mockBackendImpl = async opts => {
+ backendCalls++;
+ opts.onActivity();
+ now += 20 * 60_000;
+ expect(now - opts.lastEventAt()).toBe(1_200_000);
+ now += 60 * 60_000;
+ suspensionClock.suspended += 60 * 60_000;
+ expect(now - opts.lastEventAt()).toBe(unavailable ? 4_800_000 : 1_200_000);
+ opts.onActivity();
+ expect(now - opts.lastEventAt()).toBe(0);
+ opts.onEvent({ type: 'done', status: 'completed', output: 'done' });
+ };
+ try {
+ const result = await (await loadRunner()).run({
+ uid: TEST_UID, cid: 'c-suspend', agentId: 'a', cli: 'claude', prompt: 'work', cwd: tmpDir,
+ signal: new AbortController().signal, onEvent: () => {},
+ });
+ expect(result.status).toBe('completed');
+ expect(backendCalls).toBe(1);
+ } finally { date.mockRestore(); }
+ });
+
it('advertises only granted bridge categories and directs Commander-only work to handoff', async () => {
const runner = await loadRunner();
const restricted = runner.buildBridgeSystemPrompt([
diff --git a/test/main/features/local_agents/watchdog.test.ts b/test/main/features/local_agents/watchdog.test.ts
index fe7ce98c..ca87924d 100644
--- a/test/main/features/local_agents/watchdog.test.ts
+++ b/test/main/features/local_agents/watchdog.test.ts
@@ -1,5 +1,5 @@
import { afterEach, describe, it, expect, vi } from 'vitest';
-import { armKillWatchdog } from '../../../../src/main/features/local_agents/backends/base';
+import { armKillWatchdog, bindAbort } from '../../../../src/main/features/local_agents/backends/base';
import type { ChildProcessWithoutNullStreams } from 'node:child_process';
import {
AGENT_EXECUTION_IDLE_MS,
@@ -8,6 +8,7 @@ import {
} from '../../../../src/main/util/agent-execution-budget';
import { resolveIdleKillMs } from '../../../../src/main/features/local_agents/runner';
import { localCliCapabilities } from '../../../../src/main/features/local_agents/registry';
+import { SystemActivityTracker } from '../../../../src/main/features/system_activity';
// Business invariants of the activity-aware kill watchdog
// (backends/base.ts::armKillWatchdog). The bug class this guards: a
@@ -147,6 +148,113 @@ describe('armKillWatchdog', () => {
});
});
+// The OS event source is controlled; the real clock and watchdog decide
+// whether the child is killed. Wall-clock jumps without suspend are not sleep.
+function suspensionFixture() {
+ vi.useFakeTimers();
+ vi.setSystemTime(0);
+ const listeners = new Map<string, () => void>();
+ const system = new SystemActivityTracker({ on: (event, fn) => { listeners.set(event, fn); } });
+ system.start();
+ const awakeNow = () => {
+ const snapshot = system.snapshot();
+ return snapshot.wall_time_ms - snapshot.suspended_total_ms;
+ };
+ const clock = new AgentActivityClock(awakeNow);
+ const { child, kill } = fakeChild();
+ const wd = armKillWatchdog(child, {
+ timeoutMs: 86_400_000, idleKillMs: AGENT_EXECUTION_IDLE_MS, lastEventAt: clock.lastEventAt,
+ });
+ return { clock, wd, kill, child,
+ suspend: () => listeners.get('suspend')!(),
+ resume: () => listeners.get('resume')!(),
+ jump: (ms: number) => vi.setSystemTime(Date.now() + ms),
+ };
+}
+
+describe('CLI idle budget across system suspension', () => {
+ it('keeps user cancellation immediate while the system clock is suspended', () => {
+ const f = suspensionFixture();
+ const controller = new AbortController();
+ const unbind = bindAbort(f.child, controller.signal);
+ try {
+ f.suspend(); f.jump(3_600_000);
+ controller.abort();
+ expect(f.kill).toHaveBeenCalledWith('SIGTERM');
+ expect(f.kill).toHaveBeenCalledTimes(1);
+ expect(f.wd.fired()).toBeNull();
+ } finally { unbind(); f.wd.disarm(); }
+ });
+
+ it('preserves the remaining idle budget even if a watchdog tick precedes resume delivery', async () => {
+ const f = suspensionFixture();
+ await vi.advanceTimersByTimeAsync(20 * 60_000);
+ f.suspend(); f.jump(60 * 60_000);
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(f.kill).not.toHaveBeenCalled();
+ f.resume();
+ await vi.advanceTimersByTimeAsync(595_000);
+ expect(f.kill).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(f.wd.fired()).toBe('idle');
+ expect(f.wd.reason()).toContain('no activity for 1800000ms');
+ expect(f.kill).toHaveBeenCalledTimes(1);
+ f.wd.disarm();
+ });
+
+ it('counts multiple suspensions once and lets real progress renew the awake idle budget', async () => {
+ const f = suspensionFixture();
+ await vi.advanceTimersByTimeAsync(600_000);
+ f.suspend(); f.jump(3_600_000); f.resume();
+ await vi.advanceTimersByTimeAsync(600_000);
+ f.suspend(); f.suspend(); f.jump(3_600_000); f.resume(); f.resume();
+ f.clock.progress();
+ await vi.advanceTimersByTimeAsync(1_795_000);
+ expect(f.kill).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(f.wd.fired()).toBe('idle');
+ expect(f.kill).toHaveBeenCalledTimes(1);
+ f.wd.disarm();
+ });
+
+ it('does not deduct overlapping approval waits and system suspension twice', async () => {
+ const f = suspensionFixture();
+ await vi.advanceTimersByTimeAsync(1_200_000);
+ const first = f.clock.pause();
+ const second = f.clock.pause();
+ await vi.advanceTimersByTimeAsync(600_000);
+ f.suspend(); f.jump(3_600_000); f.resume();
+ first(); first();
+ await vi.advanceTimersByTimeAsync(600_000);
+ expect(f.kill).not.toHaveBeenCalled();
+ second();
+ await vi.advanceTimersByTimeAsync(595_000);
+ expect(f.kill).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(f.wd.fired()).toBe('idle');
+ f.wd.disarm();
+ });
+
+ it('retains the absolute 24-hour cap during suspension and a pending approval', async () => {
+ const f = suspensionFixture();
+ const doneWaiting = f.clock.pause();
+ f.suspend(); f.jump(86_400_000);
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(f.wd.fired()).toBe('wall');
+ expect(f.kill).toHaveBeenCalledTimes(1);
+ doneWaiting(); f.resume(); f.wd.disarm();
+ });
+
+ it('does not infer sleep from a silent CLI or an unaccompanied wall-clock jump', async () => {
+ const f = suspensionFixture();
+ f.jump(3_600_000);
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(f.wd.fired()).toBe('idle');
+ expect(f.kill).toHaveBeenCalledTimes(1);
+ f.wd.disarm();
+ });
+});
+
describe('who gets an idle clock', () => {
const previous = process.env.ORKAS_LOCAL_AGENT_IDLE_KILL_MS;
afterEach(() => {
diff --git a/test/main/features/system-activity.test.ts b/test/main/features/system-activity.test.ts
index 48a62090..c87e8a77 100644
--- a/test/main/features/system-activity.test.ts
+++ b/test/main/features/system-activity.test.ts
@@ -1,6 +1,37 @@
-import { describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+const power = vi.hoisted(() => ({ listeners: new Map<string, () => void>(), on: vi.fn() }));
+vi.mock('electron', () => ({ powerMonitor: { on: (event: string, fn: () => void) => {
+ power.on(event); power.listeners.set(event, fn);
+} } }));
+afterEach(() => { vi.useRealTimers(); });
describe('SystemActivityTracker', () => {
+ it('shares one registered OS clock across snapshot consumers and concurrent CLI runs, ignoring duplicate events', async () => {
+ vi.resetModules();
+ power.listeners.clear(); power.on.mockClear();
+ vi.useFakeTimers(); vi.setSystemTime(1000);
+ const { getSystemActivityClock, getSystemActivitySnapshot } = await import('../../../src/main/features/system_activity');
+ const [first, second] = await Promise.all([getSystemActivityClock(), getSystemActivityClock()]);
+ await getSystemActivitySnapshot();
+ expect(power.on.mock.calls).toEqual([['suspend'], ['resume']]);
+ expect(first()).toBe(1000);
+ vi.setSystemTime(1100);
+ power.listeners.get('suspend')!();
+ vi.setSystemTime(1500);
+ power.listeners.get('suspend')!();
+ expect(first()).toBe(1100);
+ expect(second()).toBe(1100);
+ vi.setSystemTime(1700);
+ power.listeners.get('resume')!(); power.listeners.get('resume')!();
+ vi.setSystemTime(1900);
+ expect(first()).toBe(1300);
+ expect(await getSystemActivitySnapshot()).toEqual({
+ wall_time_ms: 1900, suspended_total_ms: 600, suspend_count: 1,
+ });
+ expect(power.on).toHaveBeenCalledTimes(2);
+ });
+
it('exposes cumulative suspend time that can be differenced across a task', async () => {
const { SystemActivityTracker } = await import('../../../src/main/features/system_activity');
const listeners = new Map<string, () => void>();