Skip to content

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

fix(background-tasks): bound previews and drain process output

algerccf588bfc7f1
diff --git a/apps/desktop/src/components/BackgroundTasksBar.tsx b/apps/desktop/src/components/BackgroundTasksBar.tsx
index 15d0bca29..5dbd25016 100644
--- a/apps/desktop/src/components/BackgroundTasksBar.tsx
+++ b/apps/desktop/src/components/BackgroundTasksBar.tsx
@@ -1,10 +1,7 @@
-import { useCallback, useEffect, useMemo, useState } from "react";
+import { useMemo } from "react";
import { useTranslation } from "react-i18next";
-import {
- api,
- type BackgroundTaskOutput,
- type BackgroundTaskSummary,
-} from "../lib/api";
+import type { BackgroundTaskOutput } from "../lib/api";
+import { useBackgroundTasks } from "../features/chat/background-tasks/useBackgroundTasks";
import { Button } from "./ui";
/** Characters shown when a finished task produced no output at all. */
@@ -18,71 +15,25 @@ const NO_OUTPUT = "—";
*/
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],
+ const { tasks, expandedId, output, stoppingIds, error, toggleOutput, stop } = useBackgroundTasks();
+ const outputText = useMemo(
+ () => formatOutput(output, expandedId ?? ""),
+ [output, expandedId],
);
-
- // 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;
+ if (tasks.length === 0 && !error) return null;
return (
<div
className="background-tasks-bar"
role="region"
aria-label={t("backgroundTasks.title")}
+ tabIndex={0}
>
+ {error ? (
+ <p className="background-task-error" role="alert">
+ {t(`backgroundTasks.${error}Failed`)}
+ </p>
+ ) : null}
{tasks.map((task) => {
const isRunning = task.state === "running";
const stopping = stoppingIds.has(task.id);
@@ -129,7 +80,7 @@ export function BackgroundTasksBar(): React.JSX.Element | null {
) : null}
{expandedId === task.id ? (
<pre className="background-task-output">
- {formatOutput(output, task.id) || NO_OUTPUT}
+ {outputText || NO_OUTPUT}
</pre>
) : null}
</div>
diff --git a/apps/desktop/src/features/chat/background-tasks/useBackgroundTasks.ts b/apps/desktop/src/features/chat/background-tasks/useBackgroundTasks.ts
new file mode 100644
index 000000000..6fd6f7b2f
--- /dev/null
+++ b/apps/desktop/src/features/chat/background-tasks/useBackgroundTasks.ts
@@ -0,0 +1,121 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+import { api, type BackgroundTaskOutput, type BackgroundTaskSummary } from "../../../lib/api";
+
+const REFRESH_MS = 1_000;
+type Failure = "load" | "output" | "stop";
+
+export function useBackgroundTasks() {
+ 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 [error, setError] = useState<Failure | null>(null);
+ const mounted = useRef(false);
+ const pendingStops = useRef(new Set<string>());
+ const refreshList = useRef<(() => void) | null>(null);
+
+ useEffect(() => {
+ mounted.current = true;
+ let disposed = false;
+ let inFlight = false;
+ let queued = false;
+ let pollAgain = true;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const refresh = async () => {
+ clearTimeout(timer);
+ if (inFlight) {
+ queued = true;
+ return;
+ }
+ inFlight = true;
+ try {
+ const result = await api.backgroundTasksList();
+ if (disposed) return;
+ setTasks(result.tasks);
+ setError((current) => current === "load" ? null : current);
+ pollAgain = result.tasks.some((task) => task.state === "running");
+ } catch (failure) {
+ if (disposed) return;
+ console.error("Background task list failed", failure);
+ setError("load");
+ pollAgain = true;
+ } finally {
+ inFlight = false;
+ if (!disposed) {
+ if (queued) {
+ queued = false;
+ void refresh();
+ } else if (pollAgain) {
+ timer = setTimeout(() => void refresh(), REFRESH_MS);
+ }
+ }
+ }
+ };
+ refreshList.current = () => void refresh();
+ const unsubscribe = api.onBackgroundTasksChanged(() => void refresh());
+ void refresh();
+ return () => {
+ disposed = true;
+ mounted.current = false;
+ refreshList.current = null;
+ clearTimeout(timer);
+ unsubscribe();
+ };
+ }, []);
+
+ const selectedState = tasks.find((task) => task.id === expandedId)?.state;
+ useEffect(() => {
+ setOutput(null);
+ if (!expandedId) return;
+ let disposed = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const refresh = async () => {
+ try {
+ const result = await api.backgroundTasksOutput(expandedId);
+ if (disposed) return;
+ setOutput(result);
+ setError((current) => current === "output" ? null : current);
+ } catch (failure) {
+ if (disposed) return;
+ console.error("Background task output failed", failure);
+ setError("output");
+ } finally {
+ // Only the selected log crosses IPC, with at most one read in flight.
+ if (!disposed && selectedState === "running") {
+ timer = setTimeout(() => void refresh(), REFRESH_MS);
+ }
+ }
+ };
+ void refresh();
+ return () => {
+ disposed = true;
+ clearTimeout(timer);
+ };
+ }, [expandedId, selectedState]);
+
+ const toggleOutput = useCallback((id: string) => {
+ setExpandedId((current) => current === id ? null : id);
+ setError((current) => current === "output" ? null : current);
+ }, []);
+
+ const stop = useCallback(async (id: string) => {
+ if (pendingStops.current.has(id)) return;
+ pendingStops.current.add(id);
+ setStoppingIds(new Set(pendingStops.current));
+ setError(null);
+ try {
+ await api.backgroundTasksStop(id);
+ if (mounted.current) refreshList.current?.();
+ } catch (failure) {
+ if (mounted.current) {
+ console.error("Background task stop failed", failure);
+ setError("stop");
+ }
+ } finally {
+ pendingStops.current.delete(id);
+ if (mounted.current) setStoppingIds(new Set(pendingStops.current));
+ }
+ }, []);
+
+ return { tasks, expandedId, output, stoppingIds, error, toggleOutput, stop };
+}
diff --git a/apps/desktop/src/styles/composer.css b/apps/desktop/src/styles/composer.css
index 0b46e5291..db0ff52c8 100644
--- a/apps/desktop/src/styles/composer.css
+++ b/apps/desktop/src/styles/composer.css
@@ -887,9 +887,14 @@
status block instead of a stack of input-like fields. */
.background-tasks-bar {
display: flex;
+ flex: 0 0 auto;
flex-direction: column;
+ max-height: min(200px, 24vh);
margin: 0 0 8px;
- overflow: hidden;
+ overflow-x: hidden;
+ overflow-y: auto;
+ overscroll-behavior: contain;
+ scrollbar-gutter: stable;
border: 1px solid var(--ds-border-subtle);
border-radius: var(--radius-md);
background: var(--ds-bg-dock-raised);
@@ -897,6 +902,7 @@
.background-task {
display: flex;
+ flex-shrink: 0;
flex-wrap: wrap;
align-items: center;
gap: 8px;
@@ -906,6 +912,13 @@
font-size: var(--text-sm);
}
+.background-task-error {
+ margin: 0;
+ padding: 6px 10px;
+ color: var(--ds-warning);
+ font-size: var(--text-sm);
+}
+
.background-task + .background-task {
border-top: 1px solid var(--ds-border-subtle);
}
diff --git a/apps/desktop/test/background-tasks.test.mjs b/apps/desktop/test/background-tasks.test.mjs
index c3bc54cc7..1653be781 100644
--- a/apps/desktop/test/background-tasks.test.mjs
+++ b/apps/desktop/test/background-tasks.test.mjs
@@ -30,6 +30,10 @@ const bar = await readFile(
new URL("../src/components/BackgroundTasksBar.tsx", import.meta.url),
"utf8",
);
+const controller = await readFile(
+ new URL("../src/features/chat/background-tasks/useBackgroundTasks.ts", 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),
@@ -86,8 +90,8 @@ test("the registry keeps output bounded and stops everything on shutdown", () =>
});
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(controller, /api\.backgroundTasksList\(\)/);
+ assert.match(controller, /api\.backgroundTasksStop\(id\)/);
assert.match(bar, /aria-label=\{t\("backgroundTasks\.title"\)\}/);
assert.match(composer, /import \{ BackgroundTasksBar \} from "\.\/BackgroundTasksBar";/);
assert.match(composer, /<BackgroundTasksBar \/>/);
diff --git a/apps/desktop/test/rpc-lifecycle-contract.test.mjs b/apps/desktop/test/rpc-lifecycle-contract.test.mjs
index a64e5ad14..8cb12dc4c 100644
--- a/apps/desktop/test/rpc-lifecycle-contract.test.mjs
+++ b/apps/desktop/test/rpc-lifecycle-contract.test.mjs
@@ -157,7 +157,9 @@ test("host disposal closes stdin, observes exit, and force-kills only after grac
test("Bash execution remains bounded while permission transport has no deadline", () => {
assert.match(runtimeSource, /DEFAULT_COMMAND_TIMEOUT_MS/);
assert.match(runtimeSource, /defaults to a 60-second timeout/);
- assert.match(runtimeSource, /timeoutMs,\n\s+}/);
+ // Bash may carry additive options after its timeout. Runtime tests exercise
+ // the default and override values at the tools.execute boundary.
+ assert.match(runtimeSource, /\btimeoutMs,/);
assert.doesNotMatch(rpcTimeoutSource, /DEFAULT_BASH_RPC_TIMEOUT_MS/);
// A tool relay carries its own budget; the transport must not cut it with the
// flat default. The same holds for the remote workspace counterpart.
diff --git a/crates/host-core/src/background_tasks.rs b/crates/host-core/src/background_tasks.rs
index 4e98acd50..020aa30b1 100644
--- a/crates/host-core/src/background_tasks.rs
+++ b/crates/host-core/src/background_tasks.rs
@@ -49,11 +49,13 @@ pub(crate) struct TaskShared {
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 {
+ if text.is_empty() {
+ return false;
+ }
ring.push_back(text.to_string());
*total += text.len();
let mut dropped = false;
@@ -88,6 +90,7 @@ pub struct BackgroundTask {
pub command_shell_id: String,
pub started_at: Instant,
pub shared: Arc<Mutex<TaskShared>>,
+ stop: watch::Sender<bool>,
}
#[derive(Serialize)]
@@ -268,8 +271,8 @@ fn register_spawned_task(
stdout_bytes: 0,
stderr_bytes: 0,
truncated: false,
- stop,
})),
+ stop,
};
registry.order.push(task.id.clone());
registry.tasks.insert(task.id.clone(), task.clone());
@@ -295,12 +298,31 @@ async fn supervise(
drop(chunk_tx);
let mut wait = runner.wait_task;
- let exit = loop {
+ let mut exit = None;
+ let mut output_closed = false;
+ let mut stopping = false;
+ let mut lifecycle_failed = false;
+ let mut stdout_decoder = tools::Utf8Decoder::default();
+ let mut stderr_decoder = tools::Utf8Decoder::default();
+ // Reaping the process and draining its output are separate completion
+ // conditions. Keep receiving after exit/stop so a full channel cannot
+ // deadlock the readers, and disable recv after EOF to avoid a busy loop.
+ while exit.is_none() || !output_closed {
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', "");
+ waited = &mut wait, if exit.is_none() => {
+ exit = Some(waited);
+ if let Err(error) = runner.ownership.terminate_fail_closed(runner.pid) {
+ tracing::error!(task_id = %task.id, %error, "background task exit cleanup failed");
+ lifecycle_failed = true;
+ }
+ }
+ chunk = chunk_rx.recv(), if !output_closed => {
+ let Some((is_stdout, bytes)) = chunk else {
+ output_closed = true;
+ continue;
+ };
+ let decoder = if is_stdout { &mut stdout_decoder } else { &mut stderr_decoder };
+ let text = decoder.push(&bytes).replace('\r', "");
let mut shared = task.shared.lock().await;
let dropped = if is_stdout {
shared.push_stdout(&text)
@@ -311,34 +333,47 @@ async fn supervise(
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);
+ changed = stop_rx.changed(), if !stopping => {
+ if changed.is_err() || *stop_rx.borrow() {
+ stopping = true;
+ if let Err(error) = runner.ownership.terminate_fail_closed(runner.pid) {
+ tracing::error!(task_id = %task.id, %error, "background task stop failed");
+ lifecycle_failed = true;
+ }
}
}
}
+ }
+ for reader in [stdout_reader, stderr_reader] {
+ match reader.await {
+ Ok(Ok(())) => {}
+ result => {
+ tracing::error!(task_id = %task.id, ?result, "background task output reader failed");
+ lifecycle_failed = true;
+ }
+ }
+ }
+ let exit_code = match exit {
+ Some(Ok(Ok(status))) => status.code(),
+ result => {
+ tracing::error!(task_id = %task.id, ?result, "background task wait failed");
+ lifecycle_failed = true;
+ None
+ }
};
- // 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 state = match (exit_code, stopped, lifecycle_failed) {
+ (_, _, true) => BackgroundTaskState::Failed,
+ (_, true, false) => BackgroundTaskState::Stopped,
+ (Some(0), false, false) => BackgroundTaskState::Exited,
+ _ => BackgroundTaskState::Failed,
};
{
let mut shared = task.shared.lock().await;
+ let stdout_dropped = shared.push_stdout(&stdout_decoder.finish());
+ let stderr_dropped = shared.push_stderr(&stderr_decoder.finish());
+ shared.truncated |= stdout_dropped || stderr_dropped;
shared.state = state;
shared.exit_code = exit_code;
}
@@ -349,21 +384,23 @@ async fn drain_pipe<R>(
pipe: Option<R>,
is_stdout: bool,
tx: tokio::sync::mpsc::Sender<(bool, Vec<u8>)>,
-) where
+) -> std::io::Result<()>
+where
R: tokio::io::AsyncRead + Unpin,
{
- let Some(mut pipe) = pipe else { return };
+ let Some(mut pipe) = pipe else { return Ok(()) };
let mut buffer = [0u8; 8192];
loop {
- match pipe.read(&mut buffer).await {
- Ok(0) | Err(_) => break,
- Ok(read) => {
+ match pipe.read(&mut buffer).await? {
+ 0 => break,
+ read => {
if tx.send((is_stdout, buffer[..read].to_vec())).await.is_err() {
break;
}
}
}
}
+ Ok(())
}
/// Registry operations that read or signal a task. Output reads and state
@@ -375,10 +412,10 @@ pub async fn stop_task(registry: &BackgroundTaskRegistry, id: &str) -> Result<bo
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() {
+ if shared.state != BackgroundTaskState::Running || *task.stop.borrow() {
return Ok(false);
}
- let _ = shared.stop.send(true);
+ let _ = task.stop.send(true);
Ok(true)
}
@@ -405,9 +442,7 @@ pub async fn task_output(
/// 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);
- }
+ let _ = task.stop.send(true);
}
}
@@ -438,6 +473,79 @@ mod tests {
use super::*;
use std::time::Duration;
+ #[tokio::test]
+ async fn retains_output_when_the_process_exits_before_supervision_starts() {
+ let dir = tempfile::tempdir().unwrap();
+ let shell = crate::tools::shell::default_shell_id();
+ let command = if cfg!(windows) {
+ "[Console]::Out.Write('final-stdout'); [Console]::Error.Write('final-stderr')"
+ } else {
+ "printf final-stdout; printf final-stderr >&2"
+ };
+ let config = resolve_runner_config(shell, command, dir.path(), None).unwrap();
+ let runner = tools::spawn_tool_runner(&config).await.unwrap();
+ tokio::time::timeout(Duration::from_secs(10), async {
+ while !runner.wait_task.is_finished() {
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .unwrap();
+ let mut registry = BackgroundTaskRegistry::default();
+ let changed = Arc::new(tokio::sync::Notify::new());
+ let notify = changed.clone();
+ let task = register_spawned_task(
+ &mut registry,
+ "session-output",
+ command,
+ shell,
+ runner,
+ Arc::new(move || notify.notify_one()),
+ );
+ tokio::time::timeout(Duration::from_secs(5), changed.notified())
+ .await
+ .expect("the process must settle after draining both pipes");
+ let output = task_output(&registry, &task.id).await.unwrap().unwrap();
+ assert_eq!(output["state"], "exited");
+ assert_eq!(output["stdout"], "final-stdout");
+ assert_eq!(output["stderr"], "final-stderr");
+ }
+
+ #[tokio::test]
+ async fn shutdown_signals_a_task_while_its_output_is_locked() {
+ let dir = tempfile::tempdir().unwrap();
+ let shell = crate::tools::shell::default_shell_id();
+ let config = resolve_runner_config(shell, "sleep 30", dir.path(), None).unwrap();
+ let runner = tools::spawn_tool_runner(&config).await.unwrap();
+ let mut registry = BackgroundTaskRegistry::default();
+ let changed = Arc::new(tokio::sync::Notify::new());
+ let notify = changed.clone();
+ let task = register_spawned_task(
+ &mut registry,
+ "session-output",
+ "sleep 30",
+ shell,
+ runner,
+ Arc::new(move || notify.notify_one()),
+ );
+ let output_lock = task.shared.lock().await;
+ stop_all_running_sync(&registry);
+ drop(output_lock);
+ let settled = tokio::time::timeout(Duration::from_secs(3), changed.notified()).await;
+ if settled.is_err() {
+ // Clean up the real child even when the regression is present.
+ stop_task(&registry, &task.id).await.unwrap();
+ tokio::time::timeout(Duration::from_secs(5), changed.notified())
+ .await
+ .unwrap();
+ }
+ assert!(
+ settled.is_ok(),
+ "shutdown must not skip a contended output lock"
+ );
+ assert_eq!(registry.summaries()[0].state, BackgroundTaskState::Stopped);
+ }
+
/// 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 —
diff --git a/crates/host-core/src/tools/mod.rs b/crates/host-core/src/tools/mod.rs
index fe05c1f34..aba38a35a 100644
--- a/crates/host-core/src/tools/mod.rs
+++ b/crates/host-core/src/tools/mod.rs
@@ -2252,12 +2252,12 @@ struct OutputChunk {
}
#[derive(Debug, Default)]
-struct Utf8Decoder {
+pub(crate) struct Utf8Decoder {
pending: Vec<u8>,
}
impl Utf8Decoder {
- fn push(&mut self, bytes: &[u8]) -> String {
+ pub(crate) fn push(&mut self, bytes: &[u8]) -> String {
self.pending.extend_from_slice(bytes);
let mut output = String::new();
loop {
@@ -2291,7 +2291,7 @@ impl Utf8Decoder {
output
}
- fn finish(&mut self) -> String {
+ pub(crate) fn finish(&mut self) -> String {
if self.pending.is_empty() {
return String::new();
}
diff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.md
index 3774fb3d5..9e2bb7ec4 100644
--- a/docs/spec/03-runtime/03-tools-and-permissions.md
+++ b/docs/spec/03-runtime/03-tools-and-permissions.md
@@ -430,6 +430,18 @@ Host execution baseline:
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.
+- Background output is drained before a terminal state is published, including
+ output queued when the process exits or is stopped. UTF-8 characters split
+ across pipe reads remain intact. Shutdown signals do not acquire output locks.
+- The task list keeps the existing Composer order: Todo, background commands,
+ Plan/Ask decisions, then the input. There is no configurable display priority.
+ The list scrolls within `min(200px, 24vh)` so additional tasks do not displace
+ the decision surfaces. Existing approval and Ask input gating is unchanged.
+- Only one output preview is open at a time. While its task runs, the Renderer
+ refreshes that preview at one-second intervals after the previous read settles;
+ collapsed outputs are not fetched. The preview shows at most 8,000 stdout
+ characters and 4,000 stderr characters. Late reads from a previous selection
+ are ignored. Read/stop failures are visible and stopping can be retried.
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 30df9c2c6..e03cfbd78 100644
--- a/docs/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md
@@ -679,6 +679,11 @@ 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.
+Output chunks do not emit `backgroundTasks.changed`; the event remains a
+lifecycle invalidation, not a high-volume log transport. Clients fetch only the
+selected output preview. A terminal snapshot includes the final drained output,
+and shutdown signals every registered task even during a concurrent output read.
+
### 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 7389af259..9ba0ac466 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -7754,20 +7754,33 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
`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.
+ 5) Start ten tasks with 100,000 lines of 100 characters on both streams,
+ then inspect their final output. 6) Show Todo and Ask alongside the task list
+ at wide and narrow widths, scroll to the tenth task, and switch output previews
+ while an earlier read is pending. 7) Fail a Stop request and retry it.
+ 8) Start two more tasks and quit the app during output capture.
- **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.
+ app leaves no orphan process behind. The ten-task list scrolls within its
+ height cap without displacing Todo, Ask, or input. Only the selected log is
+ fetched and refreshed; old responses cannot erase it. Each stream remains
+ bounded to 256KiB and retains its final marker after exit. A Stop failure is
+ visible without an unhandled rejection and the control remains retryable.
- **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)
+ renderer contract test `apps/desktop/test/background-tasks.test.mjs`;
+ `node scripts/e2e-background-tasks-host.mjs` runs the real Host/process/pipe
+ stress path without providers, and `node scripts/e2e-background-tasks.mjs`
+ exercises production React components in isolated Electron at 1280px, 700px,
+ and 390px widths. Host tests cover exit-before-drain and shutdown under output
+ lock contention. The full agent-to-Desktop journey and an 83-minute paced
+ 100,000-line soak remain manual; the automated volume test is accelerated.)
#### E2E-117: Agent/Plan/Goal UX and locales contain no Chat controls
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 4564a21be..adaac2331 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
@@ -388,7 +388,15 @@ tool/protocol 名称,请求中单独携带固定的 shell ID。
- `runInBackground: true` 让命令脱离本轮:shell 一启动就返回 `backgroundTaskId`,
不再套用超时,进程也不会被 `tools.abort` / `agent.abort` 终止。进程树归宿主
所有,通过输入框上方的运行中任务栏展示,可由用户停止或随应用退出而结束。
- 最多同时运行 32 个任务,每个输出流保留最后 256KB。
+ 最多同时运行 32 个任务,每个输出流保留最后 256KB。
+- 后台任务先排空输出,再发布最终状态,保留跨管道读取边界的 UTF-8 字符;
+ 退出和停止时已排队的输出不会丢失。关闭宿主时发送停止信号不依赖输出锁。
+- 输入框上方保持 Todo、后台命令、Plan/Ask 决策、输入框的既有顺序,没有可配置的
+ 显示优先级。任务列表在 `min(200px, 24vh)` 内滚动,不随任务数量无限增高;
+ 审批和 Ask 对输入的既有约束不变。
+- 同时只展开一个输出预览;任务运行时,上次读取完成后每秒刷新一次,折叠的日志
+ 不读取。预览最多展示 stdout 的 8,000 字符和 stderr 的 4,000 字符,忽略切换前
+ 的过期响应。读取或停止失败会显示错误,停止操作可以重试。
初始拒绝名单(可扩展):
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 804eed599..b47139846 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
@@ -464,6 +464,10 @@ off | minimal | low | medium | high | xhigh | max
取消表,因此 `tools.abort` / `agent.abort` 都无法触及它,输出按流保存在有界环形缓冲
中。注册表位于宿主进程内,宿主关闭时会停止全部任务,因此应用退出不会残留孤儿进程。
+输出块不会触发 `backgroundTasks.changed`;该事件仍用于生命周期状态失效通知,
+不承担高频日志传输。客户端只读取当前展开的输出。最终状态包含排空后的尾部输出,
+即使并发读取占用输出锁,关闭宿主仍会向每个任务发送停止信号。
+
### 贝壳
- `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 ab7fff660..093af946c 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
@@ -4532,16 +4532,27 @@ eleven-tool-round desktop paths are verified by
- **前置条件**:项目会话,其目录 shell 支持后台执行;测试服务可绑定的端口。
- **步骤**:1) 让 agent 用 `runInBackground` 启动长驻进程(本地 Web 服务),观察
输入框上方的运行中任务栏。2) 中止本轮,在同一会话发送第二条提示,然后重新加载
- 渲染进程。3) 展开该行的“输出”。4) 点击“停止”。5) 再启动两个任务后退出应用。
+ 渲染进程。3) 展开该行的“输出”。4) 点击“停止”。5) 启动十个任务,每个流
+ 输出十万行、每行一百字符,检查最终输出。6) 在宽窄窗口同时展示 Todo、Ask 和
+ 任务列表,滚动到第十个任务,在旧读取未完成时切换日志。7) 模拟停止失败后重试。
+ 8) 再启动两个任务,在输出读取期间退出应用。
- **预期**:工具结果携带 `backgroundTaskId` 且不等待命令结束;任务栏显示运行中的
任务与递增的耗时,并展示流式输出;进程在中止后、Bash 60 秒超时后、渲染进程重载后
- 仍然存活。“停止”把该行落定为“已停止”并杀掉整个进程树;退出应用后不残留孤儿进程。
+ 仍然存活。“停止”把该行落定为“已停止”并杀掉整个进程树;退出应用后不残留孤儿进程。
+ 十任务列表在限高区域内滚动,不挤占 Todo、Ask 和输入框;仅刷新当前展开的日志,
+ 过期响应不能清空新预览。每个流保持 256KiB 上限并保留最终标记。停止失败可见、
+ 无未处理的 Promise 拒绝,且可以重试。
- **关联规范**:`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`;任务栏交互本身仍为人工验证)
+ `apps/desktop/test/background-tasks.test.mjs`;运行
+ `node scripts/e2e-background-tasks-host.mjs` 验证真实宿主、进程和管道压力路径,
+ `node scripts/e2e-background-tasks.mjs` 在隔离 Electron 中以 1280px、700px、
+ 390px 宽度验证生产 React 组件。宿主回归测试覆盖退出前输出排空和输出锁竞争时关闭。
+ 完整 agent 到桌面流程及约 83 分钟的十万行定速长测仍为人工场景;
+ 自动化的大输出测试采用加速模式。)
#### E2E-117:Agent/Plan/Goal UX 和区域设置不包含聊天控件
diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.ts
index 8b700a01d..7e252daa9 100644
--- a/packages/agent-runtime/src/runtime.test.ts
+++ b/packages/agent-runtime/src/runtime.test.ts
@@ -1527,6 +1527,34 @@ describe("DesktopAgentRuntime configuration matching", () => {
await runtime.dispose();
});
+ it("opts into background Bash without changing foreground timeout forwarding", async () => {
+ const host = { call: vi.fn().mockResolvedValue({ ok: true, content: "done" }) };
+ const runtime = createRuntime({ host });
+ const agent = Reflect.get(runtime, "agent") as Agent;
+ const bash = agent.state.tools.find((tool) => tool.name === "Bash");
+ if (!bash) throw new Error("Bash tool is missing");
+ try {
+ await bash.execute("background", { command: "npm run dev", runInBackground: true });
+ expect(host.call).toHaveBeenLastCalledWith("tools.execute", expect.objectContaining({
+ toolName: "Bash",
+ timeoutMs: 60_000,
+ runInBackground: true,
+ args: { command: "npm run dev", runInBackground: true },
+ }));
+ for (const args of [
+ { command: "printf foreground" },
+ { command: "printf foreground", runInBackground: false },
+ ]) {
+ await bash.execute("foreground", args);
+ const request = host.call.mock.calls.at(-1)?.[1];
+ expect(request).toMatchObject({ toolName: "Bash", timeoutMs: 60_000 });
+ expect(request).not.toHaveProperty("runInBackground");
+ }
+ } finally {
+ await runtime.dispose();
+ }
+ });
+
it("reads a millisecond Bash timeout as seconds and clamps it to the ceiling", async () => {
const host = {
call: vi.fn().mockResolvedValue({ ok: true, content: "done" }),
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index 0c9e398af..2aabf4a5e 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -668,6 +668,9 @@ export const de = {
failed: "Fehlgeschlagen",
stopped: "Gestoppt",
title: "Hintergrundbefehle",
+ loadFailed: "Hintergrundbefehle konnten nicht aktualisiert werden. Erneuter Versuch...",
+ outputFailed: "Die Ausgabe dieses Befehls konnte nicht gelesen werden.",
+ stopFailed: "Dieser Befehl konnte nicht gestoppt werden. Erneut versuchen.",
output: "Ausgabe",
stop: "Stoppen",
stopping: "Stoppe…",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index 1069665ff..3f86819e0 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -680,6 +680,9 @@ export const en = {
failed: "Failed",
stopped: "Stopped",
title: "Background commands",
+ loadFailed: "Could not refresh background commands. Retrying...",
+ outputFailed: "Could not read this command's output.",
+ stopFailed: "Could not stop this command. Try again.",
output: "Output",
stop: "Stop",
stopping: "Stopping…",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index 9ff749c6b..216262833 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -668,6 +668,9 @@ export const es = {
failed: "Fallido",
stopped: "Detenido",
title: "Comandos en segundo plano",
+ loadFailed: "No se pudieron actualizar los comandos en segundo plano. Reintentando...",
+ outputFailed: "No se pudo leer la salida de este comando.",
+ stopFailed: "No se pudo detener este comando. Inténtalo de nuevo.",
output: "Salida",
stop: "Detener",
stopping: "Deteniendo…",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index 96f10ef4f..7b8e36a72 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -668,6 +668,9 @@ export const fr = {
failed: "Échec",
stopped: "Arrêté",
title: "Commandes en arrière-plan",
+ loadFailed: "Impossible d'actualiser les commandes en arrière-plan. Nouvelle tentative...",
+ outputFailed: "Impossible de lire la sortie de cette commande.",
+ stopFailed: "Impossible d'arrêter cette commande. Réessayez.",
output: "Sortie",
stop: "Arrêter",
stopping: "Arrêt…",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index 441f8d2f8..9aab673a2 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -677,6 +677,9 @@ export const ko = {
failed: "실패",
stopped: "중지됨",
title: "백그라운드 명령",
+ loadFailed: "백그라운드 명령을 새로 고칠 수 없습니다. 다시 시도 중...",
+ outputFailed: "이 명령의 출력을 읽을 수 없습니다.",
+ stopFailed: "이 명령을 중지할 수 없습니다. 다시 시도하세요.",
output: "출력",
stop: "중지",
stopping: "중지 중…",
diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.ts
index 63dadb787..5da88d388 100644
--- a/packages/i18n/src/locales/pt-BR/index.ts
+++ b/packages/i18n/src/locales/pt-BR/index.ts
@@ -667,6 +667,9 @@ export const ptBR = {
failed: "Falhou",
stopped: "Parado",
title: "Comandos em segundo plano",
+ loadFailed: "Não foi possível atualizar os comandos em segundo plano. Tentando novamente...",
+ outputFailed: "Não foi possível ler a saída deste comando.",
+ stopFailed: "Não foi possível parar este comando. Tente novamente.",
output: "Saída",
stop: "Parar",
stopping: "Parando…",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index 643498294..fcfe38e58 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -677,6 +677,9 @@ export const tr = {
failed: "Başarısız",
stopped: "Durduruldu",
title: "Arka plan komutları",
+ loadFailed: "Arka plan komutları yenilenemedi. Yeniden deneniyor...",
+ outputFailed: "Bu komutun çıktısı okunamadı.",
+ stopFailed: "Bu komut durdurulamadı. Yeniden deneyin.",
output: "Çıktı",
stop: "Durdur",
stopping: "Durduruluyor…",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index 3eae9f35d..b70b244b3 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -673,6 +673,9 @@ export const zhCN = {
failed: "失败",
stopped: "已停止",
title: "后台命令",
+ loadFailed: "无法刷新后台命令,正在重试...",
+ outputFailed: "无法读取此命令的输出。",
+ stopFailed: "无法停止此命令,请重试。",
output: "输出",
stop: "停止",
stopping: "停止中…",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index d36b5cf91..9d9464e8c 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -673,6 +673,9 @@ export const zhTW = {
failed: "失敗",
stopped: "已停止",
title: "背景命令",
+ loadFailed: "無法重新整理背景命令,正在重試...",
+ outputFailed: "無法讀取此命令的輸出。",
+ stopFailed: "無法停止此命令,請重試。",
output: "輸出",
stop: "停止",
stopping: "停止中…",
diff --git a/scripts/e2e-background-tasks-host.mjs b/scripts/e2e-background-tasks-host.mjs
new file mode 100644
index 000000000..a6df45b7f
--- /dev/null
+++ b/scripts/e2e-background-tasks-host.mjs
@@ -0,0 +1,117 @@
+#!/usr/bin/env node
+import assert from "node:assert/strict";
+import { access, copyFile, mkdir, mkdtemp, writeFile } from "node:fs/promises";
+import { delimiter, dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { setImmediate } from "node:timers/promises";
+import { Host, resolveHostBinary } from "./e2e/host.mjs";
+import { beginTurn, configureSession, createSession, endTurn } from "./e2e/session.mjs";
+
+const root = fileURLToPath(new URL("..", import.meta.url));
+const artifacts = join(root, ".cache", "background-tasks-host-e2e");
+await mkdir(artifacts, { recursive: true });
+const scratch = await mkdtemp(join(artifacts, "run-"));
+const workspace = join(scratch, "workspace");
+await mkdir(workspace);
+await copyFile(join(root, "scripts/e2e/background-task-output.mjs"), join(workspace, "output.mjs"));
+const host = new Host(resolveHostBinary(), join(scratch, "data"), {
+ quiet: true,
+ env: { PATH: [dirname(process.execPath), process.env.PATH].filter(Boolean).join(delimiter) },
+});
+const rpcDurations = [];
+const timedCall = async (method, params = {}) => {
+ const start = performance.now();
+ const result = await host.call(method, params);
+ rpcDurations.push(performance.now() - start);
+ return result;
+};
+const until = async (check, message) => {
+ const deadline = performance.now() + 30_000;
+ while (!(await check())) {
+ assert(performance.now() < deadline, message);
+ await setImmediate();
+ }
+};
+try {
+ await host.start();
+ const session = await createSession(host, workspace, "Background output stress");
+ await configureSession(host, session, "agent", "auto");
+ // PowerShell converts a native child's stderr into ErrorRecords. Use the
+ // catalog's cmd entry for raw two-stream throughput on Windows.
+ if (process.platform === "win32") {
+ await host.call("settings.set", { defaultCommandShell: "cmd" });
+ }
+ const turnId = await beginTurn(host, session.id);
+ const { effective: shell } = await host.call("commandShells.list");
+ assert(shell && ["cmd", "posix"].includes(shell.dialect), "fixture needs cmd or a POSIX shell");
+ const ids = await Promise.all(Array.from({ length: 10 }, async (_, index) => {
+ const command = `node output.mjs . ${index}`;
+ const result = await host.call("tools.execute", {
+ sessionId: session.id, turnId, toolCallId: `stress-${index}`,
+ toolName: "Bash", args: { command, runInBackground: true },
+ mode: "agent", runInBackground: true, timeoutMs: 1_000,
+ expectedCommandShellId: shell.id, expectedCommandShellDialect: shell.dialect,
+ });
+ assert(result.ok && result.content.backgroundTaskId, JSON.stringify(result));
+ return result.content.backgroundTaskId;
+ }));
+ await until(async () => {
+ const { tasks } = await host.call("backgroundTasks.list");
+ const failed = tasks.find((task) => task.state === "failed");
+ if (failed) {
+ const output = await host.call("backgroundTasks.output", { id: failed.id });
+ throw new Error(`Fixture failed to start: ${output.stderr.slice(-2_000)}`);
+ }
+ const ready = await Promise.all(ids.map((_, index) => access(join(workspace, `${index}.ready`)).then(() => true, () => false)));
+ return ready.every(Boolean);
+ }, "all ten commands must start");
+ await Promise.all(ids.map((_, index) =>
+ host.call("tools.abort", { sessionId: session.id, toolCallId: `stress-${index}` }),
+ ));
+ await endTurn(host, turnId, "aborted");
+ let summaries = (await timedCall("backgroundTasks.list")).tasks;
+ assert.equal(summaries.filter((task) => task.state === "running").length, 10, "turn abort must preserve running background tasks");
+ await writeFile(join(workspace, "release"), "");
+ let polls = 0;
+ await until(async () => {
+ summaries = (await timedCall("backgroundTasks.list")).tasks;
+ const output = await timedCall("backgroundTasks.output", { id: ids[polls++ % ids.length] });
+ assert(Buffer.byteLength(output.stdout) <= 256 * 1024);
+ assert(Buffer.byteLength(output.stderr) <= 256 * 1024);
+ return summaries.every((task) => task.state !== "running");
+ }, "large output commands must drain and settle");
+ for (const [index, id] of ids.entries()) {
+ const output = await timedCall("backgroundTasks.output", { id });
+ assert.equal(output.state, "exited", JSON.stringify({
+ index, state: output.state, exitCode: output.exitCode,
+ stdoutTail: output.stdout.slice(-500), stderrTail: output.stderr.slice(-2_000),
+ hostErrors: host.stderr.slice(-2_000),
+ }));
+ assert.equal(output.exitCode, 0);
+ assert.equal(output.truncated, true);
+ assert(output.stdout.endsWith(`stdout-done-${index}\n`), "final stdout must not be lost");
+ assert(output.stderr.endsWith(`stderr-done-${index}\n`), "final stderr must not be lost");
+ assert(Buffer.byteLength(output.stdout) <= 256 * 1024);
+ assert(Buffer.byteLength(output.stderr) <= 256 * 1024);
+ }
+ rpcDurations.sort((a, b) => a - b);
+ const result = {
+ tasks: 10, shell: shell.id, linesPerTaskPerStream: 100_000, bytesProduced: 202_000_000,
+ maxRetainedBytesPerStream: 256 * 1024, polls,
+ rpcP95Ms: Number(rpcDurations[Math.floor(rpcDurations.length * 0.95)].toFixed(2)),
+ rpcMaxMs: Number(rpcDurations.at(-1).toFixed(2)),
+ turnAbortSurvived: true, finalOutputRetained: true,
+ };
+ await writeFile(join(scratch, "result.json"), JSON.stringify(result, null, 2));
+ console.log(JSON.stringify(result, null, 2));
+} finally {
+ // EOF exercises graceful host shutdown; no user profile or running app is used.
+ host.child?.stdin.end();
+ if (host.child && !host.exited) {
+ await Promise.race([host.exitPromise, new Promise((resolve) => {
+ const timer = setTimeout(resolve, 3_000);
+ timer.unref();
+ })]);
+ }
+ await host.stop();
+}
diff --git a/scripts/e2e-background-tasks.mjs b/scripts/e2e-background-tasks.mjs
new file mode 100644
index 000000000..3a350dac4
--- /dev/null
+++ b/scripts/e2e-background-tasks.mjs
@@ -0,0 +1,105 @@
+#!/usr/bin/env node
+import assert from "node:assert/strict";
+import { execFileSync, spawn } from "node:child_process";
+import { createRequire } from "node:module";
+import { mkdir, readFile, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { resolveElectronBinary } from "./e2e/boot.mjs";
+
+const root = fileURLToPath(new URL("..", import.meta.url));
+const require = createRequire(join(root, "packages/agent-runtime/package.json"));
+const { build } = require("esbuild");
+const baselineIndex = process.argv.indexOf("--baseline");
+const baseline = baselineIndex >= 0 ? process.argv[baselineIndex + 1] : undefined;
+assert(baselineIndex < 0 || (baseline && !baseline.startsWith("-")), "--baseline requires a Git revision");
+const artifacts = join(root, ".cache", `background-tasks-e2e${baseline ? "-baseline" : ""}`);
+const original = (path) => execFileSync("git", ["show", `${baseline}:${path}`], { cwd: root, encoding: "utf8" });
+await mkdir(artifacts, { recursive: true });
+await build({
+ entryPoints: [join(root, "scripts/e2e/background-tasks.tsx")],
+ outfile: join(artifacts, "renderer.js"),
+ bundle: true, platform: "browser", format: "iife", jsx: "automatic",
+ define: { "process.env.NODE_ENV": '"production"', "import.meta.env.DEV": "false" },
+ loader: { ".css": "empty" },
+ alias: {
+ "@pi-desktop/i18n": join(root, "packages/i18n/src/index.ts"),
+ react: join(root, "apps/desktop/node_modules/react"),
+ "react-dom": join(root, "apps/desktop/node_modules/react-dom"),
+ },
+ nodePaths: [join(root, "apps/desktop/node_modules")],
+ plugins: baseline ? [{
+ name: "baseline-background-tasks",
+ setup(build) {
+ build.onLoad({ filter: /[\\/]BackgroundTasksBar\.tsx$/ }, () => ({
+ contents: original("apps/desktop/src/components/BackgroundTasksBar.tsx"),
+ loader: "tsx",
+ resolveDir: join(root, "apps/desktop/src/components"),
+ }));
+ },
+ }] : [],
+});
+let styles;
+if (baseline) {
+ styles = ["tokens.css", "globals.css", "ui-kit.css", "composer.css", "messages.css", "overlays.css"]
+ .map((name) => original(`apps/desktop/src/styles/${name}`));
+} else {
+ const renderer = join(root, "apps/desktop/out/renderer");
+ const html = await readFile(join(renderer, "index.html"), "utf8");
+ const paths = [...html.matchAll(/href="([^"]+\.css)"/g)].map((match) => match[1]);
+ assert(paths.length, "Build the Desktop stylesheet before running the renderer probe");
+ styles = await Promise.all(paths.map((path) => readFile(join(renderer, path), "utf8")));
+}
+await writeFile(join(artifacts, "styles.css"), styles.join("\n"));
+await writeFile(join(artifacts, "index.html"), `<!doctype html>
+<html><head><meta charset="utf-8">
+<meta http-equiv="Content-Security-Policy" content="default-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self' data:">
+<link rel="stylesheet" href="styles.css">
+<style>body { margin: 0; } textarea { display: block; width: 100%; min-height: 60px; box-sizing: border-box; }</style>
+</head><body><script src="renderer.js"></script></body></html>`);
+await writeFile(join(artifacts, "main.cjs"), `
+const { app, BrowserWindow } = require("electron");
+const { join } = require("node:path");
+const { writeFile } = require("node:fs/promises");
+app.setPath("userData", join(__dirname, "profile"));
+app.disableHardwareAcceleration();
+app.on("window-all-closed", () => {});
+app.whenReady().then(async () => {
+ const results = [];
+ for (const [width, height] of [[1280, 800], [700, 800], [390, 844]]) {
+ const window = new BrowserWindow({ show: false, width, height, useContentSize: true,
+ webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false } });
+ window.webContents.on("console-message", event => console.error(event.message));
+ try {
+ await window.loadFile(join(__dirname, "index.html"));
+ const result = await window.webContents.executeJavaScript("globalThis.backgroundTasksProbe()");
+ results.push(result);
+ await writeFile(join(__dirname, "tasks-" + width + ".png"), (await window.webContents.capturePage()).toPNG());
+ } finally { window.destroy(); }
+ }
+ console.log("BACKGROUND_TASKS_PROBE " + JSON.stringify(results));
+ app.exit(results.every(result => result.ok) ? 0 : 1);
+}).catch(error => { console.error(error); app.exit(1); });
+`);
+const env = { ...process.env };
+delete env.ELECTRON_RUN_AS_NODE;
+const { electronBinary } = resolveElectronBinary(root);
+const child = spawn(electronBinary, [join(artifacts, "main.cjs")], {
+ env, windowsHide: true, stdio: ["ignore", "pipe", "pipe"],
+});
+let output = "";
+for (const stream of [child.stdout, child.stderr]) stream.on("data", (chunk) => { output += chunk; });
+const timer = setTimeout(() => child.kill("SIGKILL"), 90_000);
+let code;
+try {
+ code = await new Promise((resolve, reject) => {
+ child.once("error", reject);
+ child.once("close", resolve);
+ });
+} finally { clearTimeout(timer); }
+const line = output.split(/\r?\n/).find((line) => line.startsWith("BACKGROUND_TASKS_PROBE "));
+assert(line, `renderer probe did not finish (exit ${code}): ${output.slice(-6000)}`);
+const results = JSON.parse(line.slice("BACKGROUND_TASKS_PROBE ".length));
+await writeFile(join(artifacts, "results.json"), JSON.stringify(results, null, 2));
+console.log(JSON.stringify(results, null, 2));
+assert.equal(code, 0, `background task interaction failed; artifacts: ${artifacts}`);
diff --git a/scripts/e2e/background-task-output.mjs b/scripts/e2e/background-task-output.mjs
new file mode 100644
index 000000000..44efea8bc
--- /dev/null
+++ b/scripts/e2e/background-task-output.mjs
@@ -0,0 +1,22 @@
+import { once } from "node:events";
+import { writeFile, access } from "node:fs/promises";
+import { join } from "node:path";
+import { setTimeout } from "node:timers/promises";
+
+const [directory, id] = process.argv.slice(2);
+await writeFile(join(directory, `${id}.ready`), "");
+while (true) {
+ try { await access(join(directory, "release")); break; }
+ catch (error) {
+ if (error.code !== "ENOENT") throw error;
+ await setTimeout(20);
+ }
+}
+const chunk = `${"*".repeat(100)}\n`.repeat(1_000);
+for (let batch = 0; batch < 100; batch++) {
+ for (const stream of [process.stdout, process.stderr]) {
+ if (!stream.write(chunk)) await once(stream, "drain");
+ }
+}
+process.stdout.write(`stdout-done-${id}\n`);
+process.stderr.write(`stderr-done-${id}\n`);
diff --git a/scripts/e2e/background-tasks.tsx b/scripts/e2e/background-tasks.tsx
new file mode 100644
index 000000000..fe321f478
--- /dev/null
+++ b/scripts/e2e/background-tasks.tsx
@@ -0,0 +1,239 @@
+import { createRoot, type Root } from "react-dom/client";
+import { flushSync } from "react-dom";
+import i18n from "i18next";
+import { I18nextProvider } from "react-i18next";
+import { en } from "@pi-desktop/i18n";
+import { IPC } from "@pi-desktop/shared";
+import { BackgroundTasksBar } from "../../apps/desktop/src/components/BackgroundTasksBar";
+import { TodoDock } from "../../apps/desktop/src/components/TodoDock";
+import { AskToolCard } from "../../apps/desktop/src/components/AskToolCard";
+import { useAppStore } from "../../apps/desktop/src/stores/app-store";
+import type { BackgroundTaskOutput, BackgroundTaskSummary } from "../../apps/desktop/src/lib/api";
+
+const listeners = new Set<() => void>();
+const requests: string[] = [];
+const pending = new Map<string, (value: BackgroundTaskOutput) => void>();
+let tasks: BackgroundTaskSummary[] = [];
+let revision = 0;
+let deferOutput = false;
+let rejectStop = false;
+let root: Root | undefined;
+
+function assert(value: unknown, label: string): asserts value {
+ if (!value) throw new Error(label);
+}
+
+const frame = () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
+async function until(predicate: () => boolean, label: string) {
+ const deadline = performance.now() + 5_000;
+ while (!predicate()) {
+ assert(performance.now() < deadline, label);
+ await frame();
+ }
+}
+
+function output(id: string): BackgroundTaskOutput {
+ return {
+ id, state: "running", truncated: true,
+ stdout: `${"*".repeat(256 * 1024 - 100)}\n${id}: output revision ${revision}`,
+ stderr: "*".repeat(256 * 1024),
+ };
+}
+
+Object.defineProperty(window, "piDesktop", {
+ value: {
+ invoke: async (channel: string, payload?: { id: string }) => {
+ const call = async () => {
+ if (channel === IPC.invoke.backgroundTasksList) return { tasks: [...tasks], version: revision };
+ if (channel === IPC.invoke.backgroundTasksOutput) {
+ const id = payload!.id;
+ requests.push(id);
+ if (deferOutput) return new Promise<BackgroundTaskOutput>((resolve) => pending.set(id, resolve));
+ return output(id);
+ }
+ if (channel === IPC.invoke.backgroundTasksStop) {
+ if (rejectStop) throw new Error("Fixture stop failure");
+ tasks = tasks.map((task) => task.id === payload!.id ? { ...task, state: "stopped" } : task);
+ for (const listener of listeners) listener();
+ return { ok: true, found: true };
+ }
+ if (channel === IPC.invoke.todosGet) return useAppStore.getState().sessionTodos["fixture"];
+ throw new Error(`Unexpected fixture IPC: ${channel}`);
+ };
+ return { ok: true, data: await call() };
+ },
+ on: (channel: string, listener: () => void) => {
+ if (channel !== IPC.event.backgroundTasksChanged) return () => {};
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ },
+});
+
+async function mount(count = 10) {
+ flushSync(() => root?.unmount());
+ pending.clear();
+ requests.length = 0;
+ revision = 0;
+ deferOutput = false;
+ rejectStop = false;
+ tasks = Array.from({ length: count }, (_, index) => ({
+ id: `task-${index}`, sessionId: "fixture",
+ command: `node output-fixture.mjs --task=${index} ${"long-command-".repeat(8)}`,
+ commandShellId: "bash", state: "running", elapsedMs: 1_000,
+ }));
+ document.body.innerHTML = '<main id="root"></main>';
+ useAppStore.setState({
+ activeSessionId: "fixture",
+ sessionTodos: {
+ fixture: {
+ sessionId: "fixture", revision: 1, updatedAt: 1,
+ todos: [{ content: "Verify background commands", status: "in_progress", priority: "medium" }],
+ },
+ },
+ });
+ root = createRoot(document.getElementById("root")!);
+ flushSync(() => root!.render(
+ <I18nextProvider i18n={i18n}>
+ <div className="composer-dock composer-dock-docked">
+ <div className="composer-stack">
+ <TodoDock sessionId="fixture" />
+ <BackgroundTasksBar />
+ <AskToolCard request={{
+ sessionId: "fixture", requestId: "fixture-ask", toolCallId: "fixture-ask",
+ questions: [{ question: "Keep the background commands running?", options: ["Continue", "Stop"] }],
+ }} />
+ <div className="composer-shell"><textarea aria-label="Fixture message" /></div>
+ </div>
+ </div>
+ </I18nextProvider>,
+ ));
+ await until(() => document.querySelectorAll(".background-task").length === count, "tasks did not render");
+}
+
+function row(index: number) {
+ const element = document.querySelectorAll<HTMLElement>(".background-task")[index];
+ assert(element, `task ${index} must be reachable`);
+ return element;
+}
+
+function click(index: number, label = "Output") {
+ const button = [...row(index).querySelectorAll<HTMLButtonElement>("button")]
+ .find((button) => (button.getAttribute("aria-label") ?? button.textContent)?.trim() === label);
+ assert(button, `${label} control is missing`);
+ flushSync(() => button.click());
+}
+
+async function probe() {
+ await i18n.init({ lng: "en", resources: { en: { translation: en } } });
+ const results: { name: string; ok: boolean; error?: string }[] = [];
+ let responsiveness: { samples: number; eventLoopDelayP95Ms: number; eventLoopDelayMaxMs: number; outputReads: number } | undefined;
+ const unhandled: string[] = [];
+ const onUnhandled = (event: PromiseRejectionEvent) => {
+ event.preventDefault();
+ unhandled.push(String(event.reason));
+ };
+ window.addEventListener("unhandledrejection", onUnhandled);
+ const check = async (name: string, run: () => Promise<void>) => {
+ try { await run(); results.push({ name, ok: true }); }
+ catch (error) { results.push({ name, ok: false, error: String(error) }); }
+ };
+
+ await check("ten tasks scroll without displacing Todo, Ask, or input", async () => {
+ await mount();
+ const bar = document.querySelector<HTMLElement>(".background-tasks-bar")!;
+ const box = bar.getBoundingClientRect();
+ assert(box.height >= 40, `task list must be visible (${box.height}px)`);
+ assert(box.height <= 220, `task list is unbounded (${box.height}px)`);
+ assert(bar.scrollHeight > bar.clientHeight, "overflowing rows need an internal scrollport");
+ assert(getComputedStyle(bar).overflowY === "auto", "task list must be scrollable");
+ const todo = document.querySelector(".todo-dock")!.getBoundingClientRect();
+ const ask = document.querySelector(".asktool-card")!.getBoundingClientRect();
+ const input = document.querySelector("textarea")!.getBoundingClientRect();
+ assert(todo.top >= 0 && todo.bottom <= box.top + 1, "Todo must remain above the task list");
+ assert(box.bottom <= ask.top + 1 && ask.bottom <= input.top + 1, "Ask must remain above the input");
+ assert(input.bottom <= innerHeight && input.width > 100, "input must remain usable");
+ row(9).scrollIntoView({ block: "nearest" });
+ click(9);
+ await until(() => !!document.querySelector(".background-task-output")?.textContent?.includes("task-9"), "last task output is unreachable");
+ });
+
+ await check("only the selected log refreshes and remains bounded", async () => {
+ await mount();
+ assert(requests.length === 0, "collapsed logs must not cross IPC");
+ click(0);
+ await until(() => !!document.querySelector("pre")?.textContent?.includes("revision 0"), "initial output is missing");
+ revision = 1;
+ await until(() => !!document.querySelector("pre")?.textContent?.includes("revision 1"), "expanded output never refreshed");
+ assert(requests.every((id) => id === "task-0"), "unselected output must not be fetched");
+ assert(document.querySelector("pre")!.textContent!.length <= 12_010, "rendered output must stay bounded");
+ });
+
+ await check("late output cannot replace the newly selected task", async () => {
+ await mount();
+ deferOutput = true;
+ click(0);
+ await until(() => pending.has("task-0"), "first output request is missing");
+ click(1);
+ await until(() => pending.has("task-1"), "second output request is missing");
+ pending.get("task-1")!(output("task-1"));
+ await until(() => !!document.querySelector("pre")?.textContent?.includes("task-1"), "second output is missing");
+ pending.get("task-0")!(output("task-0"));
+ await frame();
+ await frame();
+ assert(document.querySelector("pre")?.textContent?.includes("task-1"), "late first response erased the current output");
+ });
+
+ await check("Stop failures are visible and retryable", async () => {
+ await mount();
+ rejectStop = true;
+ click(0, "Stop");
+ await until(() => !!document.querySelector('[role="alert"]'), "Stop failure must be visible");
+ rejectStop = false;
+ click(0, "Stop");
+ await until(() => row(0).dataset.state === "stopped", "Stop retry did not settle");
+ assert(unhandled.length === 0, `unhandled rejection: ${unhandled.join(", ")}`);
+ });
+
+ await check("typing remains responsive with ten tasks and a full output preview", async () => {
+ await mount();
+ click(0);
+ await until(() => !!document.querySelector("pre")?.textContent?.includes("revision 0"), "output is missing");
+ const input = document.querySelector("textarea")!;
+ input.focus();
+ const gaps: number[] = [];
+ let previous = performance.now();
+ for (let index = 0; index < 120; index++) {
+ revision++;
+ input.value = `message-${index}`;
+ input.dispatchEvent(new InputEvent("input", { bubbles: true, data: String(index) }));
+ // A fixed-rate input workload measures event-loop delay independently
+ // of compositor frame suppression in an intentionally hidden window.
+ await new Promise<void>((resolve) => setTimeout(resolve, 16));
+ const now = performance.now();
+ gaps.push(Math.max(0, now - previous - 16));
+ previous = now;
+ }
+ gaps.sort((a, b) => a - b);
+ responsiveness = {
+ samples: gaps.length,
+ eventLoopDelayP95Ms: Number(gaps[Math.floor(gaps.length * 0.95)].toFixed(2)),
+ eventLoopDelayMaxMs: Number(gaps.at(-1)!.toFixed(2)),
+ outputReads: requests.length,
+ };
+ assert(input.value === "message-119", "typing must remain usable");
+ assert(responsiveness.eventLoopDelayP95Ms < 250, "background polling must not stall the renderer");
+ assert(requests.every((id) => id === "task-0"), "only the open output may be polled");
+ });
+
+ flushSync(() => root?.unmount());
+ await frame();
+ assert(listeners.size === 0, "unmount must detach the background task listener");
+ await mount();
+ await frame();
+ await frame();
+ window.removeEventListener("unhandledrejection", onUnhandled);
+ return { viewport: { width: innerWidth, height: innerHeight }, results, responsiveness, ok: results.every((result) => result.ok) };
+}
+
+Object.assign(globalThis, { backgroundTasksProbe: probe });