Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(tools): run Bash commands as background tasks that outlive the turn

alger7507217bcb76
diff --git a/apps/desktop/electron/main/ipc/background-tasks-ipc.ts b/apps/desktop/electron/main/ipc/background-tasks-ipc.ts
new file mode 100644
index 000000000..ea48ac064
--- /dev/null
+++ b/apps/desktop/electron/main/ipc/background-tasks-ipc.ts
@@ -0,0 +1,48 @@
+import { IPC } from "@pi-desktop/shared";
+import type { HostProcess } from "../host-process";
+import type { IpcRegistrar } from "./types";
+
+export type BackgroundTasksIpcDependencies = {
+ registrar: IpcRegistrar;
+ getHost: () => HostProcess | null;
+};
+
+/** The renderer sends `{ id }`; accept a bare string too for direct callers. */
+function backgroundTaskId(payload: unknown): { id: string } {
+ const candidate =
+ typeof payload === "string"
+ ? payload
+ : (payload as { id?: unknown } | undefined)?.id;
+ if (typeof candidate !== "string" || candidate.length === 0) {
+ throw new Error("background task id required");
+ }
+ return { id: candidate };
+}
+
+/**
+ * Chat-started background tasks (dev servers, watchers) live in host-core.
+ * Main only relays the three calls; the lifecycle — including app-exit
+ * cleanup — is host-owned so a renderer reload never kills a running server.
+ */
+export function registerBackgroundTasksIpc({
+ registrar,
+ getHost,
+}: BackgroundTasksIpcDependencies): void {
+ const callHost = (method: string, params?: unknown) => {
+ const host = getHost();
+ if (!host) throw new Error("host unavailable");
+ // A background call returns as soon as the process is spawned, so the
+ // default host-call timeout applies to relay latency only.
+ return params === undefined ? host.call(method) : host.call(method, params);
+ };
+
+ registrar.handle(IPC.invoke.backgroundTasksList, () =>
+ callHost("backgroundTasks.list"),
+ );
+ registrar.handle(IPC.invoke.backgroundTasksOutput, (payload: unknown) =>
+ callHost("backgroundTasks.output", backgroundTaskId(payload)),
+ );
+ registrar.handle(IPC.invoke.backgroundTasksStop, (payload: unknown) =>
+ callHost("backgroundTasks.stop", backgroundTaskId(payload)),
+ );
+}
diff --git a/apps/desktop/electron/main/ipc/register.ts b/apps/desktop/electron/main/ipc/register.ts
index eff042db9..99c7d09e2 100644
--- a/apps/desktop/electron/main/ipc/register.ts
+++ b/apps/desktop/electron/main/ipc/register.ts
@@ -24,6 +24,7 @@ import { registerSessionIpc } from "./session-ipc";
import { registerSettingsIpc } from "./settings-ipc";
import { registerStorageIpc } from "../storage/ipc";
import { registerConfigSyncIpc } from "./config-sync-ipc";
+import { registerBackgroundTasksIpc } from "./background-tasks-ipc";
import { registerSkillsIpc } from "./skills-ipc";
import { registerAgentImportIpc } from "./agent-import-ipc";
import { registerRemoteHostIpc } from "./remote-host-ipc";
@@ -290,6 +291,10 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {
getHost,
sendToRenderer,
});
+ registerBackgroundTasksIpc({
+ registrar,
+ getHost,
+ });
registerProviderIpc({
registrar,
getHost,
diff --git a/apps/desktop/electron/main/runtime/host.ts b/apps/desktop/electron/main/runtime/host.ts
index f726ae5d9..7ca3aa149 100644
--- a/apps/desktop/electron/main/runtime/host.ts
+++ b/apps/desktop/electron/main/runtime/host.ts
@@ -101,6 +101,12 @@ export function createHostRuntime({
sendToRenderer(IPC.event.pluginInstallProgress, params);
return;
}
+ if (method === "backgroundTasks.changed") {
+ // Fan-out only: the renderer re-lists on the event and renders the
+ // running-tasks bar above the composer. No main-process decisions.
+ sendToRenderer(IPC.event.backgroundTasksChanged, params);
+ return;
+ }
if (method === "permissions.request") {
const permission = params as {
requestId: string;
diff --git a/apps/desktop/src/components/BackgroundTasksBar.tsx b/apps/desktop/src/components/BackgroundTasksBar.tsx
new file mode 100644
index 000000000..15d0bca29
--- /dev/null
+++ b/apps/desktop/src/components/BackgroundTasksBar.tsx
@@ -0,0 +1,161 @@
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import {
+ api,
+ type BackgroundTaskOutput,
+ type BackgroundTaskSummary,
+} from "../lib/api";
+import { Button } from "./ui";
+
+/** Characters shown when a finished task produced no output at all. */
+const NO_OUTPUT = "—";
+
+/**
+ * Shows chat-started background commands (dev servers, watchers) above the
+ * composer. The lifecycle lives in host-core — a task survives turn aborts
+ * and renderer reloads; this bar only reflects registry state and can stop a
+ * task on request. Every task is listed; running ones float to the top.
+ */
+export function BackgroundTasksBar(): React.JSX.Element | null {
+ const { t } = useTranslation();
+ const [tasks, setTasks] = useState<BackgroundTaskSummary[]>([]);
+ const [expandedId, setExpandedId] = useState<string | null>(null);
+ const [output, setOutput] = useState<BackgroundTaskOutput | null>(null);
+ const [stoppingIds, setStoppingIds] = useState<Set<string>>(() => new Set());
+
+ const refresh = useCallback(async () => {
+ try {
+ const result = await api.backgroundTasksList();
+ setTasks(result.tasks);
+ } catch {
+ // Host may be mid-restart; keep the last snapshot and retry on the
+ // next change event rather than flashing an error bar.
+ }
+ }, []);
+
+ useEffect(() => {
+ void refresh();
+ return api.onBackgroundTasksChanged(() => {
+ void refresh();
+ });
+ }, [refresh]);
+
+ const toggleOutput = useCallback(async (id: string) => {
+ setExpandedId((current) => (current === id ? null : id));
+ try {
+ setOutput(await api.backgroundTasksOutput(id));
+ } catch {
+ setOutput(null);
+ }
+ }, []);
+
+ const stop = useCallback(async (id: string) => {
+ setStoppingIds((current) => new Set(current).add(id));
+ try {
+ await api.backgroundTasksStop(id);
+ } finally {
+ setStoppingIds((current) => {
+ const next = new Set(current);
+ next.delete(id);
+ return next;
+ });
+ }
+ }, []);
+
+ const hasRunning = useMemo(
+ () => tasks.some((task) => task.state === "running"),
+ [tasks],
+ );
+
+ // Elapsed time comes from the host snapshot, so a running task needs a
+ // periodic re-list; without it the bar freezes at the last state change.
+ useEffect(() => {
+ if (!hasRunning) return;
+ const timer = setInterval(() => void refresh(), 1000);
+ return () => clearInterval(timer);
+ }, [hasRunning, refresh]);
+
+ if (tasks.length === 0) return null;
+
+ return (
+ <div
+ className="background-tasks-bar"
+ role="region"
+ aria-label={t("backgroundTasks.title")}
+ >
+ {tasks.map((task) => {
+ const isRunning = task.state === "running";
+ const stopping = stoppingIds.has(task.id);
+ return (
+ <div
+ key={task.id}
+ className="background-task"
+ data-state={task.state}
+ >
+ <span
+ className="background-task-state"
+ data-state={task.state}
+ title={t(`backgroundTasks.${task.state}`)}
+ />
+ <span className="background-task-command" title={task.command}>
+ {task.command}
+ </span>
+ <span className="background-task-meta">
+ {t(`backgroundTasks.${task.state}`)}
+ {isRunning ? ` · ${formatElapsed(task.elapsedMs)}` : ""}
+ {task.exitCode !== undefined ? ` · ${task.exitCode}` : ""}
+ </span>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="background-task-action"
+ onClick={() => void toggleOutput(task.id)}
+ aria-expanded={expandedId === task.id}
+ >
+ {t("backgroundTasks.output")}
+ </Button>
+ {isRunning ? (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="background-task-action is-stop"
+ onClick={() => void stop(task.id)}
+ disabled={stopping}
+ >
+ {stopping ? t("backgroundTasks.stopping") : t("backgroundTasks.stop")}
+ </Button>
+ ) : null}
+ {expandedId === task.id ? (
+ <pre className="background-task-output">
+ {formatOutput(output, task.id) || NO_OUTPUT}
+ </pre>
+ ) : null}
+ </div>
+ );
+ })}
+ </div>
+ );
+}
+
+function formatElapsed(ms: number): string {
+ const seconds = Math.floor(ms / 1000);
+ if (seconds < 60) return `${seconds}s`;
+ const minutes = Math.floor(seconds / 60);
+ if (minutes < 60) return `${minutes}m${seconds % 60}s`;
+ return `${Math.floor(minutes / 60)}h${minutes % 60}m`;
+}
+
+function formatOutput(
+ output: BackgroundTaskOutput | null,
+ id: string,
+): string {
+ if (!output || output.id !== id) return "";
+ const tail = (text: string, limit: number) =>
+ text.length > limit ? `…${text.slice(-limit)}` : text;
+ return [tail(output.stdout, 8000), tail(output.stderr, 4000)]
+ .filter((part) => part.length > 0)
+ .join("\n---\n")
+ .trim();
+}
diff --git a/apps/desktop/src/components/Composer.tsx b/apps/desktop/src/components/Composer.tsx
index cba5fbbdb..bebc1d609 100644
--- a/apps/desktop/src/components/Composer.tsx
+++ b/apps/desktop/src/components/Composer.tsx
@@ -32,6 +32,7 @@ import { ComposerAutocomplete } from "./ComposerAutocomplete";
import { AskToolCard } from "./AskToolCard";
import { PlanApprovalBar } from "./PlanApprovalBar";
import { TodoDock } from "./TodoDock";
+import { BackgroundTasksBar } from "./BackgroundTasksBar";
import {
COMPOSER_MAX_VISIBLE_ROWS,
COMPOSER_MIN_HEIGHT_PX,
@@ -525,6 +526,7 @@ export function Composer({
>
<div className="composer-stack">
{activeSessionId && localToolsAllowed ? <TodoDock sessionId={activeSessionId} /> : null}
+ <BackgroundTasksBar />
{planCheckpoint?.status === "pending" ? (
<PlanApprovalBar proposal={planCheckpoint} />
) : null}
diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts
index 476b42ecc..4a976e150 100644
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@ -351,6 +351,31 @@ async function invoke<T>(channel: string, ...args: unknown[]): Promise<T> {
return result.data;
}
+/** One chat-started background command reported by host-core. */
+export type BackgroundTaskSummary = {
+ id: string;
+ sessionId: string;
+ command: string;
+ commandShellId: string;
+ state: "running" | "exited" | "failed" | "stopped";
+ elapsedMs: number;
+ exitCode?: number;
+};
+
+export type BackgroundTasksListResult = {
+ tasks: BackgroundTaskSummary[];
+ version: number;
+};
+
+export type BackgroundTaskOutput = {
+ id: string;
+ state: "running" | "exited" | "failed" | "stopped";
+ exitCode?: number;
+ stdout: string;
+ stderr: string;
+ truncated: boolean;
+};
+
/** `session.create` input: summary fields plus the isolation switch. */
export type CreateSessionInput = Partial<SessionSummary> & {
/** Run the session in its own git worktree (ADR 0329). */
@@ -731,6 +756,18 @@ export const api = {
*/
testJevApiKey: (value: string) =>
invoke<JevKeyCheckResult>(IPC.invoke.jevTest, value),
+ backgroundTasksList: () =>
+ invoke<BackgroundTasksListResult>(IPC.invoke.backgroundTasksList),
+ backgroundTasksOutput: (id: string) =>
+ invoke<BackgroundTaskOutput>(IPC.invoke.backgroundTasksOutput, { id }),
+ backgroundTasksStop: (id: string) =>
+ invoke<{ ok: boolean; found: boolean }>(IPC.invoke.backgroundTasksStop, { id }),
+ onBackgroundTasksChanged: (listener: (payload: { version?: number }) => void) => {
+ if (!window.piDesktop?.on) return () => undefined;
+ return window.piDesktop.on(IPC.event.backgroundTasksChanged, (payload) =>
+ listener((payload ?? {}) as { version?: number }),
+ );
+ },
configSyncGetState: () => invoke<ConfigSyncState>(IPC.invoke.configSyncGetState),
configSyncConfigure: (input: ConfigSyncConfigureInput) =>
invoke<ConfigSyncState>(IPC.invoke.configSyncConfigure, input),
diff --git a/apps/desktop/src/styles/composer.css b/apps/desktop/src/styles/composer.css
index e08689b03..0b46e5291 100644
--- a/apps/desktop/src/styles/composer.css
+++ b/apps/desktop/src/styles/composer.css
@@ -880,3 +880,113 @@
transition: none;
}
}
+
+/* Background tasks bar — chat-started commands detached from their turn. The
+ host owns the lifecycle; this surface only reports state and offers output /
+ stop. One bordered list of hairline-separated rows reads as a terminal
+ status block instead of a stack of input-like fields. */
+.background-tasks-bar {
+ display: flex;
+ flex-direction: column;
+ margin: 0 0 8px;
+ overflow: hidden;
+ border: 1px solid var(--ds-border-subtle);
+ border-radius: var(--radius-md);
+ background: var(--ds-bg-dock-raised);
+}
+
+.background-task {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 8px;
+ min-width: 0;
+ padding: 6px 10px;
+ color: var(--ds-text-secondary);
+ font-size: var(--text-sm);
+}
+
+.background-task + .background-task {
+ border-top: 1px solid var(--ds-border-subtle);
+}
+
+.background-task:hover {
+ background: var(--ds-bg-hover);
+}
+
+/* The dot carries the state so the command stays the only high-contrast text
+ in the row; a running task breathes rather than spinning. */
+.background-task-state {
+ flex: 0 0 auto;
+ width: 7px;
+ height: 7px;
+ border-radius: var(--radius-round);
+ background: var(--ds-text-faint);
+}
+
+.background-task[data-state="running"] .background-task-state {
+ background: var(--ds-success);
+ animation: background-task-pulse 1.8s var(--motion-ease-standard) infinite;
+}
+
+.background-task[data-state="failed"] .background-task-state {
+ background: var(--ds-warning);
+}
+
+@keyframes background-task-pulse {
+ 0%,
+ 100% {
+ opacity: 1;
+ }
+ 50% {
+ opacity: 0.35;
+ }
+}
+
+.background-task-command {
+ min-width: 0;
+ flex: 1;
+ overflow: hidden;
+ color: var(--ds-text-primary);
+ font-family: var(--font-mono);
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.background-task-meta {
+ flex: 0 0 auto;
+ color: var(--ds-text-muted);
+ font-size: var(--text-xs);
+ /* Seconds tick in place instead of reflowing the row every second. */
+ font-variant-numeric: tabular-nums;
+ white-space: nowrap;
+}
+
+.background-tasks-bar .background-task-action {
+ flex: 0 0 auto;
+ color: var(--ds-text-muted);
+}
+
+.background-tasks-bar .background-task-action:hover:not(:disabled) {
+ color: var(--ds-text-primary);
+}
+
+.background-tasks-bar .background-task-action.is-stop:hover:not(:disabled) {
+ color: var(--ds-warning);
+}
+
+.background-task-output {
+ flex-basis: 100%;
+ max-height: 180px;
+ margin: 0;
+ padding: 8px 10px;
+ overflow: auto;
+ border-top: 1px solid var(--ds-border-subtle);
+ background: var(--ds-bg-inset);
+ color: var(--ds-text-secondary);
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ line-height: var(--leading-body);
+ white-space: pre-wrap;
+ word-break: break-word;
+}
diff --git a/apps/desktop/test/background-tasks.test.mjs b/apps/desktop/test/background-tasks.test.mjs
new file mode 100644
index 000000000..c3bc54cc7
--- /dev/null
+++ b/apps/desktop/test/background-tasks.test.mjs
@@ -0,0 +1,129 @@
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import test from "node:test";
+
+/*
+ * Background tasks: the Bash tool gains runInBackground, the registry lives in
+ * host-core, and the renderer surfaces the running tasks above the composer.
+ * These are contract tests over the sources: each layer must name the same
+ * wire fields, and the bar must only reflect registry state (never own the
+ * process lifecycle).
+ */
+
+const runtime = await readFile(
+ new URL("../../../packages/agent-runtime/src/runtime.ts", import.meta.url),
+ "utf8",
+);
+const toolSources = await readFile(
+ new URL("../../../crates/host-core/src/tools/mod.rs", import.meta.url),
+ "utf8",
+);
+const rpcSources = await readFile(
+ new URL("../../../crates/host-core/src/rpc/mod.rs", import.meta.url),
+ "utf8",
+);
+const backgroundTasks = await readFile(
+ new URL("../../../crates/host-core/src/background_tasks.rs", import.meta.url),
+ "utf8",
+);
+const bar = await readFile(
+ new URL("../src/components/BackgroundTasksBar.tsx", import.meta.url),
+ "utf8",
+);
+const api = await readFile(new URL("../src/lib/api.ts", import.meta.url), "utf8");
+const composer = await readFile(
+ new URL("../src/components/Composer.tsx", import.meta.url),
+ "utf8",
+);
+const styles = await readFile(
+ new URL("../src/styles/composer.css", import.meta.url),
+ "utf8",
+);
+const i18nEn = await readFile(
+ new URL("../../../packages/i18n/src/locales/en/index.ts", import.meta.url),
+ "utf8",
+);
+
+test("the Bash schema advertises runInBackground and the tool description explains when to use it", () => {
+ assert.match(runtime, /runInBackground: Type\.Optional\(\s*Type\.Boolean/);
+ assert.match(runtime, /runInBackground: true for long-lived processes/);
+});
+
+test("the runtime forwards runInBackground on a Bash tools.execute call", () => {
+ assert.match(
+ runtime,
+ /params\.runInBackground === true\s*\?\s*\{\s*runInBackground: true\s*\}/,
+ );
+});
+
+test("host-core parses runInBackground on ToolsExecuteParams and skips the cancellation registry for it", () => {
+ assert.match(
+ toolSources,
+ /pub run_in_background: bool,\s*\n\s*pub timeout_ms/,
+ );
+ assert.match(
+ toolSources,
+ /if options\.run_in_background \{[\s\S]*?spawn_background_task_detached/,
+ );
+});
+
+test("a background Bash call returns a backgroundTaskId and never a blocking stdout payload", () => {
+ assert.match(toolSources, /"backgroundTaskId": started/);
+});
+
+test("turn cancellation and timeout cannot reach a background task: it never registers a bash cancellation", () => {
+ assert.match(
+ rpcSources.replace(/\r/g, ""),
+ /cancellation_receiver = if remote_workspace\.is_some\(\)[\s\S]*?&& !p\.run_in_background\)/,
+ );
+ assert.match(rpcSources.replace(/\r/g, ""), /"Bash" \| "GenerateImages"/);
+});
+
+test("the registry keeps output bounded and stops everything on shutdown", () => {
+ assert.match(backgroundTasks, /RING_MAX_BYTES: usize = 256 \* 1024/);
+ assert.match(backgroundTasks, /stop_all_running_sync/);
+ assert.match(backgroundTasks, /MAX_RUNNING_TASKS: usize = 32/);
+});
+
+test("the renderer bar lists tasks, offers output and stop, and mounts above the composer input", () => {
+ assert.match(bar, /api\.backgroundTasksList\(\)/);
+ assert.match(bar, /api\.backgroundTasksStop\(id\)/);
+ assert.match(bar, /aria-label=\{t\("backgroundTasks\.title"\)\}/);
+ assert.match(composer, /import \{ BackgroundTasksBar \} from "\.\/BackgroundTasksBar";/);
+ assert.match(composer, /<BackgroundTasksBar \/>/);
+ // The bar renders before the composer shell (above the input, not inside it).
+ const barIndex = composer.indexOf("<BackgroundTasksBar />");
+ const shellIndex = composer.indexOf('className={`composer-shell');
+ assert.ok(barIndex > 0 && shellIndex > barIndex, "bar must precede the composer shell");
+});
+
+test("the api layer names the wire channels for list, output, stop, and the change event", () => {
+ assert.match(api, /IPC\.invoke\.backgroundTasksList/);
+ assert.match(api, /IPC\.invoke\.backgroundTasksOutput/);
+ assert.match(api, /IPC\.invoke\.backgroundTasksStop/);
+ assert.match(api, /IPC\.event\.backgroundTasksChanged/);
+});
+
+test("the host notification fan-out exists in the electron main host wiring", async () => {
+ const host = await readFile(
+ new URL("../electron/main/runtime/host.ts", import.meta.url),
+ "utf8",
+ );
+ assert.match(host, /method === "backgroundTasks\.changed"/);
+ assert.match(host, /sendToRenderer\(IPC\.event\.backgroundTasksChanged/);
+});
+
+test("the bar styles exist and mark a running task with a pulse", () => {
+ assert.match(styles, /\.background-tasks-bar \{/);
+ assert.match(
+ styles,
+ /\.background-task\[data-state="running"\] \.background-task-state \{[^}]*animation:/,
+ );
+ // Legibility: the command is the high-contrast element and every size comes
+ // from the token scale instead of a raw literal.
+ assert.match(styles, /\.background-task-command \{[^}]*color: var\(--ds-text-primary\)/);
+});
+
+test("the running/stopped/failed/exited labels are translated", () => {
+ assert.match(i18nEn, /backgroundTasks: \{[^}]*running: "Running"/);
+});
diff --git a/crates/host-core/src/background_tasks.rs b/crates/host-core/src/background_tasks.rs
new file mode 100644
index 000000000..4e98acd50
--- /dev/null
+++ b/crates/host-core/src/background_tasks.rs
@@ -0,0 +1,555 @@
+//! Background command tasks: long-lived processes started from a chat turn
+//! (dev servers, watchers, builds) that must outlive the turn.
+//!
+//! A foreground `Bash` tool call belongs to its turn: the timeout kills it and
+//! the abort path tears down the whole process group. Tasks registered here
+//! are detached from that lifecycle — the registry owns the process, output is
+//! kept in bounded ring buffers so reads never grow unbounded, and every
+//! state change (start, exit, stop) bumps a counter that the RPC layer turns
+//! into a `backgroundTasks.changed` notification for the renderer.
+//!
+//! Lifecycle: tasks live with the host process. `AppState::shutdown` stops
+//! every running task, so an application exit never leaves orphans behind.
+
+use std::collections::{HashMap, VecDeque};
+use std::sync::Arc;
+use std::time::Instant;
+
+use crate::tools;
+use serde::Serialize;
+use tokio::io::AsyncReadExt;
+use tokio::sync::{watch, Mutex};
+
+/// Keep the last 256KB per stream. A server that logs fast for hours must not
+/// grow host memory; a caller that needs earlier output re-runs the command.
+const RING_MAX_BYTES: usize = 256 * 1024;
+/// Upper bound on concurrently running background tasks. Each holds a process
+/// tree and two pipe readers; a runaway loop spawning servers must fail fast.
+pub(crate) const MAX_RUNNING_TASKS: usize = 32;
+/// Bounded set of finished tasks kept so the UI can show what just exited.
+const FINISHED_TASK_HISTORY: usize = 16;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub enum BackgroundTaskState {
+ Running,
+ Exited,
+ Failed,
+ Stopped,
+}
+
+/// Shared between the registry entry and the detached supervisor task. The
+/// supervisor writes output and the terminal state; RPC handlers read.
+#[derive(Debug)]
+pub(crate) struct TaskShared {
+ state: BackgroundTaskState,
+ exit_code: Option<i32>,
+ stdout: VecDeque<String>,
+ stderr: VecDeque<String>,
+ stdout_bytes: usize,
+ stderr_bytes: usize,
+ truncated: bool,
+ pub(crate) stop: watch::Sender<bool>,
+}
+
+impl TaskShared {
+ fn push_text(ring: &mut VecDeque<String>, total: &mut usize, text: &str) -> bool {
+ ring.push_back(text.to_string());
+ *total += text.len();
+ let mut dropped = false;
+ while *total > RING_MAX_BYTES && ring.len() > 1 {
+ if let Some(front) = ring.pop_front() {
+ *total -= front.len();
+ dropped = true;
+ }
+ }
+ dropped
+ }
+
+ fn push_stdout(&mut self, text: &str) -> bool {
+ Self::push_text(&mut self.stdout, &mut self.stdout_bytes, text)
+ }
+
+ fn push_stderr(&mut self, text: &str) -> bool {
+ Self::push_text(&mut self.stderr, &mut self.stderr_bytes, text)
+ }
+
+ fn render(ring: &VecDeque<String>) -> String {
+ ring.iter().map(String::as_str).collect()
+ }
+}
+
+/// Immutable identity plus the shared cell. `started_at` is fixed at spawn.
+#[derive(Debug, Clone)]
+pub struct BackgroundTask {
+ pub id: String,
+ pub session_id: String,
+ pub command: String,
+ pub command_shell_id: String,
+ pub started_at: Instant,
+ pub shared: Arc<Mutex<TaskShared>>,
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct BackgroundTaskSummary {
+ pub id: String,
+ pub session_id: String,
+ pub command: String,
+ pub command_shell_id: String,
+ pub state: BackgroundTaskState,
+ /// Milliseconds since the task started, not a wall-clock timestamp.
+ pub elapsed_ms: u64,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub exit_code: Option<i32>,
+}
+
+#[derive(Default, Debug)]
+pub struct BackgroundTaskRegistry {
+ pub(crate) tasks: HashMap<String, BackgroundTask>,
+ /// Insertion order, for stable oldest-first pruning of finished entries.
+ order: Vec<String>,
+}
+
+/// Process-wide change counter. Every start, exit, and stop bumps it; the RPC
+/// layer reads it to decide whether a `backgroundTasks.changed` notification is
+/// due. A static keeps the detached supervisors independent of the AppState
+/// mutex — they can never deadlock against a tool call that holds it.
+static CHANGE_COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+
+pub fn bump_change_counter() {
+ CHANGE_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+}
+
+pub fn change_counter() -> u64 {
+ CHANGE_COUNTER.load(std::sync::atomic::Ordering::Relaxed)
+}
+
+impl BackgroundTaskRegistry {
+ /// A snapshot is a `try_lock` on a short critical section; a contended
+ /// cell reports "running" so a concurrent read never hides a live task.
+ fn snapshot(task: &BackgroundTask) -> (BackgroundTaskState, Option<i32>) {
+ task.shared
+ .try_lock()
+ .map(|shared| (shared.state, shared.exit_code))
+ .unwrap_or((BackgroundTaskState::Running, None))
+ }
+
+ fn is_running(task: &BackgroundTask) -> bool {
+ Self::snapshot(task).0 == BackgroundTaskState::Running
+ }
+
+ pub fn running_count(&self) -> usize {
+ self.tasks
+ .values()
+ .filter(|task| Self::is_running(task))
+ .count()
+ }
+
+ pub fn summaries(&self) -> Vec<BackgroundTaskSummary> {
+ let mut list: Vec<BackgroundTaskSummary> = self
+ .tasks
+ .values()
+ .map(|task| {
+ let (state, exit_code) = Self::snapshot(task);
+ BackgroundTaskSummary {
+ id: task.id.clone(),
+ session_id: task.session_id.clone(),
+ command: task.command.clone(),
+ command_shell_id: task.command_shell_id.clone(),
+ state,
+ elapsed_ms: task.started_at.elapsed().as_millis() as u64,
+ exit_code,
+ }
+ })
+ .collect();
+ // Running tasks first, then newest first, so the bar reads naturally.
+ list.sort_by(|a, b| {
+ let rank = |s: &BackgroundTaskSummary| {
+ if s.state == BackgroundTaskState::Running {
+ 0
+ } else {
+ 1
+ }
+ };
+ rank(a).cmp(&rank(b)).then_with(|| b.id.cmp(&a.id))
+ });
+ list
+ }
+}
+
+pub(crate) async fn spawn_background_task_detached(
+ state: &tokio::sync::Mutex<crate::state::AppState>,
+ session_id: &str,
+ command: &str,
+ command_shell_id: &str,
+ workspace: &std::path::Path,
+ scratch: Option<&std::path::Path>,
+) -> Result<String, (String, String)> {
+ let on_changed: Arc<dyn Fn() + Send + Sync> = Arc::new(bump_change_counter);
+ let config = resolve_runner_config(command_shell_id, command, workspace, scratch)?;
+ let runner = tools::spawn_tool_runner(&config).await?;
+ let mut st = state.lock().await;
+ if st.background_tasks.running_count() >= MAX_RUNNING_TASKS {
+ // Runner dropped here kills its process tree (kill-on-drop / job close).
+ drop(runner);
+ return Err((
+ "TOOL_FAILED".into(),
+ format!(
+ "too many background tasks are running (limit {MAX_RUNNING_TASKS}); stop one first"
+ ),
+ ));
+ }
+ let task = register_spawned_task(
+ &mut st.background_tasks,
+ session_id,
+ command,
+ command_shell_id,
+ runner,
+ on_changed,
+ );
+ // A start is a state change too. Without this bump the renderer would only
+ // learn about the task once it finished, so the running-tasks bar would stay
+ // empty for exactly as long as the process was alive.
+ bump_change_counter();
+ Ok(task.id)
+}
+
+fn resolve_runner_config(
+ command_shell_id: &str,
+ command: &str,
+ workspace: &std::path::Path,
+ scratch: Option<&std::path::Path>,
+) -> Result<tools::ToolRunnerStartConfig, (String, String)> {
+ let resolved = tools::shell::resolve_shell(command_shell_id)
+ .map_err(|message| ("SHELL_NOT_FOUND".to_string(), message))?;
+ let invocation = tools::shell::build_invocation_for_platform(
+ tools::shell::current_platform(),
+ command_shell_id,
+ resolved.program,
+ command,
+ )
+ .map_err(|message| ("INVALID_ARGUMENT".to_string(), message))?;
+ Ok(tools::ToolRunnerStartConfig {
+ program: invocation.program,
+ args: invocation.args,
+ workspace: workspace.to_path_buf(),
+ scratch_dir: scratch.map(|path| {
+ tools::shell::format_scratch_dir_for_shell(
+ tools::shell::dialect_for_id(command_shell_id),
+ path,
+ )
+ }),
+ env_path: tools::shell::user_login_path().map(str::to_string),
+ extra_env: Vec::new(),
+ })
+}
+
+fn register_spawned_task(
+ registry: &mut BackgroundTaskRegistry,
+ session_id: &str,
+ command: &str,
+ command_shell_id: &str,
+ runner: tools::SpawnedToolRunner,
+ on_changed: Arc<dyn Fn() + Send + Sync>,
+) -> BackgroundTask {
+ let (stop, stop_rx) = watch::channel(false);
+ let task = BackgroundTask {
+ id: uuid::Uuid::new_v4().to_string(),
+ session_id: session_id.to_string(),
+ command: command.to_string(),
+ command_shell_id: command_shell_id.to_string(),
+ started_at: Instant::now(),
+ shared: Arc::new(Mutex::new(TaskShared {
+ state: BackgroundTaskState::Running,
+ exit_code: None,
+ stdout: VecDeque::new(),
+ stderr: VecDeque::new(),
+ stdout_bytes: 0,
+ stderr_bytes: 0,
+ truncated: false,
+ stop,
+ })),
+ };
+ registry.order.push(task.id.clone());
+ registry.tasks.insert(task.id.clone(), task.clone());
+ registry.prune_finished();
+ tokio::spawn(supervise(task.clone(), runner, stop_rx, on_changed));
+ task
+}
+
+/// Drain pipes into the shared rings, honour the stop signal, and record the
+/// terminal state. Detached from any turn: only a stop request or host
+/// shutdown ends it.
+async fn supervise(
+ task: BackgroundTask,
+ mut runner: tools::SpawnedToolRunner,
+ mut stop_rx: watch::Receiver<bool>,
+ on_changed: Arc<dyn Fn() + Send + Sync>,
+) {
+ let stdout_pipe = runner.stdout.take();
+ let stderr_pipe = runner.stderr.take();
+ let (chunk_tx, mut chunk_rx) = tokio::sync::mpsc::channel::<(bool, Vec<u8>)>(64);
+ let stdout_reader = tokio::spawn(drain_pipe(stdout_pipe, true, chunk_tx.clone()));
+ let stderr_reader = tokio::spawn(drain_pipe(stderr_pipe, false, chunk_tx.clone()));
+ drop(chunk_tx);
+
+ let mut wait = runner.wait_task;
+ let exit = loop {
+ tokio::select! {
+ waited = &mut wait => break Some(waited),
+ chunk = chunk_rx.recv() => {
+ let Some((is_stdout, bytes)) = chunk else { continue };
+ let text = String::from_utf8_lossy(&bytes).replace('\r', "");
+ let mut shared = task.shared.lock().await;
+ let dropped = if is_stdout {
+ shared.push_stdout(&text)
+ } else {
+ shared.push_stderr(&text)
+ };
+ if dropped {
+ shared.truncated = true;
+ }
+ }
+ _ = stop_rx.changed() => {
+ if *stop_rx.borrow() {
+ // Kill the whole tree; the wait below reaps it.
+ let _ = runner.ownership.terminate_fail_closed(runner.pid);
+ break Some((&mut wait).await);
+ }
+ }
+ }
+ };
+ // The tree is gone or exiting, so both pipes reach EOF; joining the
+ // readers keeps the rings complete before the terminal state is published.
+ let _ = stdout_reader.await;
+ let _ = stderr_reader.await;
+ let status: Option<std::io::Result<std::process::ExitStatus>> =
+ exit.and_then(|joined| joined.ok());
+ let exit_code = status
+ .and_then(|inner| inner.ok())
+ .and_then(|status| status.code());
+
+ let stopped = *stop_rx.borrow();
+ let state = match (exit_code, stopped) {
+ (_, true) => BackgroundTaskState::Stopped,
+ (Some(0), false) => BackgroundTaskState::Exited,
+ (Some(_), false) => BackgroundTaskState::Failed,
+ (None, false) => BackgroundTaskState::Failed,
+ };
+ {
+ let mut shared = task.shared.lock().await;
+ shared.state = state;
+ shared.exit_code = exit_code;
+ }
+ on_changed();
+}
+
+async fn drain_pipe<R>(
+ pipe: Option<R>,
+ is_stdout: bool,
+ tx: tokio::sync::mpsc::Sender<(bool, Vec<u8>)>,
+) where
+ R: tokio::io::AsyncRead + Unpin,
+{
+ let Some(mut pipe) = pipe else { return };
+ let mut buffer = [0u8; 8192];
+ loop {
+ match pipe.read(&mut buffer).await {
+ Ok(0) | Err(_) => break,
+ Ok(read) => {
+ if tx.send((is_stdout, buffer[..read].to_vec())).await.is_err() {
+ break;
+ }
+ }
+ }
+ }
+}
+
+/// Registry operations that read or signal a task. Output reads and state
+/// snapshots go through the per-task shared cell and never block the registry.
+pub async fn stop_task(registry: &BackgroundTaskRegistry, id: &str) -> Result<bool, String> {
+ let Some(task) = registry.tasks.get(id).cloned() else {
+ return Ok(false);
+ };
+ let shared = task.shared.lock().await;
+ // Idempotent: a task that already finished or is already stopping reports
+ // "nothing to do" so a double click cannot queue a second kill.
+ if shared.state != BackgroundTaskState::Running || *shared.stop.borrow() {
+ return Ok(false);
+ }
+ let _ = shared.stop.send(true);
+ Ok(true)
+}
+
+pub async fn task_output(
+ registry: &BackgroundTaskRegistry,
+ id: &str,
+) -> Result<Option<serde_json::Value>, String> {
+ let Some(task) = registry.tasks.get(id) else {
+ return Ok(None);
+ };
+ let shared = task.shared.lock().await;
+ Ok(Some(serde_json::json!({
+ "id": task.id,
+ "state": shared.state,
+ "exitCode": shared.exit_code,
+ "stdout": TaskShared::render(&shared.stdout),
+ "stderr": TaskShared::render(&shared.stderr),
+ "truncated": shared.truncated,
+ })))
+}
+
+/// Best-effort stop used by `AppState::shutdown`, which cannot await. The
+/// signal wakes each supervisor; the tree is killed and reaped there, so
+/// shutdown never blocks on the AppState mutex and never leaves an orphan.
+pub fn stop_all_running_sync(registry: &BackgroundTaskRegistry) {
+ for task in registry.tasks.values() {
+ if let Ok(shared) = task.shared.try_lock() {
+ let _ = shared.stop.send(true);
+ }
+ }
+}
+
+impl BackgroundTaskRegistry {
+ fn prune_finished(&mut self) {
+ let finished: Vec<String> = self
+ .order
+ .iter()
+ .filter(|id| {
+ self.tasks
+ .get(*id)
+ .is_some_and(|task| !BackgroundTaskRegistry::is_running(task))
+ })
+ .cloned()
+ .collect();
+ if finished.len() <= FINISHED_TASK_HISTORY {
+ return;
+ }
+ for id in &finished[..finished.len() - FINISHED_TASK_HISTORY] {
+ self.order.retain(|existing| existing != id);
+ self.tasks.remove(id);
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::time::Duration;
+
+ /// A start must bump the change counter. The renderer only learns about a
+ /// running task through `backgroundTasks.changed`; a start that stays
+ /// silent leaves the running-tasks bar empty while the process is alive —
+ /// the exact regression this test locks down.
+ #[tokio::test]
+ async fn start_notifies_stop_settles_and_shutdown_reaps() {
+ let dir = tempfile::tempdir().unwrap();
+ let state = tokio::sync::Mutex::new(crate::state::AppState::open(dir.path()).unwrap());
+
+ let before_start = change_counter();
+ let id = spawn_background_task_detached(
+ &state,
+ "session-1",
+ "sleep 30",
+ crate::tools::shell::default_shell_id(),
+ dir.path(),
+ None,
+ )
+ .await
+ .unwrap();
+ assert!(
+ change_counter() > before_start,
+ "registering a task must notify listeners"
+ );
+
+ {
+ let st = state.lock().await;
+ let summaries = st.background_tasks.summaries();
+ assert_eq!(summaries.len(), 1, "the registry owns the started task");
+ assert_eq!(summaries[0].id, id);
+ assert_eq!(summaries[0].state, BackgroundTaskState::Running);
+ assert_eq!(summaries[0].command, "sleep 30");
+ assert_eq!(summaries[0].session_id, "session-1");
+ assert_eq!(st.background_tasks.running_count(), 1);
+ }
+
+ let before_stop = change_counter();
+ {
+ let st = state.lock().await;
+ assert!(stop_task(&st.background_tasks, &id).await.unwrap());
+ assert!(
+ !stop_task(&st.background_tasks, &id).await.unwrap(),
+ "a task that is already stopping is not stopped twice"
+ );
+ }
+
+ // The detached supervisor kills the tree and records the terminal
+ // state; nothing here blocks the turn that started the task.
+ let mut settled = None;
+ for _ in 0..100 {
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ let st = state.lock().await;
+ let summary = st.background_tasks.summaries().remove(0);
+ if summary.state != BackgroundTaskState::Running {
+ settled = Some(summary);
+ break;
+ }
+ }
+ let settled = settled.expect("the stopped task reaches a terminal state");
+ assert_eq!(settled.state, BackgroundTaskState::Stopped);
+ assert!(
+ change_counter() > before_stop,
+ "the terminal state must notify listeners"
+ );
+
+ {
+ let st = state.lock().await;
+ let output = task_output(&st.background_tasks, &id)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(output["id"], serde_json::json!(id));
+ assert_eq!(output["state"], serde_json::json!("stopped"));
+ assert_eq!(st.background_tasks.running_count(), 0);
+ }
+ }
+
+ /// Application exit must not leave an orphan: `AppState::shutdown` signals
+ /// every running supervisor, which kills and reaps its process tree.
+ #[tokio::test]
+ async fn shutdown_stops_every_running_task() {
+ let dir = tempfile::tempdir().unwrap();
+ let state = tokio::sync::Mutex::new(crate::state::AppState::open(dir.path()).unwrap());
+ spawn_background_task_detached(
+ &state,
+ "session-1",
+ "sleep 30",
+ crate::tools::shell::default_shell_id(),
+ dir.path(),
+ None,
+ )
+ .await
+ .unwrap();
+
+ {
+ let mut st = state.lock().await;
+ assert_eq!(st.background_tasks.running_count(), 1);
+ st.shutdown();
+ }
+
+ let mut settled = None;
+ for _ in 0..100 {
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ let st = state.lock().await;
+ if st.background_tasks.running_count() == 0 {
+ settled = Some(st.background_tasks.summaries().remove(0).state);
+ break;
+ }
+ }
+ assert_eq!(
+ settled.expect("shutdown stops the running task"),
+ BackgroundTaskState::Stopped
+ );
+ }
+}
diff --git a/crates/host-core/src/main.rs b/crates/host-core/src/main.rs
index 36e8c7eda..3b5036678 100644
--- a/crates/host-core/src/main.rs
+++ b/crates/host-core/src/main.rs
@@ -2,6 +2,7 @@ mod activation;
mod agent_capabilities;
mod artifacts;
mod audit;
+mod background_tasks;
mod config_sync;
mod data_relocation;
mod db;
diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rs
index 52001553d..ea707e45f 100644
--- a/crates/host-core/src/rpc/mod.rs
+++ b/crates/host-core/src/rpc/mod.rs
@@ -20,6 +20,7 @@ use tokio::sync::{mpsc, oneshot, Mutex, Semaphore};
use crate::agent_capabilities::CapabilityLevel;
use crate::artifacts;
use crate::audit;
+use crate::background_tasks;
use crate::notifications;
use crate::permissions::{PermissionDecision, PermissionEvaluationParams, PermissionManager};
use crate::plans;
@@ -308,6 +309,27 @@ pub async fn serve(state: Arc<Mutex<AppState>>) -> Result<()> {
// chord. Keep the native fallback beside the host transport so it remains
// active even when PI-Desktop is unfocused.
crate::keyboard::start(tx.clone());
+ // Fan background-task state changes out to the renderer. The supervisors
+ // bump a static counter (no AppState lock involved); this loop watches it
+ // and emits `backgroundTasks.changed` so the composer bar stays current.
+ let background_change_task = {
+ let tx = tx.clone();
+ tokio::spawn(async move {
+ let mut seen = background_tasks::change_counter();
+ loop {
+ tokio::time::sleep(std::time::Duration::from_millis(250)).await;
+ let current = background_tasks::change_counter();
+ if current != seen {
+ seen = current;
+ send_notification(
+ &tx,
+ "backgroundTasks.changed",
+ json!({ "version": current }),
+ );
+ }
+ }
+ })
+ };
let (input_tx, mut input_rx) = mpsc::unbounded_channel::<StdinEvent>();
let _stdin_reader = match spawn_stdin_reader(input_tx) {
Ok(handle) => handle,
@@ -458,6 +480,8 @@ pub async fn serve(state: Arc<Mutex<AppState>>) -> Result<()> {
config_sync_scheduler.abort();
let _ = config_sync_scheduler.await;
+ background_change_task.abort();
+ let _ = background_change_task.await;
{
let mut st = state.lock().await;
st.shutdown();
@@ -519,6 +543,18 @@ fn request_budget_ms(method: &str, params: &Value) -> Option<u64> {
if !matches!(method, "tools.execute" | "tools.workspaceExecute") {
return Some(RPC_REQUEST_BUDGET_MS);
}
+ // A background Bash call returns as soon as the process is spawned; the
+ // task lives in the registry, not in this request. The sidecar relay must
+ // not budget it like a foreground execution or the turn's abort path
+ // would race the spawn.
+ let run_in_background = params
+ .get("runInBackground")
+ .or_else(|| params.get("run_in_background"))
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false);
+ if run_in_background {
+ return Some(RPC_REQUEST_BUDGET_MS + RPC_TOOL_BUDGET_GRACE_MS);
+ }
// `ToolsExecuteParams` is `#[serde(rename_all = "camelCase")]`, so the wire
// carries `toolName` / `timeoutMs`. Reading the snake_case spellings here
// would see an empty tool name and no timeout on every real request,
@@ -3784,6 +3820,45 @@ async fn handle_request(
}
Ok(json!({ "tools": definitions }))
}
+ "backgroundTasks.list" => {
+ let st = state.lock().await;
+ Ok(json!({
+ "tasks": st.background_tasks.summaries(),
+ // The change counter is the single version source: supervisors
+ // bump it on every transition and the renderer re-lists on the
+ // matching notification.
+ "version": background_tasks::change_counter(),
+ }))
+ }
+ "backgroundTasks.output" => {
+ let id = params
+ .get("id")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
+ let st = state.lock().await;
+ match background_tasks::task_output(&st.background_tasks, id).await {
+ Ok(Some(output)) => Ok(output),
+ // `NOT_FOUND` is the registered, documented code for an unknown
+ // entity id; a dedicated TASK_NOT_FOUND would be a new contract
+ // (ErrorCodes + 08-error-codes) for no behavioural gain.
+ Ok(None) => Err(rpc_err(1007, "task not found", "NOT_FOUND")),
+ Err(message) => Err(rpc_err(1000, message, "INTERNAL")),
+ }
+ }
+ "backgroundTasks.stop" => {
+ let id = params
+ .get("id")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
+ let st = state.lock().await;
+ // Signalling is enough: the supervisor kills the tree, records the
+ // terminal state, and bumps the change counter, which fans out the
+ // `backgroundTasks.changed` notification for this same task.
+ let found = background_tasks::stop_task(&st.background_tasks, id)
+ .await
+ .map_err(|message| rpc_err(1000, message, "INTERNAL"))?;
+ Ok(json!({ "ok": true, "found": found }))
+ }
"tools.execute" => {
let call_started = std::time::Instant::now();
let p: ToolsExecuteParams = serde_json::from_value(params.clone())
@@ -3859,7 +3934,11 @@ async fn handle_request(
// Register before permission evaluation so tools.abort can cancel
// an approval wait as well as an already-spawned process.
let cancellation_receiver = if remote_workspace.is_some()
- || matches!(p.tool_name.as_str(), "Bash" | "GenerateImages")
+ || (matches!(p.tool_name.as_str(), "Bash" | "GenerateImages")
+ // A background Bash task is detached from the turn: it
+ // never joins the per-tool-call cancellation registry, so
+ // tools.abort / agent.abort cannot kill it.
+ && !p.run_in_background)
{
let mut st = state.lock().await;
match st.register_bash_cancellation(&p.session_id, &p.tool_call_id) {
@@ -4315,6 +4394,8 @@ async fn handle_request(
cancellation,
output_tx: Some(tx.clone()),
extra_env: worktree_env.clone(),
+ run_in_background: p.run_in_background,
+ app_state: Some(state.clone()),
});
}
diff --git a/crates/host-core/src/rpc/remote_tools.rs b/crates/host-core/src/rpc/remote_tools.rs
index 908dd6352..19f461eed 100644
--- a/crates/host-core/src/rpc/remote_tools.rs
+++ b/crates/host-core/src/rpc/remote_tools.rs
@@ -342,6 +342,8 @@ pub(super) async fn handle(
output_tx: Some(tx),
// Remote workspaces are never isolated (ADR 0329).
extra_env: Vec::new(),
+ run_in_background: false,
+ app_state: None,
})
} else {
None
diff --git a/crates/host-core/src/rpc/worktree_rpc/tests.rs b/crates/host-core/src/rpc/worktree_rpc/tests.rs
index 7f2df80b5..ef7c349bb 100644
--- a/crates/host-core/src/rpc/worktree_rpc/tests.rs
+++ b/crates/host-core/src/rpc/worktree_rpc/tests.rs
@@ -138,6 +138,8 @@ async fn isolated_session_user_path_from_create_to_delete() {
cancellation: None,
output_tx: None,
extra_env: env,
+ run_in_background: false,
+ app_state: None,
})),
)
.await;
diff --git a/crates/host-core/src/session_worktrees/lifecycle.rs b/crates/host-core/src/session_worktrees/lifecycle.rs
index 1c7a5c4bd..7f28157ab 100644
--- a/crates/host-core/src/session_worktrees/lifecycle.rs
+++ b/crates/host-core/src/session_worktrees/lifecycle.rs
@@ -437,6 +437,8 @@ pub(super) async fn run_setup(
cancellation: None,
output_tx: None,
extra_env: env_for(&row, Some(&project_path)),
+ run_in_background: false,
+ app_state: None,
}),
allow_external_paths: false,
hashline: None,
diff --git a/crates/host-core/src/state.rs b/crates/host-core/src/state.rs
index a46d35db9..56d473491 100644
--- a/crates/host-core/src/state.rs
+++ b/crates/host-core/src/state.rs
@@ -59,6 +59,9 @@ pub struct AppState {
pub plugin_import_rates: HashMap<String, Vec<Instant>>,
pub plugin_batch_import_rates: HashMap<String, Vec<Instant>>,
pub plugin_delete_rates: HashMap<String, Vec<Instant>>,
+ /// Chat-started processes detached from their turn (dev servers, etc.).
+ /// Lives with the host process; `shutdown` stops every running task.
+ pub background_tasks: crate::background_tasks::BackgroundTaskRegistry,
pub tool_budget: ToolBudget,
/// (session_id, tool_call_id) -> cancellation signal for an active Bash
/// process. The signal is removed by the execution owner in all outcomes.
@@ -138,6 +141,7 @@ impl AppState {
user_subagents,
config_sync_lock: Arc::new(tokio::sync::Mutex::new(())),
config_sync_in_progress: Arc::new(AtomicBool::new(false)),
+ background_tasks: crate::background_tasks::BackgroundTaskRegistry::default(),
started_at: Instant::now(),
handshook: false,
shutting_down: false,
@@ -297,6 +301,9 @@ impl AppState {
let _ = sender.send(true);
}
self.active_bash_cancellations.clear();
+ // Chat-started background tasks follow the application: signal every
+ // running supervisor so its process tree is terminated and reaped.
+ crate::background_tasks::stop_all_running_sync(&self.background_tasks);
let pending_request_ids: Vec<String> = self.pending_permissions.keys().cloned().collect();
for request_id in pending_request_ids {
diff --git a/crates/host-core/src/tools/mod.rs b/crates/host-core/src/tools/mod.rs
index 4a77ec1db..fe05c1f34 100644
--- a/crates/host-core/src/tools/mod.rs
+++ b/crates/host-core/src/tools/mod.rs
@@ -8,7 +8,10 @@ use std::future::pending;
use std::io::{self, BufRead, BufReader, ErrorKind, Read};
use std::path::{Path, PathBuf};
use std::process::{ExitStatus, Stdio};
-use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::{
+ atomic::{AtomicU64, Ordering},
+ Arc,
+};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
#[cfg(not(test))]
use tokio::io::AsyncWriteExt;
@@ -61,12 +64,12 @@ use windows_sys::Win32::System::JobObjects::{
#[cfg(windows)]
#[derive(Debug, Default)]
-struct ProcessOwnership {
+pub(crate) struct ProcessOwnership {
job: Option<HANDLE>,
}
#[cfg(not(windows))]
#[derive(Debug, Default)]
-struct ProcessOwnership;
+pub(crate) struct ProcessOwnership;
impl ProcessOwnership {
#[cfg(windows)]
@@ -176,7 +179,7 @@ impl ProcessOwnership {
#[cfg(not(windows))]
fn close_now(&mut self) {}
- fn terminate_fail_closed(&mut self, pid: u32) -> Result<(), String> {
+ pub(crate) fn terminate_fail_closed(&mut self, pid: u32) -> Result<(), String> {
match self.terminate(pid) {
Ok(()) => Ok(()),
Err(error) => {
@@ -206,18 +209,18 @@ impl Drop for ProcessOwnership {
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
-struct ToolRunnerStartConfig {
- program: PathBuf,
- args: Vec<String>,
- workspace: PathBuf,
+pub(crate) struct ToolRunnerStartConfig {
+ pub(crate) program: PathBuf,
+ pub(crate) args: Vec<String>,
+ pub(crate) workspace: PathBuf,
#[serde(default)]
- scratch_dir: Option<PathBuf>,
+ pub(crate) scratch_dir: Option<PathBuf>,
#[serde(default)]
- env_path: Option<String>,
+ pub(crate) env_path: Option<String>,
/// Session-scoped variables such as `PI_PORT` for an isolated worktree
/// (ADR 0329). Empty for every other call.
#[serde(default)]
- extra_env: Vec<(String, String)>,
+ pub(crate) extra_env: Vec<(String, String)>,
}
fn path_has_nul(path: &Path) -> bool {
@@ -579,6 +582,8 @@ pub struct ToolsExecuteParams {
pub expected_command_shell_id: Option<String>,
#[serde(default)]
pub expected_command_shell_dialect: Option<String>,
+ #[serde(default)]
+ pub run_in_background: bool,
pub timeout_ms: Option<u64>,
/// Action names that may run in Plan or Goal mode (ADR 0211). When
/// set and non-empty, host-core admits this `plugin_*` tool in
@@ -764,7 +769,6 @@ fn spill_output(scratch: Option<&Path>, label: &str, text: &str) -> Option<PathB
}
}
-#[derive(Debug)]
pub struct BashExecutionOptions {
pub session_id: String,
pub tool_call_id: String,
@@ -774,6 +778,12 @@ pub struct BashExecutionOptions {
pub output_tx: Option<mpsc::UnboundedSender<String>>,
/// Extra environment for the command, e.g. `PI_PORT` (ADR 0329).
pub extra_env: Vec<(String, String)>,
+ /// Start as a background task detached from the turn: no timeout, no
+ /// abort wiring. The caller owns the registry; see `background_tasks`.
+ pub run_in_background: bool,
+ /// Host state the background spawn registers into. Present for RPC-driven
+ /// calls; `None` for test/`local` constructions that never go background.
+ pub app_state: Option<Arc<tokio::sync::Mutex<crate::state::AppState>>>,
}
impl BashExecutionOptions {
@@ -786,6 +796,8 @@ impl BashExecutionOptions {
cancellation: None,
output_tx: None,
extra_env: Vec::new(),
+ run_in_background: false,
+ app_state: None,
}
}
}
@@ -2549,16 +2561,16 @@ async fn wait_for_cancellation(receiver: &mut Option<watch::Receiver<bool>>) ->
}
}
-struct SpawnedToolRunner {
- pid: u32,
- ownership: ProcessOwnership,
+pub(crate) struct SpawnedToolRunner {
+ pub(crate) pid: u32,
+ pub(crate) ownership: ProcessOwnership,
control: Option<ChildStdin>,
- stdout: Option<ChildStdout>,
- stderr: Option<ChildStderr>,
- wait_task: tokio::task::JoinHandle<std::io::Result<ExitStatus>>,
+ pub(crate) stdout: Option<ChildStdout>,
+ pub(crate) stderr: Option<ChildStderr>,
+ pub(crate) wait_task: tokio::task::JoinHandle<std::io::Result<ExitStatus>>,
}
-async fn spawn_tool_runner(
+pub(crate) async fn spawn_tool_runner(
config: &ToolRunnerStartConfig,
) -> Result<SpawnedToolRunner, (String, String)> {
#[cfg(not(test))]
@@ -2758,14 +2770,42 @@ async fn tool_bash(
args: &Value,
options: BashExecutionOptions,
) -> Result<Value, (String, String)> {
- let timeout_ms = options.timeout_ms.unwrap_or(DEFAULT_BASH_TIMEOUT_MS);
- validate_bash_timeout_ms(timeout_ms)?;
let root = require_workspace(workspace)?;
let command = args
.get("command")
.and_then(|v| v.as_str())
.ok_or_else(|| ("INVALID_ARGUMENT".into(), "command required".into()))?;
+ // Background path: register the process with the detached registry and
+ // return immediately. No timeout budget, no cancellation wiring — the
+ // task outlives the turn by design and is reported via
+ // `backgroundTasks.changed` / `backgroundTasks.*` RPC.
+ if options.run_in_background {
+ let Some(app_state) = options.app_state.as_ref() else {
+ return Err((
+ "INVALID_ARGUMENT".into(),
+ "background execution requires host state (not available for local calls)".into(),
+ ));
+ };
+ let started = crate::background_tasks::spawn_background_task_detached(
+ app_state,
+ &options.session_id,
+ command,
+ &options.command_shell_id,
+ root,
+ scratch,
+ )
+ .await?;
+ return Ok(serde_json::json!({
+ "backgroundTaskId": started,
+ "command": command,
+ "commandShellId": options.command_shell_id,
+ }));
+ }
+
+ let timeout_ms = options.timeout_ms.unwrap_or(DEFAULT_BASH_TIMEOUT_MS);
+ validate_bash_timeout_ms(timeout_ms)?;
+
let resolved = shell::resolve_shell(&options.command_shell_id)
.map_err(|message| ("SHELL_NOT_FOUND".to_string(), message))?;
let invocation = shell::build_invocation_for_platform(
@@ -4747,6 +4787,8 @@ mod tests {
cancellation: None,
output_tx: None,
extra_env: Vec::new(),
+ run_in_background: false,
+ app_state: None,
}),
)
.await;
@@ -4789,6 +4831,8 @@ mod tests {
cancellation: None,
output_tx: None,
extra_env: Vec::new(),
+ run_in_background: false,
+ app_state: None,
}),
)
.await;
@@ -4826,6 +4870,8 @@ mod tests {
cancellation: None,
output_tx: None,
extra_env: Vec::new(),
+ run_in_background: false,
+ app_state: None,
}),
)
.await;
@@ -4896,6 +4942,8 @@ mod tests {
cancellation: None,
output_tx: Some(tx),
extra_env: Vec::new(),
+ run_in_background: false,
+ app_state: None,
};
let mut notifier = OutputNotifier::new(&options);
for _ in 0..(MAX_OUTPUT_NOTIFICATIONS + 100) {
@@ -4922,6 +4970,8 @@ mod tests {
cancellation: None,
output_tx: None,
extra_env: Vec::new(),
+ run_in_background: false,
+ app_state: None,
};
let output = execute_tool_with_options(
diff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.md
index f930d3b62..3774fb3d5 100644
--- a/docs/spec/03-runtime/03-tools-and-permissions.md
+++ b/docs/spec/03-runtime/03-tools-and-permissions.md
@@ -424,6 +424,12 @@ Host execution baseline:
- A command that exits non-zero returns `ok: false`, `isError: true`, and
`errorCode: TOOL_FAILED` while preserving its `exitCode`, stdout, and stderr
in `content` so the agent can diagnose the command without blindly retrying.
+- `runInBackground: true` detaches the command from the turn: the call returns
+ `backgroundTaskId` as soon as the shell starts, no timeout applies, and the
+ process survives `tools.abort` and `agent.abort`. The host owns the process
+ tree, reports it through the composer's running-tasks bar, and stops it on
+ request or on app shutdown. At most 32 tasks run concurrently and each stream
+ keeps its last 256KB.
Shell catalog (D190) exposes the stable IDs `windows-powershell`, `windows-pwsh`,
`cmd`, `git-bash`, and `bash` where supported by the platform. The host persists
diff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.md
index 1e674a39a..30df9c2c6 100644
--- a/docs/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md
@@ -664,6 +664,21 @@ Additive `worktree.*` methods; no protocol version bump. Failures use code
- `tools.abort`
- `tools.output` notifications for ordered `stdout`/`stderr` chunks
+### Background tasks
+- `backgroundTasks.list`
+- `backgroundTasks.output`
+- `backgroundTasks.stop`
+- `backgroundTasks.changed` notification carrying `{ version }`, emitted when a
+ task starts, exits, or is stopped
+
+A `tools.execute` call with `runInBackground: true` starts a `Bash` command the
+host owns instead of the turn: the call resolves immediately with a
+`backgroundTaskId`, the task never joins the per-tool-call cancellation registry
+so `tools.abort` / `agent.abort` cannot reach it, and its output is kept in
+bounded per-stream rings. The registry lives in the host process, so every task
+stops during host shutdown and an application exit never leaves an orphan
+process.
+
### Shells
- `commandShells.list`
- `settings.set` with a partial settings object; omitted fields are preserved,
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 7459ee380..709eff466 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -7693,6 +7693,29 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
descendant process tree and verifies no late marker/output; host-core tests
verify cancellation registry cleanup
+#### E2E-265: Background Bash tasks outlive their turn
+
+- **Preconditions**: A project session whose catalog shell supports background
+ execution, and a port the test server may bind.
+- **Steps**: 1) Ask the agent to start a long-lived process with
+ `runInBackground` (a local web server) and watch the running-tasks bar above
+ the composer. 2) Abort the turn, send a second prompt in the same session,
+ then reload the renderer. 3) Expand the row's `Output`. 4) Press `Stop`.
+ 5) Start two more tasks and quit the app.
+- **Expected**: The tool result carries `backgroundTaskId` and resolves without
+ waiting for the command; the bar lists the task as running with a growing
+ elapsed time and shows its streamed output; the process stays alive across the
+ abort, across the 60-second Bash timeout, and across a renderer reload.
+ `Stop` settles the row to `Stopped` and kills the process tree; quitting the
+ app leaves no orphan process behind.
+- **Specs linked**: `03-runtime/03-tools-and-permissions.md` (§5),
+ `03-runtime/06-host-rpc-protocol.md` (§4)
+- **Acceptance criterion**: C, E, F
+- **Milestone**: M6+
+- **Status**: Partially automated (host-core `background_tasks::tests` and the
+ renderer contract test `apps/desktop/test/background-tasks.test.mjs`; the bar
+ interaction itself is manual)
+
#### E2E-117: Agent/Plan/Goal UX and locales contain no Chat controls
- **Preconditions**: App can run in English and zh-CN with an idle session,
@@ -10042,6 +10065,7 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
| Quality (loop context ownership) | E2E-RUNTIME-loop-context-ownership |
| G — Plugin host lifecycle (crash report) | E2E-PLUGIN-crash-report-names-the-exit-code |
| Quality (crash report) | E2E-PLUGIN-crash-report-names-the-exit-code |
+| C / E / F / Quality — Background Bash tasks outlive their turn | E2E-265 |
The `US-UI-*` visual scenarios (§UI shell visual scenarios) trace to the
Codex parity decisions in [decisions-log §D](../08-meta/decisions-log.md)
diff --git a/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md b/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md
index bc44ac87d..4564a21be 100644
--- a/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md
+++ b/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md
@@ -385,6 +385,10 @@ tool/protocol 名称,请求中单独携带固定的 shell ID。
- Git Bash 使用发现的 Git 来执行 Windows 可执行文件。
- Unix Bash 使用经过批准的系统 Bash 条目。
- 用户中止和超时在返回之前终止整个进程树。
+- `runInBackground: true` 让命令脱离本轮:shell 一启动就返回 `backgroundTaskId`,
+ 不再套用超时,进程也不会被 `tools.abort` / `agent.abort` 终止。进程树归宿主
+ 所有,通过输入框上方的运行中任务栏展示,可由用户停止或随应用退出而结束。
+ 最多同时运行 32 个任务,每个输出流保留最后 256KB。
初始拒绝名单(可扩展):
diff --git a/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md b/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md
index 5b7a66211..804eed599 100644
--- a/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md
@@ -453,6 +453,17 @@ off | minimal | low | medium | high | xhigh | max
- `tools.abort`
- 有序 `stdout`/`stderr` 块的 `tools.output` 通知
+### 后台任务
+- `backgroundTasks.list`
+- `backgroundTasks.output`
+- `backgroundTasks.stop`
+- `backgroundTasks.changed` 通知,携带 `{ version }`;任务启动、退出或被停止时发出
+
+`tools.execute` 带 `runInBackground: true` 时启动的是归宿主所有的 `Bash` 命令,
+而不是本轮的命令:调用立即以 `backgroundTaskId` 返回,任务不进入按工具调用注册的
+取消表,因此 `tools.abort` / `agent.abort` 都无法触及它,输出按流保存在有界环形缓冲
+中。注册表位于宿主进程内,宿主关闭时会停止全部任务,因此应用退出不会残留孤儿进程。
+
### 贝壳
- `commandShells.list`
- `settings.set` 带有部分设置对象;保留省略的字段,
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index 44a7404d2..39c786d91 100644
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@ -4512,6 +4512,22 @@ eleven-tool-round desktop paths are verified by
后代进程树并验证没有迟到的 marker/output; host-core 测试
验证取消注册表清理
+#### E2E-265:后台 Bash 任务在回合结束后继续运行
+
+- **前置条件**:项目会话,其目录 shell 支持后台执行;测试服务可绑定的端口。
+- **步骤**:1) 让 agent 用 `runInBackground` 启动长驻进程(本地 Web 服务),观察
+ 输入框上方的运行中任务栏。2) 中止本轮,在同一会话发送第二条提示,然后重新加载
+ 渲染进程。3) 展开该行的“输出”。4) 点击“停止”。5) 再启动两个任务后退出应用。
+- **预期**:工具结果携带 `backgroundTaskId` 且不等待命令结束;任务栏显示运行中的
+ 任务与递增的耗时,并展示流式输出;进程在中止后、Bash 60 秒超时后、渲染进程重载后
+ 仍然存活。“停止”把该行落定为“已停止”并杀掉整个进程树;退出应用后不残留孤儿进程。
+- **关联规范**:`03-runtime/03-tools-and-permissions.md`(§5)、
+ `03-runtime/06-host-rpc-protocol.md`(§4)
+- **验收标准**:C、E、F
+- **里程碑**:M6+
+- **状态**:部分自动化(host-core `background_tasks::tests`、渲染层契约测试
+ `apps/desktop/test/background-tasks.test.mjs`;任务栏交互本身仍为人工验证)
+
#### E2E-117:Agent/Plan/Goal UX 和区域设置不包含聊天控件
- **先决条件**:应用程序可以在空闲会话下以英语和 zh-CN 运行,
@@ -5811,6 +5827,7 @@ eleven-tool-round desktop paths are verified by
| 品质(循环上下文归属) | E2E-RUNTIME-loop-context-ownership |
| G — 插件宿主生命周期(崩溃上报) | E2E-PLUGIN-crash-report-names-the-exit-code |
| 品质(崩溃上报) | E2E-PLUGIN-crash-report-names-the-exit-code |
+| C / E / F / 品质 —— 后台 Bash 任务在回合结束后继续运行 | E2E-265 |
| F — 持久化(存储的模型绑定数组) | E2E-PROVIDER-stored-binding-array-reads-entry-by-entry |
| 品质(存储的模型绑定数组) | E2E-PROVIDER-stored-binding-array-reads-entry-by-entry |
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index b85d50697..608274521 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -1327,6 +1327,7 @@ function commandShellToolDescription(
shellSyntaxGuidance(shell),
`The session scratch directory variable is ${shellScratchVariable(shell)}.`,
`An optional timeout from 1 to ${MAX_COMMAND_TIMEOUT_SECONDS} seconds may be supplied; without it, the command defaults to a 60-second timeout.`,
+ `Set runInBackground: true for long-lived processes the user needs after the turn ends (dev servers, watchers, builds). A background call returns a backgroundTaskId immediately, survives turn aborts and timeouts, and its output is visible in the composer's running-tasks bar; do not set it for commands whose output the current turn depends on.`,
...(formattedScratch ? [`The session scratch directory is ${formattedScratch}.`] : []),
].join(" ");
}
@@ -3386,6 +3387,12 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
`Optional command timeout in seconds from 1 to ${MAX_COMMAND_TIMEOUT_SECONDS}; defaults to 60 seconds.`,
}),
),
+ runInBackground: Type.Optional(
+ Type.Boolean({
+ description:
+ "Start the command as a background task that outlives the turn (dev servers, watchers, builds). Returns backgroundTaskId immediately; ignored with timeout.",
+ }),
+ ),
},
PluginScaffold: {
template: Type.String(),
@@ -3523,6 +3530,9 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
expectedCommandShellId: this.commandShell.id,
expectedCommandShellDialect: this.commandShell.dialect,
timeoutMs,
+ ...(isRecord(params) && params.runInBackground === true
+ ? { runInBackground: true }
+ : {}),
}
: {}),
...(toolName.startsWith("plugin_")
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index bf51b92a8..0c9e398af 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -662,6 +662,16 @@ export const de = {
"renameSave": "Speichern",
"renameSaving": "Speichern…"
},
+ backgroundTasks: {
+ running: "Läuft",
+ exited: "Beendet",
+ failed: "Fehlgeschlagen",
+ stopped: "Gestoppt",
+ title: "Hintergrundbefehle",
+ output: "Ausgabe",
+ stop: "Stoppen",
+ stopping: "Stoppe…",
+ },
planHistory: {
pending: "Genehmigung ausstehend",
approved: "Genehmigt",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index d6cf547cb..1069665ff 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -674,6 +674,16 @@ export const en = {
renameSave: "Save",
renameSaving: "Saving…",
},
+ backgroundTasks: {
+ running: "Running",
+ exited: "Exited",
+ failed: "Failed",
+ stopped: "Stopped",
+ title: "Background commands",
+ output: "Output",
+ stop: "Stop",
+ stopping: "Stopping…",
+ },
planHistory: {
pending: "Awaiting approval",
approved: "Approved",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index 3b434a2a8..9ff749c6b 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -662,6 +662,16 @@ export const es = {
"renameSave": "Guardar",
"renameSaving": "Guardando…"
},
+ backgroundTasks: {
+ running: "En ejecución",
+ exited: "Finalizado",
+ failed: "Fallido",
+ stopped: "Detenido",
+ title: "Comandos en segundo plano",
+ output: "Salida",
+ stop: "Detener",
+ stopping: "Deteniendo…",
+ },
planHistory: {
pending: "Pendiente de aprobación",
approved: "Aprobado",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index 8cad1aa64..96f10ef4f 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -662,6 +662,16 @@ export const fr = {
"renameSave": "Enregistrer",
"renameSaving": "Enregistrer…"
},
+ backgroundTasks: {
+ running: "En cours",
+ exited: "Terminé",
+ failed: "Échec",
+ stopped: "Arrêté",
+ title: "Commandes en arrière-plan",
+ output: "Sortie",
+ stop: "Arrêter",
+ stopping: "Arrêt…",
+ },
planHistory: {
pending: "En attente d’approbation",
approved: "Approuvé",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index 68559465d..441f8d2f8 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -671,6 +671,16 @@ export const ko = {
renameSave: "저장",
renameSaving: "저장 중…",
},
+ backgroundTasks: {
+ running: "실행 중",
+ exited: "종료됨",
+ failed: "실패",
+ stopped: "중지됨",
+ title: "백그라운드 명령",
+ output: "출력",
+ stop: "중지",
+ stopping: "중지 중…",
+ },
planHistory: {
pending: "승인 대기",
approved: "승인됨",
diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.ts
index 58491bc13..63dadb787 100644
--- a/packages/i18n/src/locales/pt-BR/index.ts
+++ b/packages/i18n/src/locales/pt-BR/index.ts
@@ -661,6 +661,16 @@ export const ptBR = {
renameSave: "Salvar",
renameSaving: "Salvando…"
},
+ backgroundTasks: {
+ running: "Em execução",
+ exited: "Finalizado",
+ failed: "Falhou",
+ stopped: "Parado",
+ title: "Comandos em segundo plano",
+ output: "Saída",
+ stop: "Parar",
+ stopping: "Parando…",
+ },
planHistory: {
pending: "Aguardando aprovação",
approved: "Aprovado",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index 63a08e057..643498294 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -671,6 +671,16 @@ export const tr = {
renameSave: "Kaydet",
renameSaving: "Kaydediliyor…",
},
+ backgroundTasks: {
+ running: "Çalışıyor",
+ exited: "Çıktı",
+ failed: "Başarısız",
+ stopped: "Durduruldu",
+ title: "Arka plan komutları",
+ output: "Çıktı",
+ stop: "Durdur",
+ stopping: "Durduruluyor…",
+ },
planHistory: {
pending: "Onay bekleniyor",
approved: "Onaylandı",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index 11df7b16f..3eae9f35d 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -667,6 +667,16 @@ export const zhCN = {
renameSave: "保存",
renameSaving: "保存中…",
},
+ backgroundTasks: {
+ running: "运行中",
+ exited: "已退出",
+ failed: "失败",
+ stopped: "已停止",
+ title: "后台命令",
+ output: "输出",
+ stop: "停止",
+ stopping: "停止中…",
+ },
planHistory: {
pending: "待审批",
approved: "已批准",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index 27467e44b..d36b5cf91 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -667,6 +667,16 @@ export const zhTW = {
renameSave: "儲存",
renameSaving: "儲存中…",
},
+ backgroundTasks: {
+ running: "執行中",
+ exited: "已結束",
+ failed: "失敗",
+ stopped: "已停止",
+ title: "背景命令",
+ output: "輸出",
+ stop: "停止",
+ stopping: "停止中…",
+ },
planHistory: {
pending: "待審批",
approved: "已批准",
diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.ts
index b8cf71270..d77114286 100644
--- a/packages/shared/src/protocol.ts
+++ b/packages/shared/src/protocol.ts
@@ -169,6 +169,9 @@ export const IPC = {
settingsGet: "pi-desktop/settings/get",
settingsSet: "pi-desktop/settings/set",
configSyncGetState: "pi-desktop/configSync/getState",
+ backgroundTasksList: "pi-desktop/backgroundTasks/list",
+ backgroundTasksOutput: "pi-desktop/backgroundTasks/output",
+ backgroundTasksStop: "pi-desktop/backgroundTasks/stop",
configSyncConfigure: "pi-desktop/configSync/configure",
configSyncTest: "pi-desktop/configSync/test",
configSyncSyncNow: "pi-desktop/configSync/syncNow",
@@ -417,6 +420,8 @@ export const IPC = {
/** Host-originated app settings mutation (e.g. plugin `app.setTheme`). */
settingsChanged: "pi-desktop/app/event/settingsChanged",
configSyncChanged: "pi-desktop/configSync/event/changed",
+ /** A chat-started background task started, exited, or was stopped. */
+ backgroundTasksChanged: "pi-desktop/backgroundTasks/event/changed",
/** What a running sync is doing, while it is still running. */
configSyncProgress: "pi-desktop/configSync/event/progress",
extensionsUiPrompt: "pi-desktop/extensions/event/uiPrompt",