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.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
Fix stalled bash tool cleanup
wyt151513557a8d
diff --git a/src/core-agent/src/agent/runner.ts b/src/core-agent/src/agent/runner.tsindex ef987009..12b7bb1c 100644--- a/src/core-agent/src/agent/runner.ts+++ b/src/core-agent/src/agent/runner.ts@@ -392,6 +392,7 @@ export class AgentRunner {skillsLoadedSet.add((call.input as any).id as string);}try {+ if (params.signal?.aborted) throw new Error("Run aborted");log.debug(`Executing tool: ${call.name}`);const progressQueue: Array<Extract<AgentRunEvent, { type: "tool_progress" }>> = [];let notifyProgress: (() => void) | null = null;@@ -426,17 +427,26 @@ export class AgentRunner {(result) => ({ ok: true as const, result }),(err) => ({ ok: false as const, err }),);+ const abortWait = waitForAbort(params.signal);let completed: ToolCompletion | null = null;- while (!completed) {- while (progressQueue.length) {- yield progressQueue.shift()!;+ try {+ while (!completed) {+ while (progressQueue.length) {+ yield progressQueue.shift()!;+ }+ const progressWait = new Promise<"progress">((resolve) => {+ notifyProgress = () => resolve("progress");+ });+ const waits: Array<Promise<ToolCompletion | "progress" | "abort">> = [toolPromise, progressWait];+ if (abortWait.promise) waits.push(abortWait.promise);+ const raced = await Promise.race(waits);+ if (raced === "progress") continue;+ if (raced === "abort") throw new Error("Run aborted");+ completed = raced;+ notifyProgress = null;}- const progressWait = new Promise<"progress">((resolve) => {- notifyProgress = () => resolve("progress");- });- const raced = await Promise.race([toolPromise, progressWait]);- if (raced === "progress") continue;- completed = raced;+ } finally {+ abortWait.cleanup();notifyProgress = null;}while (progressQueue.length) {@@ -457,6 +467,7 @@ export class AgentRunner {log.warn(`Tool ${call.name} returned error: ${toolResult.content.slice(0, 150)}`);}} catch (err) {+ if (params.signal?.aborted) throw err;const errMsg = formatError(err);const isTransient = isRetryableError(err);log.error(`Tool ${call.name} failed (${isTransient ? 'transient' : 'permanent'}): ${errMsg}`);@@ -774,6 +785,24 @@ function sleep(ms: number): Promise<void> {return new Promise((resolve) => setTimeout(resolve, ms));}+function waitForAbort(signal: AbortSignal | undefined): {+ promise: Promise<"abort"> | null;+ cleanup: () => void;+} {+ if (!signal) return { promise: null, cleanup: () => undefined };+ let cleanup = () => undefined;+ const promise = new Promise<"abort">((resolve) => {+ if (signal.aborted) {+ resolve("abort");+ return;+ }+ const onAbort = () => resolve("abort");+ signal.addEventListener("abort", onAbort, { once: true });+ cleanup = () => signal.removeEventListener("abort", onAbort);+ });+ return { promise, cleanup };+}+/*** Build the skills guidance block injected into the system prompt.* Tells the agent about skill_manage and metacognition tools.diff --git a/src/core-agent/src/sandbox/executor.ts b/src/core-agent/src/sandbox/executor.tsindex a43b1e49..a3647854 100644--- a/src/core-agent/src/sandbox/executor.ts+++ b/src/core-agent/src/sandbox/executor.ts@@ -369,6 +369,7 @@ export class SandboxExecutor {const child = spawn(invocation.command, invocation.args, {cwd,env,+ detached: process.platform !== "win32",stdio: ["pipe", "pipe", "pipe"],windowsHide: true,});@@ -415,15 +416,26 @@ export class SandboxExecutor {function killChild() {if (killed) return;killed = true;- child.kill("SIGTERM");+ killChildWithSignal("SIGTERM");// Escalate to SIGKILL after 5 seconds- setTimeout(() => {- try {- child.kill("SIGKILL");- } catch {- // Process may already be dead+ const killTimer = setTimeout(() => killChildWithSignal("SIGKILL"), 5000);+ if (typeof killTimer.unref === "function") killTimer.unref();+ }++ function killChildWithSignal(signal: NodeJS.Signals) {+ try {+ if (process.platform !== "win32" && child.pid) {+ process.kill(-child.pid, signal);+ return;}- }, 5000);+ } catch {+ // Fall back to killing the shell process below.+ }+ try {+ child.kill(signal);+ } catch {+ // Process may already be dead.+ }}child.on("close", (code) => {diff --git a/src/core-agent/src/tools/builtin.ts b/src/core-agent/src/tools/builtin.tsindex 9a39de18..4302975a 100644--- a/src/core-agent/src/tools/builtin.ts+++ b/src/core-agent/src/tools/builtin.ts@@ -1,6 +1,6 @@import fs from "node:fs/promises";import path from "node:path";-import { defineTool, type AgentTool } from "./base.js";+import { defineTool, type AgentTool, type ToolContext } from "./base.js";import { SandboxExecutor } from "../sandbox/executor.js";import { webFetchTool } from "./web-fetch.js";import { webSearchTool } from "./web-search.js";@@ -66,14 +66,17 @@ export const writeFileTool: AgentTool = defineTool({* Uses SandboxExecutor for timeout enforcement, output limits,* and blocked command filtering.*/+export const DEFAULT_BASH_TIMEOUT_MS = 30 * 60_000;+export const BASH_PROGRESS_INTERVAL_MS = 60_000;+export const bashTool: AgentTool = defineTool({name: "bash",- description: "Execute a shell command in a sandboxed environment and return its output. Use for system operations, builds, etc.",+ description: "Execute a shell command in a sandboxed environment and return its output. Use for system operations, builds, etc. For GUI apps, browsers, servers, watchers, or any command you would normally background with `&`, set run_in_background=true instead of shell-backgrounding it; inherited stdout/stderr can otherwise keep the tool waiting.",inputSchema: {type: "object",properties: {command: { type: "string", description: "The shell command to execute." },- timeoutMs: { type: "number", description: "Timeout in milliseconds (default: 300000 = 5 min). Pass a larger value (e.g. 600000 / 900000) for long-running commands like builds, large installs, network fetches, video processing." },+ timeoutMs: { type: "number", description: "Timeout in milliseconds (default: 1800000 = 30 min). Pass a larger value (e.g. 3600000) for long-running commands like builds, large installs, network fetches, video processing." },run_in_background: {type: "boolean",description: "Run detached and return immediately with a pid + log file path instead of waiting. Use for commands that may outlast any reasonable timeout (long builds, renders, big downloads). Poll progress by reading the log file; stop the process with `kill <pid>`. The process is NOT stopped automatically when the conversation ends.",@@ -83,7 +86,7 @@ export const bashTool: AgentTool = defineTool({},async execute(input, ctx) {const command = input.command as string;- const timeoutMs = (input.timeoutMs as number) ?? 300_000;+ const timeoutMs = (input.timeoutMs as number) ?? DEFAULT_BASH_TIMEOUT_MS;const sandbox = new SandboxExecutor({workingDir: ctx.workingDir ?? ".",@@ -108,7 +111,13 @@ export const bashTool: AgentTool = defineTool({};}- const result = await sandbox.execute(command);+ const stopHeartbeat = startBashHeartbeat(ctx, timeoutMs);+ let result;+ try {+ result = await sandbox.execute(command);+ } finally {+ stopHeartbeat();+ }if (result.timedOut) {return { content: `Command timed out after ${timeoutMs}ms`, isError: true };@@ -123,6 +132,28 @@ export const bashTool: AgentTool = defineTool({},});+function startBashHeartbeat(ctx: ToolContext, timeoutMs: number): () => void {+ if (!ctx.emitProgress) return () => undefined;+ const startedAt = Date.now();+ const timer = setInterval(() => {+ const elapsedMs = Date.now() - startedAt;+ ctx.emitProgress?.({+ phase: "running",+ message: `Command still running (${formatDuration(elapsedMs)} elapsed; timeout ${formatDuration(timeoutMs)})`,+ data: { elapsedMs, timeoutMs },+ });+ }, BASH_PROGRESS_INTERVAL_MS);+ if (typeof timer.unref === "function") timer.unref();+ return () => clearInterval(timer);+}++function formatDuration(ms: number): string {+ if (!Number.isFinite(ms) || ms < 0) return `${ms}ms`;+ if (ms >= 60_000) return `${Math.max(1, Math.round(ms / 60_000))}m`;+ if (ms >= 1_000) return `${Math.max(1, Math.round(ms / 1_000))}s`;+ return `${Math.round(ms)}ms`;+}+/** List files in a directory. */export const listFilesTool: AgentTool = defineTool({name: "list_files",diff --git a/src/core-agent/test/agent-runner.test.ts b/src/core-agent/test/agent-runner.test.tsindex be65d6c3..994315c2 100644--- a/src/core-agent/test/agent-runner.test.ts+++ b/src/core-agent/test/agent-runner.test.ts@@ -432,6 +432,58 @@ describe("AgentRunner", () => {expect(iEnd).toBeGreaterThan(iFirstProgress);});+ it("runStream stops waiting when a tool ignores abort", async () => {+ const mockProvider = createMockProvider([+ {+ content: [+ { type: "tool_use", id: "call_1", name: "wedged_tool", input: {} },+ ],+ stopReason: "tool_use",+ usage: { inputTokens: 5, outputTokens: 3, totalTokens: 8 },+ model: "mock-model",+ },+ ]);++ const registry = new ProviderRegistry();+ registry.registerFactory("mock", () => mockProvider);+ let toolStarted!: () => void;+ const toolStartedPromise = new Promise<void>((resolve) => { toolStarted = resolve; });+ const wedgedTool = defineTool({+ name: "wedged_tool",+ description: "Never resolves",+ inputSchema: { type: "object", properties: {} },+ async execute() {+ toolStarted();+ return new Promise(() => undefined);+ },+ });+ const config = createConfig({+ agent: { defaultProvider: "mock", defaultModel: "mock-model" },+ });++ const runner = new AgentRunner({ config, providers: registry, tools: [wedgedTool] });+ const controller = new AbortController();+ const collected: Array<{ type: string; [k: string]: unknown }> = [];+ const run = (async () => {+ for await (const ev of runner.runStream({ message: "go", signal: controller.signal })) {+ collected.push(ev as { type: string; [k: string]: unknown });+ }+ })();++ await toolStartedPromise;+ controller.abort();+ const settled = await Promise.race([+ run.then(() => true),+ new Promise<boolean>((resolve) => setTimeout(() => resolve(false), 1000)),+ ]);++ expect(settled).toBe(true);+ const done = collected[collected.length - 1] as { type: string; result?: { meta?: { aborted?: boolean } } };+ expect(done.type).toBe("done");+ expect(done.result?.meta?.aborted).toBe(true);+ expect(collected.some((e) => e.type === "tool_end")).toBe(false);+ });+it("runStream forwards tool input deltas before tool execution", async () => {const mockProvider = createMockProvider([{diff --git a/src/core-agent/test/sandbox.test.ts b/src/core-agent/test/sandbox.test.tsindex b105a68a..c582c4c1 100644--- a/src/core-agent/test/sandbox.test.ts+++ b/src/core-agent/test/sandbox.test.ts@@ -40,6 +40,24 @@ describe("SandboxExecutor", () => {expect(result.timedOut).toBe(true);}, 10000);+ it("times out commands whose background child keeps stdout open", async () => {+ if (process.platform === "win32") return;+ const quote = (s: string) => `"${s.replace(/(["\\$`])/g, "\\$1")}"`;+ const script = [+ "const { spawn } = require('node:child_process');",+ "spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'inherit' });",+ "console.log('parent done');",+ ].join("");+ const sandbox = new SandboxExecutor({+ workingDir: os.tmpdir(),+ timeoutMs: 500,+ });+ const started = Date.now();+ const result = await sandbox.execute(`${quote(process.execPath)} -e ${quote(script)}`);+ expect(result.timedOut).toBe(true);+ expect(Date.now() - started).toBeLessThan(5000);+ }, 10000);+it("blocks dangerous commands", async () => {const sandbox = new SandboxExecutor({ workingDir: os.tmpdir() });const result = await sandbox.execute("rm -rf /");diff --git a/src/main/model/core-agent/local-tools.ts b/src/main/model/core-agent/local-tools.tsindex 3b467827..02f436d3 100644--- a/src/main/model/core-agent/local-tools.ts+++ b/src/main/model/core-agent/local-tools.ts@@ -46,7 +46,12 @@ import * as path from 'node:path';import { spawn } from 'node:child_process';import type { AgentTool, ToolContext, ToolResult } from '#core-agent';-import { bashTool as coreBashTool, writeFileTool as coreWriteFileTool } from '../../../core-agent/src/tools/builtin';+import {+ BASH_PROGRESS_INTERVAL_MS,+ DEFAULT_BASH_TIMEOUT_MS,+ bashTool as coreBashTool,+ writeFileTool as coreWriteFileTool,+} from '../../../core-agent/src/tools/builtin';import { buildSandboxEnv, decodeProcessOutput } from '../../../core-agent/src/sandbox/executor';import { getLocalExecGranted, getLocalExecMode } from '../../features/permissions';import { classifyBashCommand } from './bash-risk';@@ -434,7 +439,7 @@ async function executeDirectOrkasCli(ctx: ToolContext,workingDir: string,): Promise<ToolResult> {- const timeoutMs = (input.timeoutMs as number | undefined) ?? 300_000;+ const timeoutMs = (input.timeoutMs as number | undefined) ?? DEFAULT_BASH_TIMEOUT_MS;const sandboxEnv = (ctx.state.sandboxEnv ?? {}) as Record<string, string>;const env = buildSandboxEnv(sandboxEnv);@@ -446,6 +451,8 @@ async function executeDirectOrkasCli(let outputLimitExceeded = false;let truncatedKind: 'stdout' | 'stderr' | null = null;let settled = false;+ const startedAt = Date.now();+ let heartbeat: NodeJS.Timeout | null = null;const child = spawn(invocation.nodePath, [invocation.scriptPath, ...invocation.args], {cwd: workingDir,@@ -458,6 +465,7 @@ async function executeDirectOrkasCli(if (settled) return;settled = true;clearTimeout(timeout);+ if (heartbeat) clearInterval(heartbeat);resolve(result);};@@ -493,6 +501,18 @@ async function executeDirectOrkasCli(}, timeoutMs);if (typeof timeout.unref === 'function') timeout.unref();+ if (ctx.emitProgress) {+ heartbeat = setInterval(() => {+ const elapsedMs = Date.now() - startedAt;+ ctx.emitProgress?.({+ phase: 'running',+ message: `Command still running (${formatBashDuration(elapsedMs)} elapsed; timeout ${formatBashDuration(timeoutMs)})`,+ data: { elapsedMs, timeoutMs },+ });+ }, BASH_PROGRESS_INTERVAL_MS);+ if (typeof heartbeat.unref === 'function') heartbeat.unref();+ }+child.on('error', (err) => {finish({ content: bashMsg('start_failed', { command: invocation.script, error: err.message }), isError: true });});@@ -522,6 +542,13 @@ async function executeDirectOrkasCli(});}+function formatBashDuration(ms: number): string {+ if (!Number.isFinite(ms) || ms < 0) return `${ms}ms`;+ if (ms >= 60_000) return `${Math.max(1, Math.round(ms / 60_000))}m`;+ if (ms >= 1_000) return `${Math.max(1, Math.round(ms / 1_000))}s`;+ return `${Math.round(ms)}ms`;+}+async function executeCoreBashWithOutputTracking(opts: LocalToolsOpts,input: Record<string, unknown>,@@ -673,7 +700,10 @@ function createBashTool(opts: LocalToolsOpts): AgentTool {'should be shown to the user as produced-file chips (for example .docx, .xlsx, ' +'.pptx, .pdf, images, HTML, CSV, Markdown), write them under the absolute ' +'$ORKAS_OUTPUT_DIR path, which is the current conversation workspace. ' +- 'Scratch/cache files should stay in temporary or cache directories.',+ 'Scratch/cache files should stay in temporary or cache directories. ' ++ 'For GUI apps, browsers, servers, watchers, or any command you would normally ' ++ 'background with `&`, set run_in_background=true instead of shell-backgrounding it; ' ++ 'inherited stdout/stderr can otherwise keep the tool waiting.',inputSchema: coreBashTool.inputSchema,async execute(input, ctx) {const mode = getLocalExecMode();diff --git a/src/renderer/modules/conversation.js b/src/renderer/modules/conversation.jsindex 47c90122..0434e7b3 100644--- a/src/renderer/modules/conversation.js+++ b/src/renderer/modules/conversation.js@@ -4934,6 +4934,10 @@ async function handleChatSubmit() {// own AbortController. Entries are dropped on done via the hooks below.const _convChatCtrls = new Map(); // cid → controller+function _observerShouldDeferCleanup(cid, allowWithController) {+ return !!allowWithController && _convChatCtrls.has(cid);+}+function _makeConvChatController(cid) {// Captured into the hooks below so we can compare identity before deleting// — see onDone for why.@@ -5263,7 +5267,7 @@ function _observeConversationRunFromPlanAction(cid, opts = {}) {_convChatCtrls.delete(cid);}if (activated) {- if (allowWithController) {+ if (_observerShouldDeferCleanup(cid, allowWithController)) {if (window.PlanRail) window.PlanRail.refresh(cid, { force: true });if (window.ConversationInfo) window.ConversationInfo.refreshTasks(cid, { silent: true });return;diff --git a/test/renderer/conversation-sidebar.test.ts b/test/renderer/conversation-sidebar.test.tsindex 946101aa..e66682ea 100644--- a/test/renderer/conversation-sidebar.test.ts+++ b/test/renderer/conversation-sidebar.test.ts@@ -114,6 +114,20 @@ describe('conversation create-agent inline gate', () => {});});+describe('conversation run observer cleanup', () => {+ it('defers cleanup only while the primary send stream still owns the turn', () => {+ const context = loadConversationRenderer();++ expect(context._observerShouldDeferCleanup('c1', true)).toBe(false);+ expect(context._observerShouldDeferCleanup('c1', false)).toBe(false);++ vm.runInContext('_convChatCtrls.set("c1", { abort() {} })', context);++ expect(context._observerShouldDeferCleanup('c1', true)).toBe(true);+ expect(context._observerShouldDeferCleanup('c1', false)).toBe(false);+ });+});+describe('conversation sidebar task row actions', () => {it('renders a single menu button after the title', () => {const context = loadConversationRenderer();