Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(chat): hide the task dock with its last row (#1932)
Alger7a7b1679ed56
diff --git a/apps/desktop/src/components/TaskDock.tsx b/apps/desktop/src/components/TaskDock.tsxindex 1abd52fe4..ce5265928 100644--- a/apps/desktop/src/components/TaskDock.tsx+++ b/apps/desktop/src/components/TaskDock.tsx@@ -43,7 +43,6 @@ export function TaskDock({ sessionId }: { sessionId: string }) {// whether a new task needs a badge.const {tasks,- sessionTasks,activeTab,openTasksTab,openTodoTab,@@ -60,8 +59,13 @@ export function TaskDock({ sessionId }: { sessionId: string }) {stoppingIds,} = useBackgroundTasks(sessionId, todos);- const hasTasks = sessionTasks.length > 0;- const running = sessionTasks.filter((task) => task.state === "running").length;+ // Presence, the live count, and the header count describe the rows the+ // container can render. Host-core keeps a finished task in its registry after+ // the row's grace window closes, so deriving them from the session's full+ // task list would leave a permanent "1 background tasks" header with no row+ // to stop, dismiss, or read.+ const hasTasks = tasks.length > 0;+ const running = tasks.filter((task) => task.state === "running").length;const showTabs = hasTodo && hasTasks;if (!hasTodo && !hasTasks && !error) return null;@@ -75,7 +79,7 @@ export function TaskDock({ sessionId }: { sessionId: string }) {const headerText = progress? progress.label- : t("backgroundTasks.headerCount", { count: sessionTasks.length });+ : t("backgroundTasks.headerCount", { count: tasks.length });return (<div className={`dock${collapsed ? "" : " is-expanded"}`}>diff --git a/apps/desktop/src/features/chat/background-tasks/useBackgroundTasks.ts b/apps/desktop/src/features/chat/background-tasks/useBackgroundTasks.tsindex 01c7a6fa7..c70998aa3 100644--- a/apps/desktop/src/features/chat/background-tasks/useBackgroundTasks.ts+++ b/apps/desktop/src/features/chat/background-tasks/useBackgroundTasks.ts@@ -31,22 +31,22 @@ type Failure = "load" | "output" | "stop" | "remove";/*** 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+ * The task side describes the rows the container can render, and the todo side+ * comes from the 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[],+ rows: readonly BackgroundTaskSummary[],todos: readonly SessionTodo[],): DockSides {let runningTasks = 0;- for (const task of sessionTasks) {+ for (const task of rows) {if (task.state === "running") runningTasks += 1;}return {hasTodo: todos.length > 0,- hasTasks: sessionTasks.length > 0,+ hasTasks: rows.length > 0,runningTasks,inProgressTodos: todos.filter((todo) => todo.status === "in_progress").length,};@@ -112,7 +112,9 @@ export function useBackgroundTasks(const seen = knownIds.current.get(currentSession) ?? new Set<string>();setDockView((current) => {const state = sessionDockState(current, currentSession);- const tasksVisible = tasksPanelVisible(state, sidesFor(sessionTasks, todosRef.current));+ // The same description the render path uses: the rows the container+ // can actually show decide whether its tasks panel is on screen.+ const tasksVisible = tasksPanelVisible(state, sidesRef.current);const folded = observeSessionTasks(current, currentSession, sessionTasks, {knownIds: seen,tasksVisible,@@ -154,11 +156,9 @@ export function useBackgroundTasks(}, []);// 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;+ // is not hidden because it ended: it simply belongs elsewhere. Registry+ // history is kept out of the container by the visible-row rule below, not by+ // dropping tasks from this list: removal and output reads still need them.const sessionTasks = useMemo(() => (sessionId ? allTasks.filter((task) => task.sessionId === sessionId) : []),[allTasks, sessionId],@@ -281,14 +281,18 @@ export function useBackgroundTasks(}, []);const dock = sessionDockState(dockView, sessionId);- const sides = sidesFor(sessionTasks, todos);+ // The tab and badge rules see the rows the container can render, so a task+ // that already left it cannot decide which panel is on screen.+ const sides = sidesFor(visibleTasks, todos);const activeTab: DockTab = resolveDockTabFor(dock, sides);+ // The poll loop outlives a render, so it reads the container's description of+ // itself through a ref rather than capturing one snapshot of it.+ const sidesRef = useRef(sides);+ sidesRef.current = sides;return {- /** Tasks belonging to the session on screen, after the grace window. */+ /** The session's rows the container may render: live, in grace, or pinned. */tasks: visibleTasks,- /** Every task of this session, regardless of the grace window. */- sessionTasks,activeTab,openTasksTab,openTodoTab,diff --git a/apps/desktop/test/background-tasks-dock-render.test.mjs b/apps/desktop/test/background-tasks-dock-render.test.mjsnew file mode 100644index 000000000..bbeaf5976--- /dev/null+++ b/apps/desktop/test/background-tasks-dock-render.test.mjs@@ -0,0 +1,151 @@+import assert from "node:assert/strict";+import test from "node:test";+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { createInstance } from "i18next";+import { I18nextProvider } from "react-i18next";+import { catalogs } from "@pi-desktop/i18n";+import { createServer } from "vite";+import { fileURLToPath } from "node:url";++/*+ * What the shared container shows once a task is over.+ *+ * host-core keeps a finished task in its registry so its output stays readable+ * and the renderer can show the exit code for the grace window; the entry is+ * not deleted when the row leaves the container. The container must therefore+ * answer to the rows it can render, never to the registry's full session list —+ * otherwise a stopped or self-exited command leaves a permanent+ * "1 background tasks" header with no row to stop, dismiss, or read.+ *+ * Rendered through the real container, store, and locale with the task data+ * layer stubbed, so the assertion is what the user actually sees.+ */++const ROOT = fileURLToPath(new URL("..", import.meta.url));+const HOOK = fileURLToPath(new URL("./helpers/background-tasks-hook.stub.ts", import.meta.url));++const task = (id, state, exitCode) => ({+ id,+ sessionId: "session-dock-render",+ command: `pnpm dev ${id}`,+ commandShellId: "pwsh",+ state,+ elapsedMs: 2_000,+ ...(exitCode === undefined ? {} : { exitCode }),+});++async function withDockRender(run) {+ const server = await createServer({+ root: ROOT,+ configFile: false,+ server: { middlewareMode: true, hmr: false, ws: false },+ esbuild: { jsx: "automatic" },+ appType: "custom",+ optimizeDeps: { noDiscovery: true, include: [] },+ plugins: [+ {+ // The registry read is the container's data source; stub it only.+ name: "background-tasks-hook-stub",+ enforce: "pre",+ resolveId(source) {+ return source.endsWith("background-tasks/useBackgroundTasks") ? HOOK : null;+ },+ },+ ],+ });+ try {+ const { TaskDock } = await server.ssrLoadModule("/src/components/TaskDock.tsx");+ const { useAppStore } = await server.ssrLoadModule("/src/stores/app-store.ts");+ const i18n = createInstance();+ await i18n.init({ lng: "en", resources: { en: { translation: catalogs.en } } });+ const render = (fixture) => {+ const sessionId = "session-dock-render";+ // The checklist side is the only other content the container can show.+ const snapshot = fixture.todos+ ? { sessionId, revision: 1, updatedAt: 1, todos: fixture.todos }+ : undefined;+ Object.assign(useAppStore.getInitialState(), {+ sessionTodos: snapshot ? { [sessionId]: snapshot } : {},+ });+ globalThis.__piDockFixture = fixture;+ return renderToStaticMarkup(+ createElement(+ I18nextProvider,+ { i18n },+ createElement(TaskDock, { sessionId: "session-dock-render" }),+ ),+ );+ };+ await run({ render });+ } finally {+ delete globalThis.__piDockFixture;+ await server.close();+ }+}++test("the container disappears with its last row, even though the host still lists the finished task", async () => {+ await withDockRender(({ render }) => {+ const finished = task("t-stopped", "stopped");+ const html = render({ tasks: [], sessionTasks: [finished] });+ assert.equal(+ html,+ "",+ "a task the container can no longer render must not keep the container — or a task count — on screen",+ );+ });+});++test("registry history alone never keeps a header, even with several finished tasks", async () => {+ await withDockRender(({ render }) => {+ const html = render({+ tasks: [],+ sessionTasks: [task("t-1", "exited", 0), task("t-2", "failed", 1), task("t-3", "stopped")],+ });+ assert.equal(html, "");+ });+});++test("the container counts the rows it can render", async () => {+ await withDockRender(({ render }) => {+ const running = task("t-running", "running");+ const html = render({ tasks: [running], sessionTasks: [running, task("t-old", "exited", 0)] });+ assert.match(html, /class="dock/);+ assert.match(html, /1 background tasks/, "the header counts the renderable row");+ assert.match(html, /1 running/);+ assert.match(html, /pnpm dev t-running/);+ assert.doesNotMatch(+ html,+ /pnpm dev t-old/,+ "a row the container may not render must not appear",+ );+ });+});++test("a finished row inside its grace window still counts", async () => {+ await withDockRender(({ render }) => {+ const finished = task("t-grace", "exited", 0);+ const html = render({ tasks: [finished], sessionTasks: [finished, task("t-hidden", "stopped")] });+ assert.match(html, /1 background tasks/);+ assert.doesNotMatch(html, /running/, "a finished row raises no live count");+ assert.match(html, /pnpm dev t-grace/);+ });+});++test("a checklist keeps the container without inventing an empty task panel", async () => {+ await withDockRender(({ render }) => {+ const html = render({+ tasks: [],+ sessionTasks: [task("t-stopped", "stopped")],+ todos: [{ content: "ship the dock fix", status: "in_progress", priority: "high" }],+ });+ assert.match(html, /class="todo-dock-list"/);+ assert.match(html, /ship the dock fix/);+ assert.doesNotMatch(html, /class="task-list"/, "no renderable row means no task panel");+ assert.doesNotMatch(+ html,+ /role="tablist"/,+ "tabs appear only while both sides have content",+ );+ });+});diff --git a/apps/desktop/test/helpers/background-tasks-hook.stub.ts b/apps/desktop/test/helpers/background-tasks-hook.stub.tsnew file mode 100644index 000000000..4761b9b03--- /dev/null+++ b/apps/desktop/test/helpers/background-tasks-hook.stub.ts@@ -0,0 +1,47 @@+import type { BackgroundTaskSummary } from "../../src/lib/api";++/**+ * Stand-in for `useBackgroundTasks` in the container's render tests.+ *+ * The hook's data source is the host registry, which is not reachable from a+ * static render, so the test installs the two lists the hook keeps apart:+ * `tasks` are the rows the container may render, `sessionTasks` are every+ * registry entry the host still lists for the session — including finished+ * tasks it keeps as history after their grace window closed. Keeping both in+ * the fixture is the point: the rendered container must answer only to+ * `tasks`.+ */+export type DockFixture = {+ tasks: BackgroundTaskSummary[];+ sessionTasks: BackgroundTaskSummary[];+ collapsed?: boolean;+};++declare global {+ // Installed by the render test before each render.+ var __piDockFixture: DockFixture | undefined;+}++export function useBackgroundTasks() {+ const fixture = globalThis.__piDockFixture ?? { tasks: [], sessionTasks: [] };+ return {+ tasks: fixture.tasks,+ sessionTasks: fixture.sessionTasks,+ activeTab: "tasks" as const,+ openTasksTab() {},+ openTodoTab() {},+ collapsed: fixture.collapsed ?? true,+ setCollapsed() {},+ badge: 0,+ badgeText: "0",+ expandedId: null,+ output: null,+ toggleOutput() {},+ stop() {},+ remove() {+ return true;+ },+ error: null,+ stoppingIds: new Set<string>(),+ };+}