Skip to content

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

feat(chat): scope background tasks to their session and share one dock with todo (#1844)

TioitWang1191e07f1960
diff --git a/apps/desktop/src/components/BackgroundTasksBar.tsx b/apps/desktop/src/components/BackgroundTasksBar.tsx
deleted file mode 100644
index ace12f696..000000000
--- a/apps/desktop/src/components/BackgroundTasksBar.tsx
+++ /dev/null
@@ -1,148 +0,0 @@
-import { useMemo } from "react";
-import { useTranslation } from "react-i18next";
-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. */
-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.
- *
- * Only work that is still running, or that the renderer just watched finish,
- * earns a row here: a command that ended long ago is history, not something
- * the user is waiting on, and it must not sit above the composer forever.
- * Running tasks float to the top.
- */
-export function BackgroundTasksBar(): React.JSX.Element | null {
- const { t } = useTranslation();
- const { tasks, expandedId, output, stoppingIds, error, toggleOutput, stop, dismiss } =
- useBackgroundTasks();
- const outputText = useMemo(
- () => formatOutput(output, expandedId ?? ""),
- [output, expandedId],
- );
- 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);
- const isExpanded = expandedId === task.id;
- return (
- <div
- key={task.id}
- className="background-task"
- data-state={task.state}
- data-expanded={isExpanded ? "true" : undefined}
- >
- {/* The row body toggles the log; the explicit action buttons keep
- their own behavior and stay out of it. Kept as a div with a
- button role so Enter / Space match the projection button. */}
- <div
- className="background-task-main"
- role="button"
- tabIndex={0}
- aria-expanded={isExpanded}
- onClick={() => void toggleOutput(task.id)}
- onKeyDown={(event) => {
- if (event.target !== event.currentTarget) return;
- if (event.key === "Enter" || event.key === " ") {
- event.preventDefault();
- void toggleOutput(task.id);
- }
- }}
- >
- <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>
- </div>
- <Button
- type="button"
- variant="ghost"
- size="sm"
- className="background-task-action"
- onClick={() => void toggleOutput(task.id)}
- aria-expanded={isExpanded}
- >
- {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>
- ) : (
- <Button
- type="button"
- variant="ghost"
- size="sm"
- className="background-task-action"
- onClick={() => dismiss(task.id)}
- >
- {t("backgroundTasks.dismiss")}
- </Button>
- )}
- {isExpanded ? (
- <pre className="background-task-output">
- {outputText || 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 ccb335817..365669947 100644
--- a/apps/desktop/src/components/Composer.tsx
+++ b/apps/desktop/src/components/Composer.tsx
@@ -31,8 +31,7 @@ import {
import { ComposerAutocomplete } from "./ComposerAutocomplete";
import { AskToolCard } from "./AskToolCard";
import { PlanApprovalBar } from "./PlanApprovalBar";
-import { TodoDock } from "./TodoDock";
-import { BackgroundTasksBar } from "./BackgroundTasksBar";
+import { TaskDock } from "./TaskDock";
import {
COMPOSER_MAX_VISIBLE_ROWS,
COMPOSER_MIN_HEIGHT_PX,
@@ -531,8 +530,10 @@ export function Composer({
data-composer-dock={variant}
>
<div className="composer-stack">
- {activeSessionId && localToolsAllowed ? <TodoDock sessionId={activeSessionId} /> : null}
- <BackgroundTasksBar />
+ {/* One container for todo and background tasks: the tabs live in the
+ header, so the gate now covers both the way it already covered the
+ todo dock. */}
+ {activeSessionId && localToolsAllowed ? <TaskDock sessionId={activeSessionId} /> : null}
{planCheckpoint?.status === "pending" ? (
<PlanApprovalBar proposal={planCheckpoint} />
) : null}
diff --git a/apps/desktop/src/components/TaskDock.tsx b/apps/desktop/src/components/TaskDock.tsx
new file mode 100644
index 000000000..1abd52fe4
--- /dev/null
+++ b/apps/desktop/src/components/TaskDock.tsx
@@ -0,0 +1,323 @@
+import { useId, useMemo } from "react";
+import { useTranslation } from "react-i18next";
+import type { SessionTodo } from "@pi-desktop/shared";
+import type { BackgroundTaskOutput, BackgroundTaskSummary } from "../lib/api";
+import { Button } from "./ui";
+import { IconChevronDown, IconChevronUp } from "./icons";
+import { TodoPanel, todoProgress } from "./TodoDock";
+import { useAppStore } from "../stores/app-store";
+import { useBackgroundTasks } from "../features/chat/background-tasks/useBackgroundTasks";
+import { useSessionTodosRecovery } from "../features/chat/todos/useSessionTodosRecovery";
+
+/**
+ * The composer's shared Todo + background-task container.
+ *
+ * Layout: one container, one header. The header carries the progress summary, a
+ * live count, the tab list and the chevron; collapsing hides only the panels, so
+ * the tabs stay reachable while collapsed. A single tab whose side is empty is
+ * not rendered, and a container with nothing to show renders nothing at all.
+ *
+ * The container owns the disclosure and the tab choice; the panels only render
+ * rows. Filtering, removal and the badge all live in the hook, so this file stays
+ * presentational.
+ */
+export function TaskDock({ sessionId }: { sessionId: string }) {
+ const { t } = useTranslation();
+ const snapshot = useAppStore((state) => state.sessionTodos[sessionId]);
+ const panelId = useId();
+
+ // The container now owns the todo read, so it recovers the snapshot the same
+ // way the standalone dock did.
+ useSessionTodosRecovery(sessionId);
+
+ const todos = snapshot?.todos ?? [];
+ const hasTodo = todos.length > 0;
+
+ const progress = useMemo(
+ () => (hasTodo ? todoProgress(todos, t) : null),
+ [hasTodo, todos, t],
+ );
+
+ // The container owns the todo read, so it hands the hook the todo side it
+ // cannot read itself: one tab rule then decides both the visible panel and
+ // whether a new task needs a badge.
+ const {
+ tasks,
+ sessionTasks,
+ activeTab,
+ openTasksTab,
+ openTodoTab,
+ collapsed,
+ setCollapsed,
+ badge,
+ badgeText,
+ expandedId,
+ output,
+ toggleOutput,
+ stop,
+ remove,
+ error,
+ stoppingIds,
+ } = useBackgroundTasks(sessionId, todos);
+
+ const hasTasks = sessionTasks.length > 0;
+ const running = sessionTasks.filter((task) => task.state === "running").length;
+ const showTabs = hasTodo && hasTasks;
+
+ if (!hasTodo && !hasTasks && !error) return null;
+
+ // A remembered tab that lost its content falls back to the other side.
+ const tab = hasTodo && hasTasks
+ ? activeTab
+ : hasTasks
+ ? "tasks"
+ : "todo";
+
+ const headerText = progress
+ ? progress.label
+ : t("backgroundTasks.headerCount", { count: sessionTasks.length });
+
+ return (
+ <div className={`dock${collapsed ? "" : " is-expanded"}`}>
+ <div className="dock-header">
+ <button
+ type="button"
+ className="dock-header-main"
+ aria-expanded={!collapsed}
+ aria-controls={panelId}
+ aria-label={
+ collapsed
+ ? t("taskDock.expand", { label: headerText })
+ : t("taskDock.collapse", { label: headerText })
+ }
+ onClick={() => setCollapsed(!collapsed)}
+ >
+ <span className="dock-header-symbol" aria-hidden>
+ {progress ? progress.symbol : "\u25d0"}
+ </span>
+ <span className="dock-header-copy">
+ <span className="dock-header-text">{headerText}</span>
+ {progress?.current ? (
+ <span
+ className={`dock-header-current${collapsed ? " todo-dock-shimmer" : ""}`}
+ title={progress.current.content}
+ >
+ {progress.current.content}
+ </span>
+ ) : null}
+ </span>
+ {running > 0 ? (
+ <span className="dock-live">
+ <span className="dock-live-dot" aria-hidden />
+ <span className="dock-live-label">
+ {t("taskDock.runningCount", { count: running })}
+ </span>
+ </span>
+ ) : null}
+ </button>
+
+ {showTabs ? (
+ <div className="dock-tablist is-inline" role="tablist" aria-label={t("taskDock.title")}>
+ <button
+ type="button"
+ role="tab"
+ id={`${panelId}-todo-tab`}
+ aria-controls={`${panelId}-todo`}
+ aria-selected={tab === "todo"}
+ tabIndex={tab === "todo" ? 0 : -1}
+ className={`dock-tab${tab === "todo" ? " is-active" : ""}`}
+ onClick={openTodoTab}
+ >
+ {t("taskDock.tabTodo")}
+ </button>
+ <button
+ type="button"
+ role="tab"
+ id={`${panelId}-tasks-tab`}
+ aria-controls={`${panelId}-tasks`}
+ aria-selected={tab === "tasks"}
+ tabIndex={tab === "tasks" ? 0 : -1}
+ className={`dock-tab${tab === "tasks" ? " is-active" : ""}`}
+ onClick={openTasksTab}
+ >
+ {t("taskDock.tabTasks")}
+ {badge > 0 ? (
+ <span
+ className="dock-tab-badge"
+ aria-label={t("taskDock.newTasks", { count: badge })}
+ >
+ {badgeText}
+ </span>
+ ) : null}
+ </button>
+ </div>
+ ) : null}
+
+ <Button
+ type="button"
+ variant="ghost"
+ className="dock-toggle"
+ aria-expanded={!collapsed}
+ aria-controls={panelId}
+ aria-label={
+ collapsed
+ ? t("taskDock.expand", { label: headerText })
+ : t("taskDock.collapse", { label: headerText })
+ }
+ onClick={() => setCollapsed(!collapsed)}
+ >
+ {collapsed ? <IconChevronUp size={18} /> : <IconChevronDown size={18} />}
+ </Button>
+ </div>
+
+ <div id={panelId} className="dock-content" aria-hidden={collapsed}>
+ <div className="dock-clip">
+ {error ? (
+ <p className="background-task-error" role="alert">
+ {t(`backgroundTasks.${error === "remove" ? "removeFailed" : `${error}Failed`}`)}
+ </p>
+ ) : null}
+ {hasTodo ? (
+ <TodoPanel
+ todos={todos}
+ listId={`${panelId}-todo`}
+ interactive={!collapsed && tab === "todo"}
+ />
+ ) : null}
+ {hasTasks ? (
+ <TaskPanel
+ listId={`${panelId}-tasks`}
+ tasks={tasks}
+ expandedId={expandedId}
+ output={output}
+ stoppingIds={stoppingIds}
+ onToggleOutput={toggleOutput}
+ onStop={(id) => void stop(id)}
+ onRemove={remove}
+ />
+ ) : null}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+/**
+ * Task rows. `Output` and `Stop`/`Remove` sit outside the row body so the
+ * clickable band never swallows a control, and the whole row stays one line:
+ * a long command ellipsizes with its full text in `title`.
+ */
+function TaskPanel({
+ listId,
+ tasks,
+ expandedId,
+ output,
+ stoppingIds,
+ onToggleOutput,
+ onStop,
+ onRemove,
+}: {
+ listId: string;
+ tasks: readonly BackgroundTaskSummary[];
+ expandedId: string | null;
+ output: BackgroundTaskOutput | null;
+ stoppingIds: ReadonlySet<string>;
+ onToggleOutput: (id: string) => void;
+ onStop: (id: string) => void;
+ onRemove: (id: string) => boolean;
+}) {
+ const { t } = useTranslation();
+ return (
+ <div id={listId} className="dock-panel" role="tabpanel" aria-labelledby={`${listId}-tab`}>
+ <div className="task-list">
+ {tasks.map((task) => {
+ const running = task.state === "running";
+ const stopping = stoppingIds.has(task.id);
+ const expanded = expandedId === task.id;
+ const meta = [
+ t(`backgroundTasks.${task.state}`),
+ running ? formatElapsed(task.elapsedMs) : null,
+ task.exitCode !== undefined ? String(task.exitCode) : null,
+ ].filter(Boolean).join(" \u00b7 ");
+ return (
+ <div
+ key={task.id}
+ className="task-row"
+ data-state={task.state}
+ data-expanded={expanded ? "true" : undefined}
+ >
+ <div className="task-band">
+ <div
+ className="task-main"
+ role="button"
+ tabIndex={0}
+ aria-expanded={expanded}
+ onClick={() => onToggleOutput(task.id)}
+ onKeyDown={(event) => {
+ if (event.target !== event.currentTarget) return;
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ onToggleOutput(task.id);
+ }
+ }}
+ >
+ <span className="task-state" aria-hidden />
+ <span className="task-command" title={task.command}>{task.command}</span>
+ <span className="task-meta">{meta}</span>
+ </div>
+ {running ? (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="task-action is-stop"
+ onClick={() => onStop(task.id)}
+ disabled={stopping}
+ >
+ {stopping ? t("backgroundTasks.stopping") : t("backgroundTasks.stop")}
+ </Button>
+ ) : (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="task-action"
+ onClick={() => onRemove(task.id)}
+ >
+ {t("backgroundTasks.dismiss")}
+ </Button>
+ )}
+ </div>
+ {expanded ? (
+ <pre className="task-output">{formatOutput(output, task.id)}</pre>
+ ) : null}
+ </div>
+ );
+ })}
+ </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`;
+}
+
+/** Characters shown when a finished task produced no output at all. */
+const NO_OUTPUT = "\u2014";
+
+function formatOutput(output: BackgroundTaskOutput | null, id: string): string {
+ if (!output || output.id !== id) return "";
+ const tail = (text: string, limit: number) =>
+ text.length > limit ? `\u2026${text.slice(-limit)}` : text;
+ return [tail(output.stdout, 8000), tail(output.stderr, 4000)]
+ .filter((part) => part.length > 0)
+ .join("\n---\n")
+ .trim() || NO_OUTPUT;
+}
+
+export type { SessionTodo };
diff --git a/apps/desktop/src/components/TodoDock.tsx b/apps/desktop/src/components/TodoDock.tsx
index ac3256a98..b5434eea3 100644
--- a/apps/desktop/src/components/TodoDock.tsx
+++ b/apps/desktop/src/components/TodoDock.tsx
@@ -6,17 +6,95 @@ import { IconCheck, IconChevronDown, IconChevronUp } from "./icons";
import { useSessionTodosRecovery } from "../features/chat/todos/useSessionTodosRecovery";
import { useAppStore } from "../stores/app-store";
+/**
+ * Todo rendering for the composer.
+ *
+ * Two shapes share the same rows and progress copy:
+ * `TodoDock` — the standalone dock, kept for callers and tests that mount it
+ * alone; it owns its disclosure and recovers the snapshot.
+ * `TodoPanel` — the panel form, used inside the shared container, where the
+ * container owns the disclosure and the tab choice.
+ *
+ * Keeping the summary in `todoProgress` means the collapsed header and the list
+ * can never disagree about progress.
+ */
+
+export type TodoProgress = {
+ /** Short label for the collapsed header, e.g. "2/4 done". */
+ label: string;
+ /** Glyph that carries the same state as the label. */
+ symbol: string;
+ /** First in-progress row, shown beside the label while collapsed. */
+ current: SessionTodo | undefined;
+};
+
+export function todoProgress(
+ todos: readonly SessionTodo[],
+ t: (key: string, options?: Record<string, unknown>) => string,
+): TodoProgress {
+ const completed = todos.filter((todo) => todo.status === "completed").length;
+ const cancelled = todos.filter((todo) => todo.status === "cancelled").length;
+ const denominator = todos.length - cancelled;
+ const current = todos.find((todo) => todo.status === "in_progress");
+ const allCancelled = todos.length > 0 && cancelled === todos.length;
+ const finished = todos.every(
+ (todo) => todo.status === "completed" || todo.status === "cancelled",
+ );
+ return {
+ label: allCancelled
+ ? t("chat.todo.status.cancelled")
+ : finished
+ ? t("chat.todo.completed", { completed, total: denominator })
+ : t("chat.todo.progress", { completed, total: denominator }),
+ symbol: allCancelled ? "\u2298" : finished ? "\u2713" : "\u25d0",
+ current,
+ };
+}
+
function statusSymbol(status: TodoStatus): string {
switch (status) {
case "in_progress":
- return "•";
+ return "\u2022";
case "cancelled":
- return "−";
+ return "\u2212";
default:
return "";
}
}
+/** The todo list as a container panel: rows only, no disclosure of its own. */
+export function TodoPanel({
+ todos,
+ listId,
+ interactive,
+ labelledBy,
+}: {
+ todos: readonly SessionTodo[];
+ listId: string;
+ /** False while the container is collapsed: the list is mounted but inert. */
+ interactive: boolean;
+ labelledBy?: string;
+}) {
+ return (
+ <div
+ id={listId}
+ className="dock-panel"
+ role="tabpanel"
+ aria-labelledby={labelledBy}
+ hidden={!interactive}
+ >
+ {/* The list scrolls inside its own box rather than truncating (#1319), and
+ a keyboard user can reach that scrollport only while it is on screen. */}
+ <div className="todo-dock-list" role="list" tabIndex={interactive ? 0 : -1}>
+ {todos.map((todo, index) => (
+ <TodoRow key={`${index}:${todo.content}`} todo={todo} shimmer={interactive} />
+ ))}
+ </div>
+ </div>
+ );
+}
+
+/** Standalone todo dock: recovers its snapshot and owns its disclosure. */
export function TodoDock({ sessionId }: { sessionId: string }) {
const { t } = useTranslation();
const snapshot = useAppStore((state) => state.sessionTodos[sessionId]);
@@ -29,34 +107,23 @@ export function TodoDock({ sessionId }: { sessionId: string }) {
useSessionTodosRecovery(sessionId);
if (!snapshot || snapshot.todos.length === 0) return null;
- const completed = snapshot.todos.filter((todo) => todo.status === "completed").length;
- const cancelled = snapshot.todos.filter((todo) => todo.status === "cancelled").length;
- const denominator = snapshot.todos.length - cancelled;
- const current = snapshot.todos.find((todo) => todo.status === "in_progress");
- const allCancelled = cancelled === snapshot.todos.length;
- const finished = snapshot.todos.every(
- (todo) => todo.status === "completed" || todo.status === "cancelled",
- );
- const progressLabel = allCancelled
- ? t("chat.todo.status.cancelled")
- : finished
- ? t("chat.todo.completed", { completed, total: denominator })
- : t("chat.todo.progress", { completed, total: denominator });
- const currentShimmers = !expanded && current !== undefined;
+
+ const progress = todoProgress(snapshot.todos, t);
+ const currentShimmers = !expanded && progress.current !== undefined;
return (
<div className={`todo-dock${expanded ? " is-expanded" : ""}`}>
<div className="todo-dock-header">
<span className="todo-dock-header-symbol" aria-hidden>
- {allCancelled ? "⊘" : finished ? "✓" : "◐"}
+ {progress.symbol}
</span>
<div className="todo-dock-header-copy">
- <span className="todo-dock-header-text">{progressLabel}</span>
- {current ? (
+ <span className="todo-dock-header-text">{progress.label}</span>
+ {progress.current ? (
<span
className={`todo-dock-header-current${currentShimmers ? " todo-dock-shimmer" : ""}`}
- title={current.content}
+ title={progress.current.content}
>
- {current.content}
+ {progress.current.content}
</span>
) : null}
</div>
diff --git a/apps/desktop/src/features/chat/background-tasks/bar-visibility.ts b/apps/desktop/src/features/chat/background-tasks/bar-visibility.ts
index f8e30bd72..e8ef670d7 100644
--- a/apps/desktop/src/features/chat/background-tasks/bar-visibility.ts
+++ b/apps/desktop/src/features/chat/background-tasks/bar-visibility.ts
@@ -131,10 +131,31 @@ export function nextExpiryAt(
return earliest;
}
-/** Hide one row from the bar. Runs nowhere near the process lifecycle. */
-export function dismissTask(state: BarVisibility, id: string): BarVisibility {
- if (state.dismissed.has(id)) return state;
+/**
+ * Hide one row from the bar. Runs nowhere near the process lifecycle.
+ *
+ * Removal is a view action, so it must never make a live task unreachable: a
+ * running task (including one already sent a stop signal, which is still
+ * `running` until the supervisor settles it) refuses removal here rather than
+ * relying on the caller not to render the control. `null` means the task is not
+ * in the current snapshot — nothing to remove, nothing to leak.
+ *
+ * Returns the previous state when the request is refused or already applied, so
+ * a stale snapshot cannot slip past the check.
+ */
+export function dismissTask(
+ state: BarVisibility,
+ task: Pick<BackgroundTaskSummary, "id" | "state"> | null,
+): BarVisibility {
+ if (!task) return state;
+ if (task.state === "running") return state;
+ if (state.dismissed.has(task.id)) return state;
const dismissed = new Set(state.dismissed);
- dismissed.add(id);
+ dismissed.add(task.id);
return { ...state, dismissed };
}
+
+/** Whether the row may offer removal; the same rule `dismissTask` enforces. */
+export function canDismiss(state: BarVisibility, task: Pick<BackgroundTaskSummary, "id" | "state">): boolean {
+ return task.state !== "running" && !state.dismissed.has(task.id);
+}
diff --git a/apps/desktop/src/features/chat/background-tasks/dock-state.ts b/apps/desktop/src/features/chat/background-tasks/dock-state.ts
new file mode 100644
index 000000000..1e32cfc68
--- /dev/null
+++ b/apps/desktop/src/features/chat/background-tasks/dock-state.ts
@@ -0,0 +1,200 @@
+import type { BackgroundTaskSummary } from "../../../lib/api";
+
+/**
+ * Per-session view state for the shared Todo/background-task container.
+ *
+ * Everything here is renderer memory: never persisted and never sent to the
+ * host. The registry stays the source of truth for the processes themselves, so
+ * switching a tab or collapsing the container cannot affect them.
+ */
+export type DockTab = "todo" | "tasks";
+
+export type DockSessionState = {
+ /** Tab the user last chose, or `null` while nothing was chosen yet. */
+ readonly chosenTab: DockTab | null;
+ /** New tasks counted since the tasks tab was last entered (the badge). */
+ readonly newCount: number;
+ /** Container-wide collapse; both tabs share it. */
+ readonly collapsed: boolean;
+};
+
+export type DockViewState = Readonly<Record<string, DockSessionState>>;
+
+export const EMPTY_SESSION_DOCK: DockSessionState = {
+ chosenTab: null,
+ newCount: 0,
+ collapsed: false,
+};
+
+/** The badge value a tab shows; `0` means "no badge". */
+export const MAX_BADGE = 9;
+
+export function sessionDockState(
+ view: DockViewState,
+ sessionId: string | null | undefined,
+): DockSessionState {
+ if (!sessionId) return EMPTY_SESSION_DOCK;
+ return view[sessionId] ?? EMPTY_SESSION_DOCK;
+}
+
+function withSession(
+ view: DockViewState,
+ sessionId: string,
+ patch: Partial<DockSessionState>,
+): DockViewState {
+ const current = view[sessionId] ?? EMPTY_SESSION_DOCK;
+ return { ...view, [sessionId]: { ...current, ...patch } };
+}
+
+/**
+ * Which tab the container shows.
+ *
+ * A remembered choice wins while its side still has content; otherwise the
+ * content decides (running work first, then an in-progress todo). A tab whose
+ * side is empty is never selected, so the caller never renders an empty panel.
+ */
+export function resolveDockTab(
+ state: DockSessionState,
+ hasTodo: boolean,
+ hasTasks: boolean,
+ runningTasks: number,
+ inProgressTodos: number,
+): DockTab {
+ if (hasTodo && hasTasks) {
+ if (state.chosenTab === "todo") return "todo";
+ if (state.chosenTab === "tasks") return "tasks";
+ if (runningTasks > 0) return "tasks";
+ if (inProgressTodos > 0) return "todo";
+ return "todo";
+ }
+ if (hasTasks) return "tasks";
+ return "todo";
+}
+
+/** Both sides of the container, as the tab rule needs to see them. */
+export type DockSides = {
+ hasTodo: boolean;
+ hasTasks: boolean;
+ runningTasks: number;
+ inProgressTodos: number;
+};
+
+export function resolveDockTabFor(state: DockSessionState, sides: DockSides): DockTab {
+ return resolveDockTab(
+ state,
+ sides.hasTodo,
+ sides.hasTasks,
+ sides.runningTasks,
+ sides.inProgressTodos,
+ );
+}
+
+/**
+ * Whether the background-task panel is the one on screen, which is the only
+ * condition under which a new task needs no badge. A collapsed container shows
+ * no panel at all, so it never counts as looking at the tasks.
+ *
+ * Shared with the hook so the badge rule has one definition instead of a copy
+ * that drifts from the render rule.
+ */
+export function tasksPanelVisible(state: DockSessionState, sides: DockSides): boolean {
+ return !state.collapsed && resolveDockTabFor(state, sides) === "tasks";
+}
+
+/**
+ * Record a task list snapshot for one session.
+ *
+ * The badge counts tasks that appear for the first time while the tasks panel is
+ * not the one on screen: while it is visible a new row needs no announcement,
+ * and a collapsed container hides it too, so that case does count.
+ */
+export function observeSessionTasks(
+ view: DockViewState,
+ sessionId: string,
+ tasks: readonly BackgroundTaskSummary[],
+ options: {
+ /** Task ids this session had already seen, before this snapshot. */
+ knownIds: ReadonlySet<string>;
+ /** Whether the tasks panel is currently the visible one. */
+ tasksVisible: boolean;
+ },
+): { view: DockViewState; knownIds: Set<string> } {
+ const knownIds = new Set<string>();
+ let added = 0;
+ for (const task of tasks) {
+ knownIds.add(task.id);
+ if (options.knownIds.has(task.id)) continue;
+ if (task.state !== "running") continue;
+ if (!options.tasksVisible) added += 1;
+ }
+ if (added === 0) return { view, knownIds };
+ const current = sessionDockState(view, sessionId);
+ return {
+ view: withSession(view, sessionId, { newCount: current.newCount + added }),
+ knownIds,
+ };
+}
+
+/** The user entered the tasks tab: the badge has been seen. */
+export function clearBadge(view: DockViewState, sessionId: string): DockViewState {
+ const current = sessionDockState(view, sessionId);
+ if (current.newCount === 0) return view;
+ return withSession(view, sessionId, { newCount: 0 });
+}
+
+/**
+ * The user picked a tab. Only this writes the remembered choice, so a tab the
+ * container chose on its own never overwrites what the user wanted.
+ */
+export function chooseTab(
+ view: DockViewState,
+ sessionId: string,
+ tab: DockTab,
+): DockViewState {
+ return withSession(view, sessionId, { chosenTab: tab });
+}
+
+/**
+ * The user clicked a tab in the header.
+ *
+ * Clicking a tab while collapsed also expands the container — otherwise the
+ * click would only swap an invisible panel and appear to do nothing — so this
+ * is the one user action that writes both fields.
+ */
+export function selectTab(
+ view: DockViewState,
+ sessionId: string,
+ tab: DockTab,
+): DockViewState {
+ return withSession(view, sessionId, { chosenTab: tab, collapsed: false });
+}
+
+export function toggleCollapsed(
+ view: DockViewState,
+ sessionId: string,
+): DockViewState {
+ const current = sessionDockState(view, sessionId);
+ return withSession(view, sessionId, { collapsed: !current.collapsed });
+}
+
+/** Badge markup value: `0` hides it, and long counts collapse to `9+`. */
+export function badgeLabel(count: number): string {
+ return count > MAX_BADGE ? `${MAX_BADGE}+` : String(count);
+}
+
+/** Drop entries for sessions that no longer exist, so the map cannot grow. */
+export function pruneDockView(
+ view: DockViewState,
+ liveSessionIds: ReadonlySet<string>,
+): DockViewState {
+ let changed = false;
+ const next: Record<string, DockSessionState> = {};
+ for (const [id, state] of Object.entries(view)) {
+ if (liveSessionIds.has(id)) {
+ next[id] = state;
+ } else {
+ changed = true;
+ }
+ }
+ return changed ? next : view;
+}
diff --git a/apps/desktop/src/features/chat/background-tasks/useBackgroundTasks.ts b/apps/desktop/src/features/chat/background-tasks/useBackgroundTasks.ts
index e7cbc7277..003edbbd4 100644
--- a/apps/desktop/src/features/chat/background-tasks/useBackgroundTasks.ts
+++ b/apps/desktop/src/features/chat/background-tasks/useBackgroundTasks.ts
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { api, type BackgroundTaskOutput, type BackgroundTaskSummary } from "../../../lib/api";
import {
type BarVisibility,
@@ -8,15 +8,65 @@ import {
observeTasks,
selectVisibleTasks,
} from "./bar-visibility";
+import {
+ type DockSides,
+ type DockTab,
+ type DockViewState,
+ badgeLabel,
+ clearBadge,
+ observeSessionTasks,
+ pruneDockView,
+ resolveDockTabFor,
+ selectTab,
+ sessionDockState,
+ tasksPanelVisible,
+ toggleCollapsed,
+} from "./dock-state";
+import type { SessionTodo } from "@pi-desktop/shared";
const REFRESH_MS = 1_000;
-type Failure = "load" | "output" | "stop";
+type Failure = "load" | "output" | "stop" | "remove";
-export function useBackgroundTasks() {
- const [tasks, setTasks] = useState<BackgroundTaskSummary[]>([]);
- // Renderer-local view state: which tasks the bar may show. The registry in
- // host-core stays the source of truth for the processes themselves.
+/**
+ * Both sides of the container, described the way the tab rule expects.
+ *
+ * The hook reads the task side from the registry snapshot and takes the todo
+ * side from its caller, which owns that read. Both the render rule and the
+ * badge rule consume this one description, so they cannot disagree about which
+ * panel is on screen.
+ */
+function sidesFor(
+ sessionTasks: readonly BackgroundTaskSummary[],
+ todos: readonly SessionTodo[],
+): DockSides {
+ let runningTasks = 0;
+ for (const task of sessionTasks) {
+ if (task.state === "running") runningTasks += 1;
+ }
+ return {
+ hasTodo: todos.length > 0,
+ hasTasks: sessionTasks.length > 0,
+ runningTasks,
+ inProgressTodos: todos.filter((todo) => todo.status === "in_progress").length,
+ };
+}
+/**
+ * Background tasks for one session, plus the shared container's view state.
+ *
+ * The host registry is global and stays that way: filtering happens here so the
+ * wire contract does not have to grow a session parameter and every consumer
+ * keeps seeing the full picture. Switching sessions therefore changes only what
+ * is displayed — never whether a task runs.
+ */
+export function useBackgroundTasks(
+ sessionId: string | null | undefined,
+ todos: readonly SessionTodo[] = [],
+) {
+ const [allTasks, setAllTasks] = useState<BackgroundTaskSummary[]>([]);
+ // Renderer-local view state: which tasks the container may show. The registry
+ // in host-core stays the source of truth for the processes themselves.
const [visibility, setVisibility] = useState<BarVisibility>(EMPTY_VISIBILITY);
+ const [dockView, setDockView] = useState<DockViewState>({});
const [clock, setClock] = useState(() => Date.now());
const [expandedId, setExpandedId] = useState<string | null>(null);
const [output, setOutput] = useState<BackgroundTaskOutput | null>(null);
@@ -25,6 +75,13 @@ export function useBackgroundTasks() {
const mounted = useRef(false);
const pendingStops = useRef(new Set<string>());
const refreshList = useRef<(() => void) | null>(null);
+ // Ids already folded into the badge, per session, so a re-read of the same
+ // snapshot cannot count the same task twice.
+ const knownIds = useRef(new Map<string, Set<string>>());
+ const dockViewRef = useRef(dockView);
+ dockViewRef.current = dockView;
+ const sessionIdRef = useRef(sessionId);
+ sessionIdRef.current = sessionId;
useEffect(() => {
mounted.current = true;
@@ -44,9 +101,28 @@ export function useBackgroundTasks() {
const result = await api.backgroundTasksList();
if (disposed) return;
const observedAt = Date.now();
- setTasks(result.tasks);
+ setAllTasks(result.tasks);
setVisibility((current) => observeTasks(current, result.tasks, observedAt));
setClock(observedAt);
+
+ // Fold the snapshot into the badge for the session on screen. A task is
+ // "new" only while the tasks panel is not the one being looked at.
+ const currentSession = sessionIdRef.current;
+ if (currentSession) {
+ const sessionTasks = result.tasks.filter((task) => task.sessionId === currentSession);
+ const seen = knownIds.current.get(currentSession) ?? new Set<string>();
+ setDockView((current) => {
+ const state = sessionDockState(current, currentSession);
+ const tasksVisible = tasksPanelVisible(state, sidesFor(sessionTasks, todosRef.current));
+ const folded = observeSessionTasks(current, currentSession, sessionTasks, {
+ knownIds: seen,
+ tasksVisible,
+ });
+ knownIds.current.set(currentSession, folded.knownIds);
+ return folded.view;
+ });
+ }
+
setError((current) => current === "load" ? null : current);
pollAgain = result.tasks.some((task) => task.state === "running");
} catch (failure) {
@@ -78,23 +154,45 @@ export function useBackgroundTasks() {
};
}, []);
- // Only what the bar should render: running tasks, a finished task during its
- // post-exit grace window, and the row whose output the user is reading.
- const visibleTasks = selectVisibleTasks(visibility, tasks, clock, expandedId);
+ // Only this session's tasks reach the container. A task from another session
+ // is not hidden because it ended: it simply belongs elsewhere.
+ // The poll loop outlives a render, so it reads the todo side through a ref
+ // rather than capturing one snapshot of the caller's list.
+ const todosRef = useRef(todos);
+ todosRef.current = todos;
+ const sessionTasks = useMemo(
+ () => (sessionId ? allTasks.filter((task) => task.sessionId === sessionId) : []),
+ [allTasks, sessionId],
+ );
+
+ // Keep the per-session maps bounded as sessions come and go.
+ useEffect(() => {
+ const live = new Set(allTasks.map((task) => task.sessionId));
+ if (sessionId) live.add(sessionId);
+ setDockView((current) => pruneDockView(current, live));
+ for (const id of knownIds.current.keys()) {
+ if (!live.has(id)) knownIds.current.delete(id);
+ }
+ }, [allTasks, sessionId]);
+
+ // Only what the container should render: running tasks, a finished task during
+ // its post-exit grace window, and the row whose output the user is reading.
+ const visibleTasks = selectVisibleTasks(visibility, sessionTasks, clock, expandedId);
useEffect(() => {
- const expiry = nextExpiryAt(visibility, tasks, clock, expandedId);
+ const expiry = nextExpiryAt(visibility, sessionTasks, clock, expandedId);
if (expiry === null) return;
const timer = setTimeout(() => setClock(Date.now()), Math.max(0, expiry - clock));
return () => clearTimeout(timer);
- }, [visibility, tasks, clock, expandedId]);
+ }, [visibility, sessionTasks, clock, expandedId]);
- const selectedState = tasks.find((task) => task.id === expandedId)?.state;
+ const selectedState = sessionTasks.find((task) => task.id === expandedId)?.state;
useEffect(() => {
setOutput(null);
- if (!expandedId) return;
+ if (!expandedId || !sessionId) return;
let disposed = false;
let timer: ReturnType<typeof setTimeout> | undefined;
+ const sessionAtRequest = sessionId;
const refresh = async () => {
try {
const result = await api.backgroundTasksOutput(expandedId);
@@ -107,7 +205,7 @@ export function useBackgroundTasks() {
setError("output");
} finally {
// Only the selected log crosses IPC, with at most one read in flight.
- if (!disposed && selectedState === "running") {
+ if (!disposed && selectedState === "running" && sessionIdRef.current === sessionAtRequest) {
timer = setTimeout(() => void refresh(), REFRESH_MS);
}
}
@@ -117,17 +215,54 @@ export function useBackgroundTasks() {
disposed = true;
clearTimeout(timer);
};
- }, [expandedId, selectedState]);
+ }, [expandedId, selectedState, sessionId]);
const toggleOutput = useCallback((id: string) => {
setExpandedId((current) => current === id ? null : id);
setError((current) => current === "output" ? null : current);
}, []);
- const dismiss = useCallback((id: string) => {
- setVisibility((current) => dismissTask(current, id));
+ /**
+ * Enter the tasks tab: this is the only path that clears the badge.
+ *
+ * `selectTab` also expands the container, so a click on a tab while collapsed
+ * lands on a visible panel instead of appearing to do nothing.
+ */
+ const openTasksTab = useCallback(() => {
+ if (!sessionId) return;
+ setDockView((current) => clearBadge(selectTab(current, sessionId, "tasks"), sessionId));
+ }, [sessionId]);
+
+ const openTodoTab = useCallback(() => {
+ if (!sessionId) return;
+ setDockView((current) => selectTab(current, sessionId, "todo"));
+ }, [sessionId]);
+
+ const setCollapsed = useCallback((collapsed: boolean) => {
+ if (!sessionId) return;
+ const current = sessionDockState(dockViewRef.current, sessionId);
+ if (current.collapsed !== collapsed) {
+ setDockView((value) => toggleCollapsed(value, sessionId));
+ }
+ }, [sessionId]);
+
+ /**
+ * Remove a row from the container.
+ *
+ * The task is looked up here rather than trusting the caller's snapshot: a
+ * running task — including one already stopping — is refused with `false` so
+ * the UI can say why instead of silently dropping a live process.
+ */
+ const remove = useCallback((id: string): boolean => {
+ const task = sessionTasks.find((candidate) => candidate.id === id);
+ if (!task || task.state === "running") {
+ setError("remove");
+ return false;
+ }
+ setVisibility((current) => dismissTask(current, task));
setExpandedId((current) => current === id ? null : current);
- }, []);
+ return true;
+ }, [sessionTasks]);
const stop = useCallback(async (id: string) => {
if (pendingStops.current.has(id)) return;
@@ -148,14 +283,28 @@ export function useBackgroundTasks() {
}
}, []);
+ const dock = sessionDockState(dockView, sessionId);
+ const sides = sidesFor(sessionTasks, todos);
+ const activeTab: DockTab = resolveDockTabFor(dock, sides);
+
return {
+ /** Tasks belonging to the session on screen, after the grace window. */
tasks: visibleTasks,
+ /** Every task of this session, regardless of the grace window. */
+ sessionTasks,
+ activeTab,
+ openTasksTab,
+ openTodoTab,
+ collapsed: dock.collapsed,
+ setCollapsed,
+ badge: dock.newCount,
+ badgeText: badgeLabel(dock.newCount),
expandedId,
output,
stoppingIds,
error,
toggleOutput,
stop,
- dismiss,
+ remove,
};
}
diff --git a/apps/desktop/src/styles/composer.css b/apps/desktop/src/styles/composer.css
index e80887af4..ad89dc03c 100644
--- a/apps/desktop/src/styles/composer.css
+++ b/apps/desktop/src/styles/composer.css
@@ -992,60 +992,296 @@
}
}
-/* 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 {
+/* Shared container for todo and background tasks (one header, one tablist).
+ The header keeps the tablist visible while collapsed, so collapsing hides
+ only the panels; the chevron and the title are separate controls because a
+ tab is a button and a button may not nest inside another. */
+.dock {
+ margin-bottom: 8px;
+ overflow: hidden;
+ border: 1px solid var(--ds-border-subtle);
+ border-radius: var(--radius-md);
+ background: var(--ds-bg-dock-raised);
+}
+
+.dock-header {
+ display: flex;
+ width: 100%;
+ min-width: 0;
+ min-height: 44px;
+ align-items: center;
+ gap: 8px;
+ padding: 4px 8px 4px 6px;
+ color: var(--ds-text-primary);
+}
+
+.dock.is-expanded .dock-header {
+ border-bottom: 1px solid var(--ds-border-subtle);
+}
+
+/* The title region keeps "click the summary to collapse" discoverable without
+ wrapping the whole row in a button. */
+.dock-header-main {
+ display: flex;
+ min-width: 0;
+ flex: 1 1 auto;
+ align-items: center;
+ gap: 10px;
+ padding: 4px 4px 4px 6px;
+ border-radius: var(--radius-sm);
+ color: inherit;
+ text-align: left;
+ transition: background var(--motion-duration-fast) var(--motion-ease-out);
+}
+
+.dock-header-main:hover {
+ background: var(--ds-bg-hover);
+}
+
+.dock-header-main:focus-visible {
+ outline: 2px solid var(--ds-focus);
+ outline-offset: -2px;
+}
+
+.dock-header-symbol {
+ display: grid;
+ flex: 0 0 auto;
+ width: 18px;
+ height: 18px;
+ place-items: center;
+ color: var(--ds-text-secondary);
+ font-size: var(--text-sm);
+}
+
+.dock-header-copy {
display: flex;
+ min-width: 0;
+ flex: 1;
+ align-items: center;
+ gap: 10px;
+}
+
+.dock-header-text {
flex: 0 0 auto;
- flex-direction: column;
+ font-size: var(--text-sm);
+ white-space: nowrap;
+}
+
+.dock-header-current {
+ min-width: 0;
+ flex: 1;
+ overflow: hidden;
+ color: var(--ds-text-muted);
+ font-size: var(--text-sm);
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+/* A live dot plus its count, so the collapsed header still answers "is
+ something running" without a second control row. */
+.dock-live {
+ display: inline-flex;
+ flex: 0 0 auto;
+ align-items: center;
+ gap: 4px;
+ color: var(--ds-text-secondary);
+ font-size: var(--text-xs);
+ font-variant-numeric: tabular-nums;
+ white-space: nowrap;
+}
+
+.dock-live-dot {
+ width: 6px;
+ height: 6px;
+ border-radius: var(--radius-round);
+ background: var(--ds-success);
+ animation: dock-live-pulse 1.8s var(--motion-ease-standard) infinite;
+}
+
+@keyframes dock-live-pulse {
+ 0%,
+ 100% {
+ opacity: 1;
+ }
+
+ 50% {
+ opacity: 0.35;
+ }
+}
+
+.dock-toggle.btn {
+ width: 32px;
+ min-width: 32px;
+ height: 32px;
+ flex: 0 0 32px;
+ padding: 0;
+ color: var(--ds-text-muted);
+}
+
+.dock-toggle:hover:not(:disabled) {
+ background: var(--ds-bg-hover);
+ color: var(--ds-text-primary);
+}
+
+/* The disclosure reuses the todo dock's grid-row technique: the clip layer
+ carries the collapse so nothing holds the closed row open. */
+.dock-content {
+ display: grid;
+ grid-template-rows: 0fr;
+ opacity: 0;
+ transform: translateY(-4px);
+ transition:
+ grid-template-rows var(--motion-duration-normal) var(--motion-ease-out),
+ opacity var(--motion-duration-fast) var(--motion-ease-out),
+ transform var(--motion-duration-normal) var(--motion-ease-out);
+}
+
+.dock.is-expanded .dock-content {
+ grid-template-rows: 1fr;
+ opacity: 1;
+ transform: translateY(0);
+}
+
+.dock-clip {
+ min-height: 0;
+ overflow: hidden;
+}
+
+/* Inline tablist: lives in the header row and must never wrap. */
+.dock-tablist {
+ display: flex;
+ flex: 0 0 auto;
+ align-items: center;
+ gap: 2px;
+ padding: 2px;
+ border-radius: var(--radius-full);
+ background: color-mix(in oklab, var(--ds-text-primary) 6%, transparent);
+ width: fit-content;
+}
+
+.dock-tab {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ padding: 5px 11px;
+ border-radius: var(--radius-full);
+ color: var(--ds-text-secondary);
+ font-size: var(--text-sm);
+ line-height: var(--leading-tighter);
+ white-space: nowrap;
+ transition:
+ background var(--motion-duration-fast) var(--motion-ease-out),
+ color var(--motion-duration-fast) var(--motion-ease-out),
+ box-shadow var(--motion-duration-fast) var(--motion-ease-out);
+}
+
+.dock-tab:hover {
+ color: var(--ds-text-primary);
+}
+
+.dock-tab.is-active {
+ background: var(--ds-raised);
+ color: var(--ds-text-primary);
+ box-shadow: var(--ds-raised-shadow);
+}
+
+.dock-tab:focus-visible {
+ outline: 2px solid var(--ds-focus);
+ outline-offset: 1px;
+}
+
+/* The badge is the "new tasks" affordance that replaces auto-switching. */
+.dock-tab-badge {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ min-width: 16px;
+ height: 16px;
+ padding: 0 4px;
+ border-radius: var(--radius-full);
+ background: var(--ds-text-primary);
+ color: var(--ds-bg-primary);
+ font-size: var(--text-xs);
+ font-weight: var(--font-weight-medium);
+ font-variant-numeric: tabular-nums;
+ line-height: var(--leading-none);
+}
+
+.dock-panel {
max-height: min(200px, 24vh);
- margin: 0 0 8px;
- 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);
}
-.background-task {
+.dock-panel:focus-visible {
+ outline: 2px solid var(--ds-focus);
+ outline-offset: -2px;
+}
+
+.dock-panel[hidden] {
+ display: none;
+}
+
+/* A task row stacks vertically: the command band on top, an optional log below.
+ Keeping them as siblings stops an expanded log from redistributing the
+ command line and its action button. */
+.task-row {
display: flex;
flex-shrink: 0;
- flex-wrap: wrap;
- align-items: center;
- gap: 8px;
+ flex-direction: column;
+ align-items: stretch;
min-width: 0;
- padding: 0;
color: var(--ds-text-secondary);
font-size: var(--text-sm);
+ transition: background var(--motion-duration-fast) var(--motion-ease-out);
}
-/* The row body opens the log; the action buttons sit outside it in the same
- flex line, so the clickable area is everything except the controls. */
-.background-task-main {
+.task-row + .task-row {
+ border-top: 1px solid var(--ds-border-subtle);
+}
+
+.task-row:hover {
+ background: var(--ds-bg-hover);
+}
+
+/* The only horizontally laid out band, and it never wraps: a long command
+ ellipsizes instead of pushing the state/time metadata onto a second line. */
+.task-band {
+ display: flex;
+ flex-wrap: nowrap;
+ align-items: center;
+ gap: 8px;
+ min-width: 0;
+}
+
+/* The row body opens the log; the action button sits beside it, outside the
+ clickable area. */
+.task-main {
display: flex;
flex: 1 1 auto;
- flex-wrap: wrap;
+ flex-wrap: nowrap;
align-items: center;
gap: 8px;
min-width: 0;
- padding: 6px 10px;
+ padding: 7px 10px 7px 12px;
border-radius: var(--radius-sm);
cursor: pointer;
}
-.background-task-main:focus-visible {
+.task-main:focus-visible {
outline: 2px solid var(--ds-focus);
outline-offset: -2px;
}
-.background-task[data-expanded="true"] .background-task-main {
+.task-row[data-expanded="true"] .task-main {
color: var(--ds-text-primary);
}
+.task-row[data-expanded="true"] {
+ background: var(--ds-bg-hover);
+}
+
.background-task-error {
margin: 0;
padding: 6px 10px;
@@ -1053,17 +1289,9 @@
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 {
+.task-state {
flex: 0 0 auto;
width: 7px;
height: 7px;
@@ -1071,12 +1299,12 @@
background: var(--ds-text-faint);
}
-.background-task[data-state="running"] .background-task-state {
+.task-row[data-state="running"] .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 {
+.task-row[data-state="failed"] .task-state {
background: var(--ds-warning);
}
@@ -1090,7 +1318,7 @@
}
}
-.background-task-command {
+.task-command {
min-width: 0;
flex: 1;
overflow: hidden;
@@ -1100,7 +1328,7 @@
white-space: nowrap;
}
-.background-task-meta {
+.task-meta {
flex: 0 0 auto;
color: var(--ds-text-muted);
font-size: var(--text-xs);
@@ -1109,21 +1337,21 @@
white-space: nowrap;
}
-.background-tasks-bar .background-task-action {
+.dock-panel .task-action {
flex: 0 0 auto;
+ margin-right: 4px;
color: var(--ds-text-muted);
}
-.background-tasks-bar .background-task-action:hover:not(:disabled) {
+.dock-panel .task-action:hover:not(:disabled) {
color: var(--ds-text-primary);
}
-.background-tasks-bar .background-task-action.is-stop:hover:not(:disabled) {
+.dock-panel .task-action.is-stop:hover:not(:disabled) {
color: var(--ds-warning);
}
-.background-task-output {
- flex-basis: 100%;
+.task-output {
max-height: 180px;
margin: 0;
padding: 8px 10px;
@@ -1137,3 +1365,42 @@
white-space: pre-wrap;
word-break: break-word;
}
+
+/* Narrow composer panes: the header cannot hold progress text, the current
+ step, a live count and the tablist at once. Drop the lowest-value copy rather
+ than crushing the tabs. */
+.dock {
+ container: dock / inline-size;
+}
+
+@container dock (max-width: 560px) {
+ .dock-header-current {
+ display: none;
+ }
+}
+
+@container dock (max-width: 470px) {
+ .dock-live-label {
+ display: none;
+ }
+
+ .dock-tab {
+ padding: 4px 8px;
+ }
+
+ .dock-toggle.btn {
+ width: 26px;
+ min-width: 26px;
+ height: 26px;
+ flex: 0 0 26px;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .dock-content,
+ .dock-live-dot,
+ .task-row[data-state="running"] .task-state {
+ animation: none;
+ transition: none;
+ }
+}
diff --git a/apps/desktop/test/background-tasks-bar-row-toggle.test.mjs b/apps/desktop/test/background-tasks-bar-row-toggle.test.mjs
deleted file mode 100644
index e119fe494..000000000
--- a/apps/desktop/test/background-tasks-bar-row-toggle.test.mjs
+++ /dev/null
@@ -1,58 +0,0 @@
-import assert from "node:assert/strict";
-import { readFile } from "node:fs/promises";
-import test from "node:test";
-
-/*
- * The row body of the background-tasks bar toggles the log, not only the
- * "output" button: the clickable surface is the whole row lead (state dot,
- * command, meta), while stop / dismiss keep their own behavior.
- */
-
-const [bar, composerStyles] = await Promise.all([
- readFile(new URL("../src/components/BackgroundTasksBar.tsx", import.meta.url), "utf8"),
- readFile(new URL("../src/styles/composer.css", import.meta.url), "utf8"),
-]);
-
-test("the row body is an interactive element that toggles the log", () => {
- const main = bar.match(
- /<div\s+className="background-task-main"[\s\S]*?<\/div>/,
- );
- assert.ok(main, "row body element missing");
- assert.match(main[0], /role="button"/);
- assert.match(main[0], /tabIndex=\{0\}/);
- assert.match(main[0], /aria-expanded=\{isExpanded\}/);
- assert.match(main[0], /onClick=\{\(\) => void toggleOutput\(task\.id\)\}/);
- // Keyboard parity with a real button.
- assert.match(main[0], /event\.key === "Enter" \|\| event\.key === " "/);
- assert.match(main[0], /if \(event\.target !== event\.currentTarget\) return;/);
-});
-
-test("the toggle surface covers the state dot, command and meta rows", () => {
- const main = bar.match(
- /<div\s+className="background-task-main"[\s\S]*?<\/div>/,
- )[0];
- for (const className of ["background-task-state", "background-task-command", "background-task-meta"]) {
- assert.match(main, new RegExp(`className="${className}"`));
- }
-});
-
-test("stop and dismiss stay outside the toggle surface", () => {
- const toggleEnd = bar.indexOf('className="background-task-main"');
- const stopAt = bar.indexOf('background-task-action is-stop"');
- const dismissAt = bar.indexOf('onClick={() => dismiss(task.id)}');
- assert.ok(stopAt > toggleEnd && dismissAt > toggleEnd);
- // Exactly one projection button remains.
- assert.equal(bar.match(/t\("backgroundTasks\.output"\)/g)?.length, 1);
-});
-
-test("the row styles keep the body clickable and focus-visible", () => {
- assert.match(
- composerStyles,
- /\.background-task-main\s*\{[^{}]*flex: 1 1 auto/,
- );
- assert.match(composerStyles, /\.background-task-main\s*\{[^{}]*cursor: pointer/);
- assert.match(
- composerStyles,
- /\.background-task-main:focus-visible\s*\{[^{}]*outline: 2px solid var\(--ds-focus\)/,
- );
-});
diff --git a/apps/desktop/test/background-tasks-bar-visibility.test.mjs b/apps/desktop/test/background-tasks-bar-visibility.test.mjs
index 55a490c2e..510863db4 100644
--- a/apps/desktop/test/background-tasks-bar-visibility.test.mjs
+++ b/apps/desktop/test/background-tasks-bar-visibility.test.mjs
@@ -14,6 +14,7 @@ register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
const {
ENDED_VISIBLE_MS,
EMPTY_VISIBILITY,
+ canDismiss,
dismissTask,
nextExpiryAt,
observeTasks,
@@ -52,13 +53,13 @@ test("a task observed running shows, keeps a grace window after exit, then leave
assert.deepEqual(selectVisibleTasks(state, ended, 5_000 + ENDED_VISIBLE_MS), []);
});
-test("a row the user closed stays closed across later snapshots", () => {
+test("a row the user removed stays removed across later snapshots", () => {
let state = observeTasks(EMPTY_VISIBILITY, [task("a", "running")], 0);
const ended = [task("a", "exited", 0)];
state = observeTasks(state, ended, 100);
assert.equal(selectVisibleTasks(state, ended, 100).length, 1);
- state = dismissTask(state, "a");
+ state = dismissTask(state, ended[0]);
assert.deepEqual(selectVisibleTasks(state, ended, 100), []);
state = observeTasks(state, ended, 200);
assert.deepEqual(selectVisibleTasks(state, ended, 200), []);
@@ -74,13 +75,25 @@ test("the row whose output is open is not pulled away by the grace window", () =
assert.equal(nextExpiryAt(state, ended, muchLater, "a"), null);
});
-test("running tasks never expire and a dismissed running task stays hidden", () => {
+test("running tasks never expire, and a running task cannot be removed", () => {
const running = [task("server", "running")];
- let state = observeTasks(EMPTY_VISIBILITY, running, 0);
+ const state = observeTasks(EMPTY_VISIBILITY, running, 0);
assert.equal(nextExpiryAt(state, running, 10 * ENDED_VISIBLE_MS), null);
- state = dismissTask(state, "server");
- assert.deepEqual(selectVisibleTasks(state, running, 0), []);
+ // Removal is a view action but must not make a live task unreachable: the
+ // state layer refuses it, so the row stays.
+ const afterRefusal = dismissTask(state, running[0]);
+ assert.equal(afterRefusal, state, "a refused removal must not change state");
+ assert.deepEqual(ids(selectVisibleTasks(afterRefusal, running, 0)), ["server"]);
+});
+
+test("removal is refused while a stopped task is still settling", () => {
+ // A task that has been signalled keeps `running` until the supervisor records
+ // the terminal state, so it must stay out of removal during that window.
+ const settling = [task("server", "running")];
+ const state = observeTasks(EMPTY_VISIBILITY, settling, 0);
+ assert.equal(canDismiss(state, settling[0]), false);
+ assert.equal(dismissTask(state, settling[0]), state);
});
test("expiry reports the earliest deadline among the rows still visible", () => {
@@ -96,8 +109,10 @@ test("expiry reports the earliest deadline among the rows still visible", () =>
test("bookkeeping is pruned when the registry drops a task, so it cannot grow", () => {
let state = observeTasks(EMPTY_VISIBILITY, [task("a", "running"), task("b", "running")], 0);
- state = dismissTask(state, "a");
+ // A terminal row may be removed; that is what puts an id into `dismissed`.
+ state = dismissTask(state, task("a", "exited", 0));
assert.deepEqual([...state.seenRunning].sort(), ["a", "b"]);
+ assert.deepEqual([...state.dismissed], ["a"]);
state = observeTasks(state, [task("b", "running")], 10);
assert.deepEqual([...state.seenRunning], ["b"]);
diff --git a/apps/desktop/test/background-tasks-dock-state.test.mjs b/apps/desktop/test/background-tasks-dock-state.test.mjs
new file mode 100644
index 000000000..59b47567f
--- /dev/null
+++ b/apps/desktop/test/background-tasks-dock-state.test.mjs
@@ -0,0 +1,204 @@
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+
+/*
+ * The shared container's view state. These pin the rules a user can observe:
+ * which panel is on screen, when a new task raises a badge, and what a click on
+ * a tab does while the container is collapsed. All of it is plain renderer
+ * memory, so a controlled input decides every case.
+ */
+
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+const {
+ EMPTY_SESSION_DOCK,
+ badgeLabel,
+ chooseTab,
+ clearBadge,
+ observeSessionTasks,
+ pruneDockView,
+ resolveDockTab,
+ resolveDockTabFor,
+ selectTab,
+ sessionDockState,
+ tasksPanelVisible,
+ toggleCollapsed,
+} = await import("../src/features/chat/background-tasks/dock-state.ts");
+
+const SESSION = "session-1";
+
+const task = (id, state = "running") => ({
+ id,
+ sessionId: SESSION,
+ command: `cmd ${id}`,
+ commandShellId: "bash",
+ state,
+ elapsedMs: 1_000,
+});
+
+const view = (patch) => ({ [SESSION]: { ...EMPTY_SESSION_DOCK, ...patch } });
+
+test("an unknown session starts from the empty state", () => {
+ assert.equal(sessionDockState({}, SESSION), EMPTY_SESSION_DOCK);
+ assert.equal(sessionDockState(view({ collapsed: true }), SESSION).collapsed, true);
+ // No session means no view state to read.
+ assert.equal(sessionDockState(view({ collapsed: true }), null), EMPTY_SESSION_DOCK);
+});
+
+test("clicking a tab while collapsed also expands the container", () => {
+ // D15: the click must not only swap an invisible panel, or it would look
+ // like it did nothing.
+ const collapsed = view({ collapsed: true });
+ const opened = selectTab(collapsed, SESSION, "tasks");
+
+ assert.equal(sessionDockState(opened, SESSION).collapsed, false);
+ assert.equal(sessionDockState(opened, SESSION).chosenTab, "tasks");
+});
+
+test("clicking the already-active tab while collapsed still expands", () => {
+ const collapsed = view({ collapsed: true, chosenTab: "tasks" });
+ const opened = selectTab(collapsed, SESSION, "tasks");
+ assert.equal(sessionDockState(opened, SESSION).collapsed, false);
+});
+
+test("only a user action writes the remembered tab", () => {
+ // Folding a snapshot into the badge must never overwrite what the user chose.
+ const chosen = chooseTab({}, SESSION, "todo");
+ const afterBadge = observeSessionTasks(chosen, SESSION, [task("a")], {
+ knownIds: new Set(),
+ tasksVisible: false,
+ });
+ assert.equal(sessionDockState(afterBadge.view, SESSION).chosenTab, "todo");
+});
+
+test("the remember-chosen tab wins while its side has content", () => {
+ const state = sessionDockState(view({ chosenTab: "todo" }), SESSION);
+ assert.equal(resolveDockTab(state, true, true, 3, 0), "todo");
+ assert.equal(
+ resolveDockTab({ ...state, chosenTab: "tasks" }, true, true, 0, 3),
+ "tasks",
+ );
+});
+
+test("with nothing remembered the content decides, running work first", () => {
+ const state = EMPTY_SESSION_DOCK;
+ assert.equal(resolveDockTab(state, true, true, 1, 1), "tasks");
+ assert.equal(resolveDockTab(state, true, true, 0, 1), "todo");
+ assert.equal(resolveDockTab(state, true, true, 0, 0), "todo");
+});
+
+test("a tab whose side is empty is never selected", () => {
+ // A remembered tab that lost its content falls back to the other side.
+ const remembered = { ...EMPTY_SESSION_DOCK, chosenTab: "tasks" };
+ assert.equal(resolveDockTab(remembered, true, false, 0, 0), "todo");
+ const rememberedTodo = { ...EMPTY_SESSION_DOCK, chosenTab: "todo" };
+ assert.equal(resolveDockTab(rememberedTodo, false, true, 0, 0), "tasks");
+});
+
+test("one populated side renders alone, so the tab list is not rendered", () => {
+ const sides = { hasTodo: true, hasTasks: false, runningTasks: 0, inProgressTodos: 1 };
+ assert.equal(resolveDockTabFor(EMPTY_SESSION_DOCK, sides), "todo");
+ // The container hides the tab list exactly when one side is empty.
+ assert.equal(sides.hasTodo && sides.hasTasks, false);
+});
+
+test("a collapsed container never counts as looking at the tasks panel", () => {
+ const sides = { hasTodo: true, hasTasks: true, runningTasks: 2, inProgressTodos: 0 };
+ assert.equal(tasksPanelVisible(EMPTY_SESSION_DOCK, sides), true);
+ assert.equal(
+ tasksPanelVisible({ ...EMPTY_SESSION_DOCK, collapsed: true }, sides),
+ false,
+ );
+ // The todo panel on screen is not the tasks panel either.
+ const onTodo = { ...EMPTY_SESSION_DOCK, chosenTab: "todo" };
+ assert.equal(tasksPanelVisible(onTodo, sides), false);
+});
+
+test("the render rule and the badge rule share one tab decision", () => {
+ // Both read `resolveDockTabFor`, so they cannot disagree about which panel is
+ // on screen. This is the invariant the old duplicated call broke.
+ const sides = { hasTodo: true, hasTasks: true, runningTasks: 1, inProgressTodos: 1 };
+ const state = EMPTY_SESSION_DOCK;
+ assert.equal(resolveDockTabFor(state, sides), "tasks");
+ assert.equal(tasksPanelVisible(state, sides), true);
+});
+
+test("a new task raises the badge only while the tasks panel is not on screen", () => {
+ const seen = new Set();
+ const raised = observeSessionTasks({}, SESSION, [task("a"), task("b")], {
+ knownIds: seen,
+ tasksVisible: false,
+ });
+ assert.equal(sessionDockState(raised.view, SESSION).newCount, 2);
+ assert.deepEqual([...raised.knownIds].sort(), ["a", "b"]);
+
+ const quiet = observeSessionTasks({}, SESSION, [task("a")], {
+ knownIds: new Set(),
+ tasksVisible: true,
+ });
+ assert.equal(sessionDockState(quiet.view, SESSION).newCount, 0);
+});
+
+test("the same snapshot re-read does not count a task twice", () => {
+ const first = observeSessionTasks({}, SESSION, [task("a")], {
+ knownIds: new Set(),
+ tasksVisible: false,
+ });
+ assert.equal(sessionDockState(first.view, SESSION).newCount, 1);
+
+ const again = observeSessionTasks(first.view, SESSION, [task("a")], {
+ knownIds: first.knownIds,
+ tasksVisible: false,
+ });
+ assert.equal(sessionDockState(again.view, SESSION).newCount, 1);
+});
+
+test("a task that is already finished is not new work", () => {
+ const finished = observeSessionTasks({}, SESSION, [task("a", "exited")], {
+ knownIds: new Set(),
+ tasksVisible: false,
+ });
+ assert.equal(sessionDockState(finished.view, SESSION).newCount, 0);
+});
+
+test("entering the tasks tab is the only clear point for the badge", () => {
+ const raised = observeSessionTasks({}, SESSION, [task("a")], {
+ knownIds: new Set(),
+ tasksVisible: false,
+ });
+ // Re-reading the list with the panel still hidden keeps the badge.
+ const still = observeSessionTasks(raised.view, SESSION, [task("a")], {
+ knownIds: raised.knownIds,
+ tasksVisible: false,
+ });
+ assert.equal(sessionDockState(still.view, SESSION).newCount, 1);
+
+ const cleared = clearBadge(chooseTab(still.view, SESSION, "tasks"), SESSION);
+ assert.equal(sessionDockState(cleared, SESSION).newCount, 0);
+ // The remembered tab survives the clear.
+ assert.equal(sessionDockState(cleared, SESSION).chosenTab, "tasks");
+});
+
+test("collapse is one container-wide condition, both tabs share it", () => {
+ const collapsed = toggleCollapsed({}, SESSION);
+ assert.equal(sessionDockState(collapsed, SESSION).collapsed, true);
+ assert.equal(sessionDockState(toggleCollapsed(collapsed, SESSION), SESSION).collapsed, false);
+});
+
+test("badge text hides at zero and collapses long counts", () => {
+ assert.equal(badgeLabel(0), "0");
+ assert.equal(badgeLabel(3), "3");
+ assert.equal(badgeLabel(9), "9");
+ assert.equal(badgeLabel(10), "9+");
+});
+
+test("view state is dropped for sessions that no longer exist", () => {
+ const kept = toggleCollapsed(chooseTab({}, SESSION, "tasks"), SESSION);
+ const both = toggleCollapsed(kept, "session-2");
+
+ // Pruning the dead session rebuilds the map, so identity is not the contract;
+ // the surviving entry must be untouched.
+ assert.deepEqual(pruneDockView(both, new Set([SESSION])), kept);
+ // An unchanged map keeps its identity so a render is not forced.
+ assert.equal(pruneDockView(kept, new Set([SESSION])), kept);
+});
diff --git a/apps/desktop/test/background-tasks-row-toggle.test.mjs b/apps/desktop/test/background-tasks-row-toggle.test.mjs
new file mode 100644
index 000000000..6b6a7845c
--- /dev/null
+++ b/apps/desktop/test/background-tasks-row-toggle.test.mjs
@@ -0,0 +1,71 @@
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import test from "node:test";
+
+/*
+ * The task row's body toggles the log: the clickable surface is the whole lead
+ * band (state dot, command, metadata), while stop / remove keep their own
+ * behavior and stay outside it.
+ */
+
+const [dock, composerStyles] = await Promise.all([
+ readFile(new URL("../src/components/TaskDock.tsx", import.meta.url), "utf8"),
+ readFile(new URL("../src/styles/composer.css", import.meta.url), "utf8"),
+]);
+
+test("the row body is an interactive element that toggles the log", () => {
+ const main = dock.match(/<div\s+className="task-main"[\s\S]*?<\/div>/);
+ assert.ok(main, "row body element missing");
+ assert.match(main[0], /role="button"/);
+ assert.match(main[0], /tabIndex=\{0\}/);
+ assert.match(main[0], /aria-expanded=\{expanded\}/);
+ assert.match(main[0], /onClick=\{\(\) => onToggleOutput\(task\.id\)\}/);
+ // Keyboard parity with a real button.
+ assert.match(main[0], /event\.key === "Enter" \|\| event\.key === " "/);
+ assert.match(main[0], /if \(event\.target !== event\.currentTarget\) return;/);
+});
+
+test("the toggle surface covers the state dot, command and meta rows", () => {
+ const main = dock.match(/<div\s+className="task-main"[\s\S]*?<\/div>/)[0];
+ for (const className of ["task-state", "task-command", "task-meta"]) {
+ assert.match(main, new RegExp(`className="${className}"`));
+ }
+});
+
+test("stop and remove stay outside the toggle surface", () => {
+ const toggleEnd = dock.indexOf('className="task-main"');
+ const bandAt = dock.indexOf('className="task-band"');
+ const stopAt = dock.indexOf('"task-action is-stop"');
+ const removeAt = dock.indexOf('className="task-action"');
+ assert.ok(bandAt > 0 && bandAt < toggleEnd, "the band must wrap the row body");
+ assert.ok(stopAt > toggleEnd && removeAt > toggleEnd, "actions must follow the body");
+});
+
+test("a running task offers stop and never remove", () => {
+ // The two actions are chosen by state in one branch: the stop control gates on
+ // `running`, and the remove control lives in the other arm.
+ assert.match(dock, /className="task-action is-stop"\s+onClick=\{\(\) => onStop\(task\.id\)\}/);
+ assert.match(dock, /className="task-action"\s+onClick=\{\(\) => onRemove\(task\.id\)\}/);
+ assert.match(dock, /backgroundTasks\.dismiss/);
+ assert.ok(
+ dock.indexOf('"task-action is-stop"') < dock.indexOf('className="task-action"'),
+ "the stop control comes from the running arm",
+ );
+});
+
+test("the row styles keep the body clickable and focus-visible", () => {
+ assert.match(composerStyles, /\.task-main\s*\{[^{}]*flex: 1 1 auto/);
+ assert.match(composerStyles, /\.task-main\s*\{[^{}]*cursor: pointer/);
+ assert.match(
+ composerStyles,
+ /\.task-main:focus-visible\s*\{[^{}]*outline: 2px solid var\(--ds-focus\)/,
+ );
+});
+
+test("a long command ellipsizes on one line instead of wrapping the row", () => {
+ // The band must not wrap, and the command must own the ellipsis, or a long
+ // command would push the metadata and its action onto a second line.
+ assert.match(composerStyles, /\.task-band\s*\{[^{}]*flex-wrap: nowrap/);
+ assert.match(composerStyles, /\.task-command\s*\{[^{}]*text-overflow: ellipsis/);
+ assert.match(composerStyles, /\.task-command\s*\{[^{}]*white-space: nowrap/);
+});
diff --git a/apps/desktop/test/background-tasks.test.mjs b/apps/desktop/test/background-tasks.test.mjs
index 7fdea5981..a1c3dde65 100644
--- a/apps/desktop/test/background-tasks.test.mjs
+++ b/apps/desktop/test/background-tasks.test.mjs
@@ -27,7 +27,7 @@ const backgroundTasks = await readFile(
"utf8",
);
const bar = await readFile(
- new URL("../src/components/BackgroundTasksBar.tsx", import.meta.url),
+ new URL("../src/components/TaskDock.tsx", import.meta.url),
"utf8",
);
const controller = await readFile(
@@ -86,19 +86,26 @@ test("turn cancellation and timeout cannot reach a background task: it never reg
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/);
+ // The user-visible limit is per session; a process-wide ceiling stays only as
+ // a host safety net and must be reported separately.
+ assert.match(backgroundTasks, /MAX_RUNNING_TASKS_PER_SESSION: usize = 10/);
+ assert.match(backgroundTasks, /MAX_RUNNING_TASKS_TOTAL/);
+ assert.doesNotMatch(backgroundTasks, /MAX_RUNNING_TASKS: usize = 32/);
});
-test("the renderer bar lists tasks, offers output and stop, and mounts above the composer input", () => {
+test("the renderer container lists tasks, offers output and stop, and mounts above the composer input", () => {
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 \/>/);
- // The bar renders before the composer shell (above the input, not inside it).
- const barIndex = composer.indexOf("<BackgroundTasksBar />");
+ // The shared container is the only composer surface for tasks now.
+ assert.match(composer, /import \{ TaskDock \} from "\.\/TaskDock";/);
+ assert.match(composer, /<TaskDock sessionId=\{activeSessionId\} \/>/);
+ assert.doesNotMatch(composer, /BackgroundTasksBar/);
+ // It renders before the composer shell (above the input, not inside it).
+ const dockIndex = composer.indexOf("<TaskDock sessionId={activeSessionId} />");
const shellIndex = composer.indexOf('className={`composer-shell');
- assert.ok(barIndex > 0 && shellIndex > barIndex, "bar must precede the composer shell");
+ assert.ok(dockIndex > 0 && shellIndex > dockIndex, "container must precede the composer shell");
+ // The todo side is gated exactly as the todo dock was.
+ assert.match(composer, /activeSessionId && localToolsAllowed \? <TaskDock/);
});
test("the api layer names the wire channels for list, output, stop, and the change event", () => {
@@ -117,34 +124,68 @@ test("the host notification fan-out exists in the electron main host wiring", as
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 \{/);
+test("the container styles exist and mark a running task with a pulse", () => {
+ assert.match(styles, /\.dock \{/);
assert.match(
styles,
- /\.background-task\[data-state="running"\] \.background-task-state \{[^}]*animation:/,
+ /\.task-row\[data-state="running"\] \.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\)/);
+ assert.match(styles, /\.task-command \{[^}]*color: var\(--ds-text-primary\)/);
+ // The tabs sit in the header row: the container must expose the tablist, the
+ // badge, and a separate disclosure control.
+ assert.match(styles, /\.dock-tablist \{/);
+ assert.match(styles, /\.dock-tab-badge \{/);
+ assert.match(styles, /\.dock-toggle\.btn \{/);
});
test("the running/stopped/failed/exited labels are translated", () => {
assert.match(i18nEn, /backgroundTasks: \{[^}]*running: "Running"/);
});
-test("the bar shows only live work: a finished row expires and can be closed", async () => {
+test("the container shows only live work: a finished row expires and can be removed", async () => {
const visibility = await readFile(
new URL("../src/features/chat/background-tasks/bar-visibility.ts", import.meta.url),
"utf8",
);
// The grace window is a named constant, not a magic number in the component.
assert.match(visibility, /export const ENDED_VISIBLE_MS = 10_000;/);
- assert.match(controller, /selectVisibleTasks\(visibility, tasks, clock, expandedId\)/);
+ assert.match(controller, /selectVisibleTasks\(visibility, sessionTasks, clock, expandedId\)/);
assert.match(controller, /observeTasks\(current, result\.tasks, observedAt\)/);
- assert.match(controller, /dismissTask\(current, id\)/);
- // A finished row offers closing instead of stopping: it must be able to leave
- // the composer without touching the process lifecycle.
+ // Removal is refused for a live task in the state layer, not just by hiding
+ // the control.
+ assert.match(visibility, /task\.state === "running"\) return state;/);
+ assert.match(controller, /if \(!task \|\| task\.state === "running"\)/);
+ assert.match(controller, /dismissTask\(current, task\)/);
+ // A finished row offers removal instead of stopping.
assert.match(bar, /\{t\("backgroundTasks\.dismiss"\)\}/);
- assert.match(bar, /onClick=\{\(\) => dismiss\(task\.id\)\}/);
- assert.match(i18nEn, /backgroundTasks: \{[^}]*dismiss: "Dismiss"/);
+ assert.match(bar, /onClick=\{\(\) => onRemove\(task\.id\)\}/);
+});
+
+test("the container filters to the active session and badges new work", () => {
+ assert.match(controller, /task\.sessionId === sessionId/);
+ // The wire contract stays session-agnostic.
+ assert.match(controller, /api\.backgroundTasksList\(\)/);
+ // The badge clears only when the user enters the tasks tab.
+ assert.match(controller, /const openTasksTab = useCallback/);
+ assert.match(controller, /clearBadge\(selectTab\(current, sessionId, "tasks"\), sessionId\)/);
+});
+
+test("deleting a session signals its tasks from the shared cleanup path only", () => {
+ // D6: every deletion path converges on `drop_session_side_data`, so that is
+ // the one place a stop is issued. There is no archive RPC: archiving is a
+ // renderer flag, which is what keeps it from killing live processes.
+ const cleanup = rpcSources.match(
+ /fn drop_session_side_data\(st: &AppState, id: &str\) \{([\s\S]*?)\n\}/,
+ );
+ assert.ok(cleanup, "the shared per-session cleanup must exist");
+ assert.match(cleanup[1], /st\.background_tasks\.stop_session_running\(id\);/);
+ // Deleting is the only caller of that cleanup, and no archive method exists.
+ assert.equal(
+ rpcSources.match(/drop_session_side_data\(&st, id\);/g)?.length,
+ 2,
+ "both deletion paths reach the shared cleanup",
+ );
+ assert.doesNotMatch(rpcSources, /"session\.archive"/);
});
diff --git a/crates/host-core/src/background_tasks.rs b/crates/host-core/src/background_tasks.rs
index 020aa30b1..c210105e7 100644
--- a/crates/host-core/src/background_tasks.rs
+++ b/crates/host-core/src/background_tasks.rs
@@ -23,9 +23,14 @@ 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;
+/// Upper bound on concurrently running background tasks **per session**. Each
+/// task holds a process tree and two pipe readers, so a session that loops on
+/// spawning servers must fail fast instead of exhausting the host.
+pub(crate) const MAX_RUNNING_TASKS_PER_SESSION: usize = 10;
+/// Process-wide ceiling across every session. It exists only to keep many
+/// sessions from adding up to an exhausted host; it is not a per-session
+/// limit and its refusal is reported separately so the cause stays readable.
+pub(crate) const MAX_RUNNING_TASKS_TOTAL: usize = 64;
/// Bounded set of finished tasks kept so the UI can show what just exited.
const FINISHED_TASK_HISTORY: usize = 16;
@@ -141,7 +146,6 @@ impl BackgroundTaskRegistry {
fn is_running(task: &BackgroundTask) -> bool {
Self::snapshot(task).0 == BackgroundTaskState::Running
}
-
pub fn running_count(&self) -> usize {
self.tasks
.values()
@@ -149,6 +153,35 @@ impl BackgroundTaskRegistry {
.count()
}
+ /// Running tasks owned by one session. This is the limit a user hits in
+ /// the UI, so the count is scoped rather than global.
+ pub fn running_count_for(&self, session_id: &str) -> usize {
+ self.tasks
+ .values()
+ .filter(|task| task.session_id == session_id && Self::is_running(task))
+ .count()
+ }
+
+ /// Stop signals for every running task of one session. Signal-only on
+ /// purpose: the supervisor kills and reaps, and no output lock is taken
+ /// here, so a caller holding the state mutex cannot deadlock against a
+ /// task that is mid-write. Idempotent — already-stopping tasks ignore it.
+ pub fn stop_session_running(&self, session_id: &str) -> usize {
+ let mut signalled = 0;
+ for task in self.tasks.values() {
+ if task.session_id != session_id || !Self::is_running(task) {
+ continue;
+ }
+ if *task.stop.borrow() {
+ continue;
+ }
+ if task.stop.send(true).is_ok() {
+ signalled += 1;
+ }
+ }
+ signalled
+ }
+
pub fn summaries(&self) -> Vec<BackgroundTaskSummary> {
let mut list: Vec<BackgroundTaskSummary> = self
.tasks
@@ -193,13 +226,38 @@ pub(crate) async fn spawn_background_task_detached(
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 {
+ // A task started for a session that no longer exists would belong to no
+ // visible container and outlive the thing it was started from, so refuse it
+ let session_alive = crate::sessions::session_exists(&st.db, session_id)
+ .map_err(|error| ("INTERNAL".to_string(), error.to_string()))?;
+ if !session_alive {
+ drop(runner);
+ return Err((
+ "TOOL_FAILED".into(),
+ "cannot start a background task for a session that no longer exists".into(),
+ ));
+ }
+ let running_here = st.background_tasks.running_count_for(session_id);
+ if running_here >= MAX_RUNNING_TASKS_PER_SESSION {
// 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"
+ "this session already runs {running_here} background tasks \
+ (limit {MAX_RUNNING_TASKS_PER_SESSION}); stop one first"
+ ),
+ ));
+ }
+ // The process-wide ceiling is a host safety net, not a session rule, so it
+ // reports itself separately instead of reading like the per-session limit.
+ if st.background_tasks.running_count() >= MAX_RUNNING_TASKS_TOTAL {
+ drop(runner);
+ return Err((
+ "TOOL_FAILED".into(),
+ format!(
+ "the host is already running its maximum of {MAX_RUNNING_TASKS_TOTAL} background tasks \
+ across all sessions; stop one first"
),
));
}
@@ -473,6 +531,14 @@ mod tests {
use super::*;
use std::time::Duration;
+ /// A real session row, because a background spawn now refuses to start for
+ /// a session that no longer exists.
+ fn new_session(st: &crate::state::AppState) -> String {
+ crate::sessions::create_session(&st.db, Some("test".into()), None, None, None, None)
+ .unwrap()
+ .id
+ }
+
#[tokio::test]
async fn retains_output_when_the_process_exits_before_supervision_starts() {
let dir = tempfile::tempdir().unwrap();
@@ -554,11 +620,15 @@ mod tests {
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 session_id = {
+ let st = state.lock().await;
+ new_session(&st)
+ };
let before_start = change_counter();
let id = spawn_background_task_detached(
&state,
- "session-1",
+ &session_id,
"sleep 30",
crate::tools::shell::default_shell_id(),
dir.path(),
@@ -578,7 +648,7 @@ mod tests {
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!(summaries[0].session_id, session_id);
assert_eq!(st.background_tasks.running_count(), 1);
}
@@ -629,9 +699,13 @@ mod tests {
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());
+ let session_id = {
+ let st = state.lock().await;
+ new_session(&st)
+ };
spawn_background_task_detached(
&state,
- "session-1",
+ &session_id,
"sleep 30",
crate::tools::shell::default_shell_id(),
dir.path(),
@@ -660,4 +734,157 @@ mod tests {
BackgroundTaskState::Stopped
);
}
+
+ /// The limit is per session: one full session must not block another, and
+ /// the error must name the session dimension rather than a global cap.
+ #[tokio::test]
+ async fn the_running_limit_is_per_session() {
+ let dir = tempfile::tempdir().unwrap();
+ let state = tokio::sync::Mutex::new(crate::state::AppState::open(dir.path()).unwrap());
+ let shell = crate::tools::shell::default_shell_id().to_string();
+ let (session_a, session_b) = {
+ let st = state.lock().await;
+ (new_session(&st), new_session(&st))
+ };
+
+ for _ in 0..MAX_RUNNING_TASKS_PER_SESSION {
+ spawn_background_task_detached(
+ &state,
+ &session_a,
+ "sleep 30",
+ &shell,
+ dir.path(),
+ None,
+ )
+ .await
+ .unwrap();
+ }
+
+ // The other session is untouched by A being full.
+ spawn_background_task_detached(&state, &session_b, "sleep 30", &shell, dir.path(), None)
+ .await
+ .expect("a full session must not block a different session");
+
+ let refused = spawn_background_task_detached(
+ &state,
+ &session_a,
+ "sleep 30",
+ &shell,
+ dir.path(),
+ None,
+ )
+ .await
+ .expect_err("the session limit must refuse one more");
+ assert_eq!(refused.0, "TOOL_FAILED");
+ assert!(
+ refused.1.contains("this session already runs"),
+ "the refusal must name the per-session limit, got: {}",
+ refused.1
+ );
+
+ {
+ let st = state.lock().await;
+ assert_eq!(
+ st.background_tasks.running_count_for(&session_a),
+ MAX_RUNNING_TASKS_PER_SESSION
+ );
+ assert_eq!(st.background_tasks.running_count_for(&session_b), 1);
+ // A refused spawn leaves no registry entry behind.
+ assert_eq!(
+ st.background_tasks.running_count(),
+ MAX_RUNNING_TASKS_PER_SESSION + 1
+ );
+ st.background_tasks.stop_session_running(&session_a);
+ st.background_tasks.stop_session_running(&session_b);
+ }
+ }
+
+ /// Deleting a session stops only that session's tasks; the signal must not
+ /// reach tasks another session owns.
+ #[tokio::test]
+ async fn stopping_a_session_spares_other_sessions() {
+ let dir = tempfile::tempdir().unwrap();
+ let state = tokio::sync::Mutex::new(crate::state::AppState::open(dir.path()).unwrap());
+ let shell = crate::tools::shell::default_shell_id().to_string();
+ let (session_a, session_b) = {
+ let st = state.lock().await;
+ (new_session(&st), new_session(&st))
+ };
+
+ spawn_background_task_detached(&state, &session_a, "sleep 30", &shell, dir.path(), None)
+ .await
+ .unwrap();
+ spawn_background_task_detached(&state, &session_b, "sleep 30", &shell, dir.path(), None)
+ .await
+ .unwrap();
+
+ let signalled = {
+ let st = state.lock().await;
+ st.background_tasks.stop_session_running(&session_a)
+ };
+ assert_eq!(
+ signalled, 1,
+ "exactly the deleted session's task is signalled"
+ );
+
+ // A is stopping, B keeps running — the signal did not fan out.
+ let mut a_settled = false;
+ for _ in 0..100 {
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ let st = state.lock().await;
+ if st.background_tasks.running_count_for(&session_a) == 0 {
+ a_settled = true;
+ assert_eq!(
+ st.background_tasks.running_count_for(&session_b),
+ 1,
+ "the other session's task must still be running"
+ );
+ break;
+ }
+ }
+ assert!(
+ a_settled,
+ "the deleted session's task reaches a terminal state"
+ );
+
+ {
+ let mut st = state.lock().await;
+ st.shutdown();
+ }
+ }
+
+ /// A task may not be started for a session that is already gone: it would
+ /// belong to no visible container and outlive its owner.
+ #[tokio::test]
+ async fn spawning_for_a_deleted_session_is_refused() {
+ let dir = tempfile::tempdir().unwrap();
+ let state = tokio::sync::Mutex::new(crate::state::AppState::open(dir.path()).unwrap());
+ let shell = crate::tools::shell::default_shell_id().to_string();
+ let session_id = {
+ let st = state.lock().await;
+ let id = new_session(&st);
+ crate::sessions::delete_session(&st.db, &id).unwrap();
+ id
+ };
+
+ let refused = spawn_background_task_detached(
+ &state,
+ &session_id,
+ "sleep 30",
+ &shell,
+ dir.path(),
+ None,
+ )
+ .await
+ .expect_err("a deleted session must not accept a background task");
+ assert_eq!(refused.0, "TOOL_FAILED");
+ assert!(
+ refused.1.contains("no longer exists"),
+ "the refusal must explain the missing session, got: {}",
+ refused.1
+ );
+
+ let st = state.lock().await;
+ assert_eq!(st.background_tasks.running_count(), 0);
+ }
}
diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rs
index 8e58a366f..6cc895b64 100644
--- a/crates/host-core/src/rpc/mod.rs
+++ b/crates/host-core/src/rpc/mod.rs
@@ -784,7 +784,13 @@ fn permission_parent_param(params: &Value) -> Result<Option<String>, JsonRpcErro
/// Drop the per-session files and caches that live outside SQLite. Shared by
/// `session.delete` and `projects.remove` so removing a project cleans up
/// exactly the same side data as deleting one session.
+///
+/// Background tasks belong here too: a deleted session must not leave its
+/// servers and watchers running, and this is the one place every deletion path
+/// already goes through. The stop is a signal only — the supervisor kills and
+/// reaps — so deletion neither blocks on a task settling nor fails with it.
fn drop_session_side_data(st: &AppState, id: &str) {
+ st.background_tasks.stop_session_running(id);
scratch::remove_session_dir(&st.data_dir, id);
visualizations::remove_session_dir(&st.data_dir, id);
review::remove_session(&st.data_dir, id);
diff --git a/crates/host-core/src/sessions.rs b/crates/host-core/src/sessions.rs
index 1fe85b381..f99efbab9 100644
--- a/crates/host-core/src/sessions.rs
+++ b/crates/host-core/src/sessions.rs
@@ -1534,6 +1534,17 @@ pub fn session_summary(db: &Database, id: &str) -> Result<Option<SessionSummary>
Ok(summary)
}
+/// Whether a session row still exists. Used to refuse work that would otherwise
+/// outlive its owning session and become unreachable — a background task
+/// started after its session was deleted belongs to nobody.
+pub fn session_exists(db: &Database, id: &str) -> Result<bool> {
+ Ok(db.conn().query_row(
+ "SELECT EXISTS(SELECT 1 FROM sessions WHERE id = ?1)",
+ params![id],
+ |row| row.get(0),
+ )?)
+}
+
/// Load a session detail with an optional renderer-facing message window.
/// The uncapped default is intentionally retained for the sidecar and for
/// mutation paths that need the canonical transcript. Renderer callers should
diff --git a/docs/implementation/background-task-session-dock.md b/docs/implementation/background-task-session-dock.md
new file mode 100644
index 000000000..2a8fab10c
--- /dev/null
+++ b/docs/implementation/background-task-session-dock.md
@@ -0,0 +1,153 @@
+# Session-scoped background tasks and a shared Task Dock
+
+Design plan and execution record for the change that makes background commands
+belong to their session and lets Todo and background tasks share one composer
+container.
+
+## Problem
+
+Background commands were host-global in three separate ways:
+
+1. `backgroundTasks.list` returned every task with no session filter, and the
+ renderer showed all of them in one bar. A task started in session B was
+ visible — and stoppable — from session A.
+2. Todo and the task bar were two stacked sibling surfaces in the composer, so a
+ running command competed with the plan and ask decision rows for the same
+ vertical space, and the bar had no empty state of its own.
+3. Deleting a session removed its scratch directory, review records, and file
+ hashes, but never its background processes. A deleted session's dev server
+ kept running until the whole app exited.
+
+Two smaller defects compounded these:
+
+- The concurrency limit was a single process-wide constant of 32, which is both
+ too high to be a per-session rule and unrelated to what a user sees.
+- "Removal" of a finished row was a renderer-only action with no state-layer
+ guard, so a caller holding a stale snapshot could drop a running task from the
+ list while its process lived.
+
+## Decisions
+
+| # | Decision | Rationale |
+| --- | --- | --- |
+| D1 | Concurrency limit is **per session, 10** | It is the limit a user can actually hit; refusals name it explicitly |
+| D2 | A **process-wide ceiling** stays as a host safety net | Many sessions must not add up to an exhausted host; reported separately so the two causes are distinguishable |
+| D3 | `backgroundTasks.list` stays **session-agnostic**; the renderer filters | Filtering is presentation. Adding a required parameter would force every consumer — including a future AI read path — to change |
+| D4 | A spawn is **refused when the session is already gone** | Otherwise the task belongs to no visible container and outlives its owner |
+| D5 | **Deleting** a session stops its running tasks; **archiving** does not | Archiving is a reversible marker; killing its processes would be a destructive side effect |
+| D6 | The stop is issued from `drop_session_side_data` | That is the one place all three deletion paths already converge |
+| D7 | Stop is **signal-and-return** | Deletion must not wait for a task to settle, and must not fail when a task cannot be killed |
+| D8 | Todo and tasks share **one container, tabs in the header** | Collapsing then hides only panels, so tabs stay reachable; the tab is never a second row competing with decisions |
+| D9 | The header is a row of **siblings**, not one button | A tab is a button; a button may not nest in a button and the click target would be ambiguous |
+| D10 | Tabs appear only when **both sides have content** | With one populated side, its panel renders alone and the tab list is not rendered at all |
+| D11 | Tab choice is **per-session memory**, and only a user action writes it | A tab the container picked must never overwrite what the user wanted |
+| D12 | A remembered tab whose side emptied **falls back** to the other side | Never render an empty panel |
+| D13 | A new task **raises a badge** on the tasks tab; it never steals the tab | The user's current tab is a deliberate choice |
+| D14 | Entering the tasks tab is **the only** badge clear point | There is exactly one path, so the badge cannot clear behind the user's back |
+| D15 | Clicking a tab while collapsed **also expands** | Otherwise the click appears to do nothing |
+| D16 | Removal is gated on a **terminal state in the state layer** | Hiding the control is not a guarantee; a stale snapshot must be refused too |
+| D17 | Removal is **view-only and issues no RPC** | The host keeps the task, its output, and its id; readability by id is unchanged |
+| D18 | Grace window, 256KB per stream, 16-entry history **unchanged** | They already bound the surface correctly; this change is about ownership, not retention |
+
+## Execution
+
+### P1 — host behaviour (`crates/host-core`)
+
+- Split the limit into `MAX_RUNNING_TASKS_PER_SESSION` (10) and
+ `MAX_RUNNING_TASKS_TOTAL` (64), with distinct refusal messages.
+- Add `running_count_for(session)` and `stop_session_running(session)` to the
+ registry. The stop takes no output lock, so a caller holding the state mutex
+ cannot deadlock against a task mid-write.
+- Add `sessions::session_exists` (one indexed `EXISTS`) and refuse a spawn for a
+ session that is gone.
+- Call `stop_session_running` from `drop_session_side_data`, which covers
+ `session.delete`, the sidebar batch delete, and `projects.remove`.
+
+### P2 — renderer data layer
+
+- `dock-state.ts` (new): per-session `chosenTab` / `newCount` / `collapsed`,
+ `resolveDockTab` / `resolveDockTabFor`, `observeSessionTasks`, `clearBadge`,
+ `chooseTab`, `selectTab`, `tasksPanelVisible`, `toggleCollapsed`,
+ `pruneDockView`.
+ - `selectTab` is the tab-click entry point and writes `chosenTab` and
+ `collapsed: false` together, which is what makes D15 hold: a click while
+ collapsed expands instead of swapping an invisible panel.
+ - `tasksPanelVisible` / `resolveDockTabFor` are the shared tab rule. The
+ render path and the badge path both call them, so "which panel is on
+ screen" has one definition rather than a copy that can drift. The hook
+ therefore takes the todo side from the container (`useBackgroundTasks(sessionId, todos)`)
+ instead of assuming it is absent.
+- `bar-visibility.ts`: `dismissTask` now takes the task and refuses `running`;
+ `canDismiss` exposes the same rule to the view.
+- `useBackgroundTasks(sessionId, todos)`: filters to the session, owns the badge
+ accounting, and exposes `remove(id)` which looks the task up rather than
+ trusting the caller.
+
+### P3 — UI
+
+- `TaskDock.tsx` (new): one container, one header carrying progress summary,
+ live count, tab list, and disclosure.
+- `TodoDock.tsx`: keeps the standalone dock (and its recovery + disclosure) and
+ additionally exports `TodoPanel` / `todoProgress` for the container.
+- `Composer.tsx`: mounts `TaskDock` under the existing
+ `activeSessionId && localToolsAllowed` gate.
+- `composer.css`: `.dock*` and `.task-*` replace `.background-tasks-bar` /
+ `.background-task*`. The task row is a vertical stack — `.task-band` (command +
+ action, never wrapping) above an optional `.task-output` — so a long command
+ ellipsizes on one line instead of pushing the metadata and its action onto a
+ second line.
+
+### P4 — i18n and docs
+
+- New `taskDock` block plus `headerCount` / `removeFailed` in all 9 locales.
+- `03-tools-and-permissions.md` (en + zh-CN): the "at most 32 tasks" and the
+ fixed "Todo, background commands, Plan/Ask" stack-order clauses are replaced by
+ the per-session rule, the shared container, the badge rule, the removal guard,
+ and the deletion linkage.
+- `06-host-rpc-protocol.md`: notes that `list` stays session-agnostic and that
+ removal issues no RPC.
+
+The chosen layout was prototyped before it was implemented, and the prototype is
+an uploaded artifact rather than repository content:
+
+<https://gist.github.com/Tioit-Wang/e70adfa435287f7673212e8a135343a6>
+
+It is one self-contained page with no build step and no sibling files, rendering
+the real token values and the real container markup: five tasks covering
+running / exited / failed / stopped (two with deliberately long commands), five
+todos, the live count, the badge, collapse, removal admission, and session
+deletion with cross-session isolation.
+
+The variants that were built to choose between are not kept: an inline tab list
+in the header won over an adaptive one (tabs drop to their own row when expanded)
+and over the previous stacked bar, because only the inline form keeps the tabs
+reachable while collapsed without a second header state.
+
+## Verification
+
+Local:
+
+- `cargo test -p host-core --locked background_tasks` — 7 passed, including three
+ new tests: the per-session limit and its refusal message, session-scoped stop
+ that spares other sessions, and the deleted-session spawn refusal.
+- `cargo fmt -p host-core -- --check`, `cargo clippy -p host-core --all-targets`
+- `pnpm build:js`, `pnpm --filter @pi-desktop/desktop typecheck`, `pnpm lint`
+- `node --test apps/desktop/test/background-tasks*.test.mjs` - 46 passed. The
+ new `background-tasks-dock-state.test.mjs` covers the view rules directly,
+ including D15 (a tab click while collapsed expands) and the shared tab rule
+ that keeps the badge from disagreeing with the visible panel.
+- `node scripts/check-style-tokens.mjs` - clean.
+
+Delegated to CI: the full desktop suite, because it contains macOS
+signing and notarization, plus Electron-binary cases that need the CI
+environment.
+
+## Compatibility
+
+- No wire parameter added; `backgroundTasks.list/output/stop` and the
+ `backgroundTasks.changed` payload are unchanged.
+- No new RPC. Removal stays renderer-local.
+- The 10s grace window, per-stream 256KB cap, and 16-entry finished history are
+ unchanged.
+- Removing the standalone bar is a UI change only: the container presents the
+ same rows, states, and actions.
diff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.md
index 9eeafbec2..133457018 100644
--- a/docs/spec/03-runtime/03-tools-and-permissions.md
+++ b/docs/spec/03-runtime/03-tools-and-permissions.md
@@ -491,28 +491,61 @@ Host execution baseline:
- `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.
+ tree, reports it through the composer's shared container, and stops it on
+ request or on app shutdown. Each stream keeps its last 256KB.
+- **Background tasks belong to the session that started them.** The session id is
+ fixed at spawn and never changes: switching, renaming, archiving, or restoring
+ a session does not re-home its tasks. A session runs at most **10** concurrent
+ background tasks; the refusal names that per-session limit. A separate
+ process-wide ceiling guards the host against many sessions adding up, and it is
+ reported as its own condition so the two causes stay distinguishable. A spawn
+ is refused when the session no longer exists, so a task can never start in a
+ session that would not be able to show it.
- 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.
+- **Todo and background tasks share one container** in the Composer, above the
+ Plan/Ask decision surfaces and the input. The container has a single header
+ carrying the todo progress summary, the running-task count, the tab list, and
+ the disclosure control; collapsing hides only the panels, so the tabs stay
+ reachable while collapsed. Tabs appear only when both sides have content: with
+ one side populated, that panel renders on its own and the tab list is not
+ rendered at all, and a container with nothing to show renders nothing. The
+ panel scrolls within `min(200px, 24vh)` so additional rows do not displace the
+ decision surfaces. Existing approval and Ask input gating is unchanged.
+- **The displayed tab is per-session view state.** It remembers the user's own
+ choice; a tab the container picked on its own never overwrites that choice. A
+ remembered tab whose side has become empty falls back to the other side. The
+ container gates on an active session that allows local tools, the same
+ condition the todo dock already used.
+- **A newly started task never steals the tab.** While the tasks panel is not the
+ one on screen, new tasks raise a count badge on its tab; entering that tab
+ clears the badge. Clicking a tab while collapsed also expands the container,
+ because otherwise the click would appear to do nothing.
- A finished background task is not permanent furniture. Its row lives for a
10-second grace window after the renderer observed the task end, so the exit
- code stays readable, then it leaves the bar. A task that had already finished
- when the renderer first loaded is registry history and never appears. Closing
- a finished row removes it immediately; an open output preview pins its row so
- a log being read cannot vanish underneath it. Closing is a view action only —
- the host keeps its bounded task history.
+ code stays readable, then it leaves the container. A task that had already
+ finished when the renderer first loaded is registry history and never appears.
+ An open output preview pins its row so a log being read cannot vanish
+ underneath it.
+- **Removal is a view action with a live-task guard.** Only a terminal task
+ (`exited`, `failed`, `stopped`) can be removed; a running task — including one
+ already sent a stop signal, which stays `running` until the supervisor settles
+ it — refuses removal in the state layer, not merely by hiding the control. The
+ host task, its output, and its id are untouched, so the record stays readable
+ by id until the host's own retention drops it. Removal is remembered per
+ session and is not persisted.
+- **Deleting a session stops its running background tasks.** Archiving does not:
+ archiving is a reversible marker, so killing its processes would be a
+ destructive side effect. Deletion signals stop and returns — the deletion does
+ not wait for a task to settle and does not fail when a task cannot be killed.
+ A deleted session's stopped tasks appear in no container, because the session
+ that would have showed them is gone.
- 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.
+ are ignored. Read/stop/remove 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 63e5c4c2a..1966ae230 100644
--- a/docs/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md
@@ -704,6 +704,15 @@ 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.
+`backgroundTasks.list` stays session-agnostic: it returns every task in the
+registry, each carrying its `sessionId`, and the renderer filters to the session
+on screen. Filtering is presentation, so the wire contract does not grow a
+session parameter and no consumer loses visibility of other sessions' work.
+Deleting a session signals its running tasks host-side; the deletion path does
+not wait for them to settle and does not fail when one cannot be killed.
+Removing a row in the UI is purely a view action and issues no RPC, so a removed
+task's output remains readable by id until the host's own retention drops it.
+
### Shells
- `commandShells.list`
- `settings.set` with a partial settings object; omitted fields are preserved,
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 ab5b12b3c..762724b4b 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
@@ -422,16 +422,40 @@ tool/protocol 名称,请求中单独携带固定的 shell ID。
- 用户中止和超时在返回之前终止整个进程树。
- `runInBackground: true` 让命令脱离本轮:shell 一启动就返回 `backgroundTaskId`,
不再套用超时,进程也不会被 `tools.abort` / `agent.abort` 终止。进程树归宿主
- 所有,通过输入框上方的运行中任务栏展示,可由用户停止或随应用退出而结束。
- 最多同时运行 32 个任务,每个输出流保留最后 256KB。
+ 所有,通过输入框上方的共用容器展示,可由用户停止或随应用退出而结束。
+ 每个输出流保留最后 256KB。
+- **后台任务归属启动它的会话。** 会话 ID 在启动时固定,之后不随切换、重命名、
+ 归档或恢复而改变。单个会话最多同时运行 **10** 个后台任务,拒绝时会指明这是
+ 每会话上限。另有一个进程级总量上限,仅用于防止多个会话叠加压垮宿主,并以
+ 独立原因上报,使两种拒绝可区分。会话已不存在时启动会被拒绝,任务不会落在一个
+ 无法展示它的会话里。
- 后台任务先排空输出,再发布最终状态,保留跨管道读取边界的 UTF-8 字符;
退出和停止时已排队的输出不会丢失。关闭宿主时发送停止信号不依赖输出锁。
-- 输入框上方保持 Todo、后台命令、Plan/Ask 决策、输入框的既有顺序,没有可配置的
- 显示优先级。任务列表在 `min(200px, 24vh)` 内滚动,不随任务数量无限增高;
- 审批和 Ask 对输入的既有约束不变。
+- **Todo 与后台任务共用输入框上方的一个容器**,位于 Plan/Ask 决策面与输入框之上。
+ 容器只有一个头部,承载待办进度摘要、运行中任务数、tab 列表与展开控件;折叠
+ 只隐藏面板,因此折叠时 tab 仍可点击。仅当两侧都有内容时才出现 tabs:只有一侧
+ 有内容时直接渲染该面板、不渲染 tab 列表;两侧都为空时容器不渲染。面板在
+ `min(200px, 24vh)` 内滚动,不随行数无限增高;审批和 Ask 对输入的既有约束不变。
+- **当前显示的 tab 是按会话记的视图状态。** 它记住用户自己的选择,容器自动选出的
+ tab 不会覆盖该选择;记忆的 tab 对应侧变空时回落到另一侧。容器沿用待办坞原有的
+ 门控:需要存在 active 会话且允许本地工具。
+- **新启动的任务不抢焦点。** 当后台任务面板不是当前可见面板时,新任务只在其 tab 上
+ 累加徽标;进入该 tab 即清零。折叠状态下点击 tab 会同时展开容器,否则点击看起来
+ 没有效果。
+- 终止的后台任务不长期驻留:渲染层观察到任务结束后保留 10 秒宽限窗以便读取退出码,
+ 随后离开容器。渲染层首次加载时已经结束的任务属于注册表历史,不再出现。正在查看的
+ 输出预览会钉住其行,避免日志在阅读时消失。
+- **移除是视图动作,但对运行中任务有准入限制。** 只有终止态(`exited`、`failed`、
+ `stopped`)可移除;运行中任务——包括已发出停止信号、但在 supervisor 落定前仍是
+ `running` 的任务——在状态层就被拒绝,而不只是隐藏按钮。宿主侧任务、输出与 id
+ 均不受影响,因此按 id 仍可读取,直到宿主自身的保留策略淘汰。移除记录按会话记忆,
+ 不持久化。
+- **删除会话会停止它的运行中后台任务。** 归档不会:归档是可恢复的标记,杀掉进程属于
+ 破坏性副作用。删除只发停止信号即返回——不等待任务落定,也不因任务杀不掉而失败。
+ 已删除会话中被停止的任务不出现在任何容器里,因为原本展示它的会话已不存在。
- 同时只展开一个输出预览;任务运行时,上次读取完成后每秒刷新一次,折叠的日志
不读取。预览最多展示 stdout 的 8,000 字符和 stderr 的 4,000 字符,忽略切换前
- 的过期响应。读取或停止失败会显示错误,停止操作可以重试。
+ 的过期响应。读取、停止或移除失败会显示错误,停止操作可以重试。
初始拒绝名单(可扩展):
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index 9eb27acdf..63e702617 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -714,6 +714,17 @@ export const de = {
stop: "Stoppen",
stopping: "Stoppe…",
dismiss: "Schließen",
+ headerCount: "{{count}} Hintergrundaufgaben",
+ removeFailed: "Diese Aufgabe konnte nicht entfernt werden.",
+ },
+ taskDock: {
+ title: "Aufgaben",
+ tabTodo: "To-do",
+ tabTasks: "Hintergrundaufgaben",
+ newTasks: "{{count}} neue Aufgaben",
+ runningCount: "{{count}} laufen",
+ expand: "{{label}} ausklappen",
+ collapse: "{{label}} einklappen",
},
planHistory: {
pending: "Genehmigung ausstehend",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index b27d15093..8b93bb542 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -726,6 +726,17 @@ export const en = {
stop: "Stop",
stopping: "Stopping…",
dismiss: "Dismiss",
+ headerCount: "{{count}} background tasks",
+ removeFailed: "Could not remove this task.",
+ },
+ taskDock: {
+ title: "Todo and background tasks",
+ tabTodo: "Todo",
+ tabTasks: "Background tasks",
+ newTasks: "{{count}} new tasks",
+ runningCount: "{{count}} running",
+ expand: "Expand {{label}}",
+ collapse: "Collapse {{label}}",
},
planHistory: {
pending: "Awaiting approval",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index afd7088c5..eca25feba 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -714,6 +714,17 @@ export const es = {
stop: "Detener",
stopping: "Deteniendo…",
dismiss: "Cerrar",
+ headerCount: "{{count}} tareas en segundo plano",
+ removeFailed: "No se pudo quitar esta tarea.",
+ },
+ taskDock: {
+ title: "Pendientes y tareas en segundo plano",
+ tabTodo: "Pendientes",
+ tabTasks: "Tareas en segundo plano",
+ newTasks: "{{count}} tareas nuevas",
+ runningCount: "{{count}} en ejecución",
+ expand: "Expandir {{label}}",
+ collapse: "Contraer {{label}}",
},
planHistory: {
pending: "Pendiente de aprobación",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index 29029a20d..a40b57527 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -714,6 +714,17 @@ export const fr = {
stop: "Arrêter",
stopping: "Arrêt…",
dismiss: "Fermer",
+ headerCount: "{{count}} tâches en arrière-plan",
+ removeFailed: "Impossible de retirer cette tâche.",
+ },
+ taskDock: {
+ title: "À faire et tâches en arrière-plan",
+ tabTodo: "À faire",
+ tabTasks: "Tâches en arrière-plan",
+ newTasks: "{{count}} nouvelles tâches",
+ runningCount: "{{count}} en cours",
+ expand: "Développer {{label}}",
+ collapse: "Réduire {{label}}",
},
planHistory: {
pending: "En attente d’approbation",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index 7c2f234c7..eedbbf607 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -723,6 +723,17 @@ export const ko = {
stop: "중지",
stopping: "중지 중…",
dismiss: "닫기",
+ headerCount: "백그라운드 작업 {{count}}개",
+ removeFailed: "이 작업을 제거하지 못했습니다.",
+ },
+ taskDock: {
+ title: "할 일 및 백그라운드 작업",
+ tabTodo: "할 일",
+ tabTasks: "백그라운드 작업",
+ newTasks: "새 작업 {{count}}개",
+ runningCount: "{{count}}개 실행 중",
+ expand: "{{label}} 펼치기",
+ collapse: "{{label}} 접기",
},
planHistory: {
pending: "승인 대기",
diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.ts
index 5aab4d996..a83bd2b0d 100644
--- a/packages/i18n/src/locales/pt-BR/index.ts
+++ b/packages/i18n/src/locales/pt-BR/index.ts
@@ -713,6 +713,17 @@ export const ptBR = {
stop: "Parar",
stopping: "Parando…",
dismiss: "Fechar",
+ headerCount: "{{count}} tarefas em segundo plano",
+ removeFailed: "Não foi possível remover esta tarefa.",
+ },
+ taskDock: {
+ title: "Pendências e tarefas em segundo plano",
+ tabTodo: "Pendências",
+ tabTasks: "Tarefas em segundo plano",
+ newTasks: "{{count}} tarefas novas",
+ runningCount: "{{count}} em execução",
+ expand: "Expandir {{label}}",
+ collapse: "Recolher {{label}}",
},
planHistory: {
pending: "Aguardando aprovação",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index 50667358f..3e84b7327 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -723,6 +723,17 @@ export const tr = {
stop: "Durdur",
stopping: "Durduruluyor…",
dismiss: "Kapat",
+ headerCount: "{{count}} arka plan görevi",
+ removeFailed: "Bu görev kaldırılamadı.",
+ },
+ taskDock: {
+ title: "Yapılacaklar ve arka plan görevleri",
+ tabTodo: "Yapılacaklar",
+ tabTasks: "Arka plan görevleri",
+ newTasks: "{{count}} yeni görev",
+ runningCount: "{{count}} çalışıyor",
+ expand: "{{label}} genişlet",
+ collapse: "{{label}} daralt",
},
planHistory: {
pending: "Onay bekleniyor",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index 705804666..a403f3a85 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -719,6 +719,17 @@ export const zhCN = {
stop: "停止",
stopping: "停止中…",
dismiss: "关闭",
+ headerCount: "{{count}} 个后台任务",
+ removeFailed: "无法移除这个任务。",
+ },
+ taskDock: {
+ title: "待办与后台任务",
+ tabTodo: "待办",
+ tabTasks: "后台任务",
+ newTasks: "{{count}} 个新任务",
+ runningCount: "{{count}} 个运行中",
+ expand: "展开{{label}}",
+ collapse: "收起{{label}}",
},
planHistory: {
pending: "待审批",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index f10c09338..94e14a621 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -719,6 +719,17 @@ export const zhTW = {
stop: "停止",
stopping: "停止中…",
dismiss: "關閉",
+ headerCount: "{{count}} 個背景任務",
+ removeFailed: "無法移除這個任務。",
+ },
+ taskDock: {
+ title: "待辦與背景任務",
+ tabTodo: "待辦",
+ tabTasks: "背景任務",
+ newTasks: "{{count}} 個新任務",
+ runningCount: "{{count}} 個執行中",
+ expand: "展開{{label}}",
+ collapse: "收合{{label}}",
},
planHistory: {
pending: "待審批",