Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
revert: bring back the caption's back/forward and restart buttons
rubenluetke10-beep49c6e5ac7861
diff --git a/jarvis/ui/web/frontend/src/components/layout/SectionNavButtons.test.tsx b/jarvis/ui/web/frontend/src/components/layout/SectionNavButtons.test.tsxindex 16b4208742..108733cc62 100644--- a/jarvis/ui/web/frontend/src/components/layout/SectionNavButtons.test.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/SectionNavButtons.test.tsx@@ -1,23 +1,76 @@-import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { SectionNavButtons } from "./SectionNavButtons";+import { resetSectionHistory } from "@/hooks/useSectionHistory";import { useEventStore } from "@/store/events";+function backButton(): HTMLButtonElement {+ return screen.getByTestId("section-nav-back") as HTMLButtonElement;+}++function forwardButton(): HTMLButtonElement {+ return screen.getByTestId("section-nav-forward") as HTMLButtonElement;+}+beforeEach(() => {+ resetSectionHistory();useEventStore.setState({ activeSection: "chats", solo: false });});afterEach(() => cleanup());describe("SectionNavButtons", () => {- it("renders nothing unless a sidebar toggle is offered", () => {+ it("renders back and forward with no sidebar toggle unless one is offered", () => {render(<SectionNavButtons />);- // The back/forward arrows are gone; with no toggle the group is empty.- expect(screen.queryByTestId("section-nav-buttons")).toBeNull();- expect(screen.queryByTestId("section-nav-back")).toBeNull();- expect(screen.queryByTestId("section-nav-forward")).toBeNull();+ expect(screen.getByTestId("section-nav-buttons")).toBeTruthy();+ expect(backButton()).toBeTruthy();+ expect(forwardButton()).toBeTruthy();+ expect(screen.queryByTestId("section-nav-sidebar")).toBeNull();+ });++ it("starts with both directions disabled and honest tooltips", () => {+ render(<SectionNavButtons />);++ expect(backButton().disabled).toBe(true);+ expect(forwardButton().disabled).toBe(true);+ // WHAT the tooltip says is the locale's business; that each button names+ // itself is not — a forward button that cannot explain itself (including+ // while disabled) teaches nothing.+ for (const button of [backButton(), forwardButton()]) {+ expect(button.getAttribute("aria-label")).toBeTruthy();+ expect(button.getAttribute("title")).toBe(button.getAttribute("aria-label"));+ }+ });++ it("walks back to the last visited section on every section", () => {+ render(<SectionNavButtons />);++ // The history is section-driven, not view-driven: whatever put the voice+ // section on screen (sidebar, voice command, deck jump) lands here too.+ act(() => useEventStore.getState().setActiveSection("agents"));+ act(() => useEventStore.getState().setActiveSection("dictation"));++ expect(backButton().disabled).toBe(false);+ fireEvent.click(backButton());+ expect(useEventStore.getState().activeSection).toBe("agents");+ });++ it("enables forward only after going back, and only for visited sections", () => {+ render(<SectionNavButtons />);++ act(() => useEventStore.getState().setActiveSection("agents"));+ act(() => useEventStore.getState().setActiveSection("dictation"));++ expect(forwardButton().disabled).toBe(true);++ fireEvent.click(backButton());+ expect(forwardButton().disabled).toBe(false);++ fireEvent.click(forwardButton());+ expect(useEventStore.getState().activeSection).toBe("dictation");+ expect(forwardButton().disabled).toBe(true);});it("offers the sidebar toggle with its state and hands the click to the shell", () => {@@ -52,9 +105,10 @@ describe("SectionNavButtons", () => {it("stays out of a detached solo window", () => {useEventStore.setState({ solo: true });- render(<SectionNavButtons sidebarToggle={{ collapsed: false, onToggle: () => {} }} />);+ render(<SectionNavButtons />);- // A solo window is pinned to its one view: there is no sidebar to toggle.+ // A solo window is pinned to its one view: back/forward would walk an+ // audience of one, and there is no sidebar to toggle.expect(screen.queryByTestId("section-nav-buttons")).toBeNull();});});diff --git a/jarvis/ui/web/frontend/src/components/layout/SectionNavButtons.tsx b/jarvis/ui/web/frontend/src/components/layout/SectionNavButtons.tsxindex 6dc9f6ffec..cd50abda1d 100644--- a/jarvis/ui/web/frontend/src/components/layout/SectionNavButtons.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/SectionNavButtons.tsx@@ -1,7 +1,8 @@-import { PanelLeftClose, PanelLeftOpen } from "lucide-react";+import { ArrowLeft, ArrowRight, PanelLeftClose, PanelLeftOpen } from "lucide-react";import { useT } from "@/i18n";import { useEventStore } from "@/store/events";+import { useSectionHistory } from "@/hooks/useSectionHistory";/** The sidebar toggle the caption owns — state lives in the shell (App.tsx). */export interface SidebarToggleState {@@ -11,20 +12,28 @@ export interface SidebarToggleState {testId?: string;}-/** The caption control's shape — theme tokens only, so it reads in light and dark mode alike. */+/**+ * One shape for every caption control in this group.+ *+ * Theme tokens only, so the buttons read in light and dark mode alike. A+ * disabled direction goes quiet (no hover lift, low opacity) but keeps its+ * tooltip — a forward button that cannot explain itself teaches nothing.+ */const NAV_BUTTON ="inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-muted-foreground " +"transition-colors hover:bg-secondary hover:text-foreground " +- "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring " ++ "disabled:cursor-default disabled:opacity-40 disabled:hover:bg-transparent disabled:hover:text-muted-foreground";/**- * The caption's leading control: the sidebar toggle.+ * The caption's leading navigation: sidebar toggle, back, forward.** Rendered at the far left of the window caption (see TopBar), so it is on* screen for EVERY section — chat, agents, voice, settings — with no second- * bar per view. The back/forward arrows that used to sit beside it were- * removed on 2026-10-01 as unused. A detached solo window is pinned to one- * view and has no sidebar, so the group stays out of it.+ * bar per view. Back/forward walk the visited-section history+ * (`useSectionHistory`): back returns to the previously visited section, and+ * forward only re-applies an undone step, staying disabled until one exists.+ * A detached solo window is pinned to one view, so the group stays out of it.*/export function SectionNavButtons({sidebarToggle,@@ -33,8 +42,12 @@ export function SectionNavButtons({} = {}) {const t = useT();const solo = useEventStore((s) => s.solo);+ const { canGoBack, canGoForward, goBack, goForward } = useSectionHistory();- if (solo || !sidebarToggle) return null;+ if (solo) return null;++ const backLabel = t("topbar.nav_back");+ const forwardLabel = t("topbar.nav_forward");return (<div@@ -43,20 +56,44 @@ export function SectionNavButtons({role="group"aria-label={t("sidebar.sections")}>+ {sidebarToggle && (+ <button+ type="button"+ data-testid={sidebarToggle.testId ?? "section-nav-sidebar"}+ onClick={sidebarToggle.onToggle}+ aria-expanded={!sidebarToggle.collapsed}+ aria-label={t(sidebarToggle.collapsed ? "sidebar.expand" : "sidebar.collapse")}+ title={t(sidebarToggle.collapsed ? "sidebar.expand" : "sidebar.collapse")}+ className={NAV_BUTTON}+ >+ {sidebarToggle.collapsed ? (+ <PanelLeftOpen className="h-4 w-4" aria-hidden />+ ) : (+ <PanelLeftClose className="h-4 w-4" aria-hidden />+ )}+ </button>+ )}+ <button+ type="button"+ data-testid="section-nav-back"+ onClick={() => goBack()}+ disabled={!canGoBack}+ aria-label={backLabel}+ title={backLabel}+ className={NAV_BUTTON}+ >+ <ArrowLeft className="h-4 w-4" aria-hidden />+ </button><buttontype="button"- data-testid={sidebarToggle.testId ?? "section-nav-sidebar"}- onClick={sidebarToggle.onToggle}- aria-expanded={!sidebarToggle.collapsed}- aria-label={t(sidebarToggle.collapsed ? "sidebar.expand" : "sidebar.collapse")}- title={t(sidebarToggle.collapsed ? "sidebar.expand" : "sidebar.collapse")}+ data-testid="section-nav-forward"+ onClick={() => goForward()}+ disabled={!canGoForward}+ aria-label={forwardLabel}+ title={forwardLabel}className={NAV_BUTTON}>- {sidebarToggle.collapsed ? (- <PanelLeftOpen className="h-4 w-4" aria-hidden />- ) : (- <PanelLeftClose className="h-4 w-4" aria-hidden />- )}+ <ArrowRight className="h-4 w-4" aria-hidden /></button></div>);diff --git a/jarvis/ui/web/frontend/src/components/layout/TopBar.test.tsx b/jarvis/ui/web/frontend/src/components/layout/TopBar.test.tsxindex e31207c625..f7eb806baa 100644--- a/jarvis/ui/web/frontend/src/components/layout/TopBar.test.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/TopBar.test.tsx@@ -1,8 +1,9 @@-import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { TopBar, TopBarActions } from "./TopBar";import { ThemeProvider } from "@/hooks/useTheme";import { useEventStore } from "@/store/events";+import { resetSectionHistory } from "@/hooks/useSectionHistory";vi.mock("@/hooks/useUpdate", () => ({useUpdate: () => ({ status: { managed: false, update_available: false } }),@@ -12,7 +13,7 @@ vi.mock("@/components/MascotGigi", () => ({}));// The caption is on every screen. Tests still name the section so a later-// change cannot quietly hide the caption on one of them.+// change cannot quietly hide Restart on one of them.beforeEach(() => {useEventStore.setState({activeSection: "dictation",@@ -51,17 +52,122 @@ describe("TopBar detach button", () => {});});+describe("TopBar restart button", () => {+ it("renders a restart button labelled in the active locale", () => {+ render(<TopBar />);+ expect(+ screen.getByRole("button", { name: /restart/i }),+ ).toBeTruthy();+ });++ it("requires a confirming second click before it calls the backend", () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValue({ ok: true, json: async () => ({ ok: true }) });+ vi.stubGlobal("fetch", fetchMock);++ render(<TopBar />);+ // First click only arms the confirmation — no network call yet.+ fireEvent.click(screen.getByRole("button", { name: /^restart$/i }));+ expect(fetchMock).not.toHaveBeenCalled();+ // The button now asks for confirmation.+ expect(+ screen.getByRole("button", { name: /confirm restart/i }),+ ).toBeTruthy();+ });++ it("POSTs to /api/settings/restart-app on the confirming click", async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValue({ ok: true, json: async () => ({ ok: true }) });+ vi.stubGlobal("fetch", fetchMock);++ render(<TopBar />);+ fireEvent.click(screen.getByRole("button", { name: /^restart$/i }));+ fireEvent.click(screen.getByRole("button", { name: /confirm restart/i }));++ await waitFor(() => {+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });+ const [url, opts] = fetchMock.mock.calls[0];+ expect(url).toBe("/api/settings/restart-app");+ expect(opts?.method).toBe("POST");+ });++ it("on 409 surfaces running missions and the next click forces the restart", async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce({+ ok: false,+ status: 409,+ json: async () => ({+ detail: {+ error: "missions_running",+ missions: [{ id: "a", title: "research" }],+ },+ }),+ })+ .mockResolvedValueOnce({ ok: true, json: async () => ({ ok: true }) });+ vi.stubGlobal("fetch", fetchMock);++ render(<TopBar />);+ fireEvent.click(screen.getByRole("button", { name: /^restart$/i }));+ fireEvent.click(screen.getByRole("button", { name: /confirm restart/i }));++ // The guard refused: the button now offers a force restart instead.+ await waitFor(() => {+ expect(+ screen.getByRole("button", { name: /restart anyway/i }),+ ).toBeTruthy();+ });++ // The first POST carried NO force flag (the mission was not killed).+ expect(fetchMock.mock.calls[0][0]).not.toContain("force");++ // Forcing it sends force=true.+ fireEvent.click(screen.getByRole("button", { name: /restart anyway/i }));+ await waitFor(() => {+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });+ expect(fetchMock.mock.calls[1][0]).toContain("force=true");+ });++ it("surfaces a failed restart instead of leaving the button stuck", async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValue({ ok: false, status: 503 });+ vi.stubGlobal("fetch", fetchMock);++ render(<TopBar />);+ fireEvent.click(screen.getByRole("button", { name: /^restart$/i }));+ fireEvent.click(screen.getByRole("button", { name: /confirm restart/i }));++ // After the failure the button returns to its idle, re-clickable state.+ await waitFor(() => {+ expect(+ screen.getByRole("button", { name: /^restart$/i }),+ ).toBeTruthy();+ });+ });+});+describe("TopBar section navigation", () => {beforeEach(() => {+ resetSectionHistory();useEventStore.setState({ activeSection: "chats", solo: false });});- it("carries no back/forward or restart buttons", () => {- render(<TopBar navToggle={{ collapsed: false, onToggle: () => {} }} />);- expect(screen.queryByTestId("section-nav-back")).toBeNull();- expect(screen.queryByTestId("section-nav-forward")).toBeNull();- expect(screen.queryByRole("button", { name: /restart/i })).toBeNull();- });+ it.each(["chats", "agents", "dictation", "visualization", "profile"] as const)(+ "shows back/forward in the caption on %s",+ (section) => {+ useEventStore.setState({ activeSection: section });+ render(<TopBar />);+ expect(screen.getByTestId("section-nav-buttons")).toBeTruthy();+ expect(screen.getByTestId("section-nav-back")).toBeTruthy();+ expect(screen.getByTestId("section-nav-forward")).toBeTruthy();+ cleanup();+ },+ );it("offers the sidebar toggle from the caption and hands the click to the shell", () => {const onToggle = vi.fn();@@ -75,30 +181,26 @@ describe("TopBar section navigation", () => {it("stays out of a detached solo window", () => {useEventStore.setState({ solo: true });- render(<TopBar navToggle={{ collapsed: false, onToggle: () => {} }} />);+ render(<TopBar />);expect(screen.queryByTestId("section-nav-buttons")).toBeNull();});});describe("TopBar caption on every section", () => {it.each(["chats", "agents", "agentic-ide-classic", "dictation"] as const)(- "keeps the theme toggle on %s",+ "keeps restart on %s",(section) => {useEventStore.setState({ activeSection: section });- render(- <ThemeProvider>- <TopBar />- </ThemeProvider>,- );+ render(<TopBar />);const caption = screen.getByTestId("window-caption");expect(caption.className).not.toContain("jarvis-shell-surface");expect(caption).toBeTruthy();- expect(screen.getByTestId("theme-toggle")).toBeTruthy();+ expect(screen.getByRole("button", { name: /^restart$/i })).toBeTruthy();expect(screen.queryByTestId("window-close")).toBeNull();},);- it("places the theme toggle immediately before the window buttons", async () => {+ it("places theme and restart immediately before the window buttons", async () => {(window as unknown as { pywebview?: { api: object } }).pywebview = { api: {} };vi.stubGlobal("fetch",@@ -115,8 +217,10 @@ describe("TopBar caption on every section", () => {);const minimize = await screen.findByTestId("window-minimize");+ const restart = screen.getByRole("button", { name: /^restart$/i });const theme = screen.getByTestId("theme-toggle");- expect(theme.compareDocumentPosition(minimize) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();+ expect(theme.compareDocumentPosition(restart) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();+ expect(restart.compareDocumentPosition(minimize) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();expect(minimize.compareDocumentPosition(screen.getByTestId("window-close")) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();delete (window as unknown as { pywebview?: unknown }).pywebview;diff --git a/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx b/jarvis/ui/web/frontend/src/components/layout/TopBar.tsxindex f37b671a2f..78097c361e 100644--- a/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx@@ -1,5 +1,5 @@import { useCallback, useEffect, useRef, useState } from "react";-import { AppWindow, Download } from "lucide-react";+import { AppWindow, Download, RotateCw } from "lucide-react";import { useEventStore, type SectionId } from "@/store/events";import {@@ -22,18 +22,19 @@ import { openExternalUrl } from "@/lib/openExternal";* The window's title strip, on every screen.** It is one thin row at the top of the window: drag the empty part to move- * the window, and the right end holds the app buttons (theme and detach)- * immediately beside minimize, maximize and close. Sections do not grow a- * second bar for those buttons. The title-strip restart button was removed on- * 2026-10-01 as unused.+ * the window, and the right end holds the app buttons (theme, restart, and+ * an update when one exists) immediately beside minimize, maximize and close.+ * Sections do not grow a second bar for those buttons.*- * The update flow still restarts the app: it POSTs to- * ``/api/settings/restart-app``, which spawns a detached relauncher (see- * jarvis/ui/relauncher.py). On a headless host that endpoint returns 503 and- * we recover with an honest toast. A restart tears down the whole app- * mid-task, so it honors the mission guard (409 → arm a force override)- * rather than killing live missions silently. We avoid a native- * ``window.confirm`` on purpose — it blocks the pywebview loop.+ * The backend already ships the self-restart machinery: restart and update+ * POST to ``/api/settings/restart-app``, which spawns a detached relauncher+ * (see jarvis/ui/relauncher.py). On a headless host that endpoint returns 503+ * and we recover with an honest toast.+ *+ * A restart tears down the whole app mid-task, so both buttons honor the+ * mission guard (409 → arm a force override) rather than killing live missions+ * silently. We avoid a native ``window.confirm`` on purpose — it blocks the+ * pywebview loop.*/const CONFIRM_TIMEOUT_MS = 4000;@@ -64,7 +65,7 @@ const CHROME_BUTTON =const CHROME_QUIET = "text-muted-foreground hover:bg-secondary hover:text-foreground";/**- * A control waiting for a second, deliberate click — the update panel's+ * A control waiting for a second, deliberate click — "confirm restart",* "restart anyway". Amber is the product's "needs attention" hue and this is* the only place in the shell that earns it: the guard already refused once.*/@@ -73,8 +74,9 @@ const CHROME_ARMED = "bg-warning text-background";export function TopBar({ navToggle }: {/*** The sidebar toggle the caption owns. State lives in the shell (App.tsx):- * the sidebar header no longer carries its own button — it moved here, into- * the empty caption corner, so it is on every section.+ * the sidebar header no longer carries its own button — it moved here, next+ * to back/forward, so the leading controls sit in the empty caption corner+ * on every section.*/navToggle?: { collapsed: boolean; onToggle: () => void };} = {}) {@@ -124,6 +126,7 @@ export function TopBarActions() {<><ThemeToggle /><DetachButton />+ <RestartButton /></>);}@@ -214,6 +217,123 @@ function DetachButton() {);}+function RestartButton() {+ const t = useT();+ const pushToast = useEventStore((s) => s.pushToast);+ const [confirming, setConfirming] = useState(false);+ const [restarting, setRestarting] = useState(false);+ // Set when the backend refused the restart (HTTP 409) because missions are+ // running: the next click resends the POST with ``force=true``.+ const [forceArmed, setForceArmed] = useState(false);+ const resetTimer = useRef<number | null>(null);++ const clearResetTimer = useCallback(() => {+ if (resetTimer.current !== null) {+ clearTimeout(resetTimer.current);+ resetTimer.current = null;+ }+ }, []);++ // Drop a pending "disarm" timer if the bar is ever unmounted.+ useEffect(() => clearResetTimer, [clearResetTimer]);++ async function doRestart(force: boolean) {+ clearResetTimer();+ setRestarting(true);+ try {+ const url = force+ ? "/api/settings/restart-app?force=true"+ : "/api/settings/restart-app";+ const res = await fetch(url, { method: "POST" });+ if (res.status === 409) {+ // The mission guard refused: a restart would kill live missions. Don't+ // kill them silently — surface the count and arm a force-restart so the+ // next click is the user's explicit override.+ let count = 0;+ try {+ const body = await res.json();+ count = body?.detail?.missions?.length ?? 0;+ } catch {+ /* malformed body — still arm the override */+ }+ setRestarting(false);+ setConfirming(false);+ setForceArmed(true);+ clearResetTimer();+ resetTimer.current = window.setTimeout(() => {+ setForceArmed(false);+ resetTimer.current = null;+ }, CONFIRM_TIMEOUT_MS);+ pushToast("warning", `${count} ${t("topbar.restart_missions_running")}`);+ return;+ }+ if (!res.ok) throw new Error(`restart-failed:${res.status}`);+ // On success the window goes away — keep the spinning state; never clear+ // it, so the user doesn't see the button flip back before the app dies.+ pushToast("info", t("topbar.restarting"));+ } catch {+ // Headless host (503) or a transient failure: recover the control so the+ // user isn't left with a dead button.+ setRestarting(false);+ setConfirming(false);+ setForceArmed(false);+ pushToast("error", t("topbar.restart_failed"));+ }+ }++ function onClick() {+ if (restarting) return;+ if (forceArmed) {+ // The guard already refused once; this click is the explicit override.+ void doRestart(true);+ return;+ }+ if (!confirming) {+ // First click only arms the confirmation; auto-disarm after a few+ // seconds so a stray click never leaves a primed restart button behind.+ setConfirming(true);+ clearResetTimer();+ resetTimer.current = window.setTimeout(() => {+ setConfirming(false);+ resetTimer.current = null;+ }, CONFIRM_TIMEOUT_MS);+ return;+ }+ void doRestart(false);+ }++ const label = restarting+ ? t("topbar.restarting")+ : forceArmed+ ? t("topbar.restart_force")+ : confirming+ ? t("topbar.restart_confirm")+ : t("topbar.restart");++ const showLabel = confirming || forceArmed || restarting;++ return (+ <button+ type="button"+ onClick={onClick}+ disabled={restarting}+ title={t("topbar.restart_hint")}+ aria-label={label}+ className={clsx(+ CHROME_BUTTON,+ showLabel ? "px-3" : "w-8 justify-center px-0",+ confirming || forceArmed ? CHROME_ARMED : CHROME_QUIET,+ )}+ >+ <RotateCw+ aria-hidden+ className={cn("h-4 w-4", restarting && "animate-spin")}+ />+ {showLabel ? label : null}+ </button>+ );+}+// The restart can fail transiently right after an apply (the backend is busy,// the desktop shell still warming) — retry briefly before giving up honestly.const RESTART_ATTEMPTS = 3;diff --git a/jarvis/ui/web/frontend/src/hooks/useSectionHistory.test.ts b/jarvis/ui/web/frontend/src/hooks/useSectionHistory.test.tsnew file mode 100644index 0000000000..c03531b819--- /dev/null+++ b/jarvis/ui/web/frontend/src/hooks/useSectionHistory.test.ts@@ -0,0 +1,137 @@+import { renderHook, act } from "@testing-library/react";+import { beforeEach, describe, expect, it } from "vitest";++import { useEventStore } from "@/store/events";+import {+ resetSectionHistory,+ useSectionHistory,+ useSectionNavHistory,+} from "./useSectionHistory";++function visit(section: "chats" | "agents" | "dictation" | "tasks"): void {+ act(() => useEventStore.getState().setActiveSection(section));+}++beforeEach(() => {+ resetSectionHistory();+ useEventStore.setState({ activeSection: "chats" });+});++describe("useSectionHistory", () => {+ it("starts with both directions disabled", () => {+ const { result } = renderHook(() => useSectionHistory());+ expect(result.current.canGoBack).toBe(false);+ expect(result.current.canGoForward).toBe(false);+ });++ it("goes back to the previously visited section", () => {+ const { result } = renderHook(() => useSectionHistory());+ visit("agents");+ visit("dictation");++ expect(result.current.canGoBack).toBe(true);++ let target: string | null = null;+ act(() => {+ target = result.current.goBack();+ });++ expect(target).toBe("agents");+ expect(useEventStore.getState().activeSection).toBe("agents");+ });++ it("keeps forward disabled until a step was undone", () => {+ const { result } = renderHook(() => useSectionHistory());+ visit("agents");+ visit("dictation");++ // Forward leads nowhere before any back step — a section never visited+ // cannot be gone to.+ expect(result.current.canGoForward).toBe(false);+ expect(useSectionNavHistory.getState().goForward()).toBeNull();++ act(() => {+ result.current.goBack();+ });+ expect(result.current.canGoForward).toBe(true);++ let target: string | null = null;+ act(() => {+ target = result.current.goForward();+ });+ expect(target).toBe("dictation");+ expect(useEventStore.getState().activeSection).toBe("dictation");+ // Redone: nothing left to redo.+ expect(result.current.canGoForward).toBe(false);+ });++ it("clears the redo stack on a new visit", () => {+ const { result } = renderHook(() => useSectionHistory());+ visit("agents");+ visit("dictation");++ act(() => {+ result.current.goBack();+ });+ expect(result.current.canGoForward).toBe(true);++ visit("tasks");+ expect(result.current.canGoForward).toBe(false);+ expect(result.current.canGoBack).toBe(true);+ });++ it("walks several steps back and forward in order", () => {+ const { result } = renderHook(() => useSectionHistory());+ visit("agents");+ visit("dictation");+ visit("tasks");++ act(() => {+ result.current.goBack();+ });+ expect(useEventStore.getState().activeSection).toBe("dictation");++ act(() => {+ result.current.goBack();+ });+ expect(useEventStore.getState().activeSection).toBe("agents");+ expect(result.current.canGoBack).toBe(true);++ act(() => {+ result.current.goBack();+ });+ expect(useEventStore.getState().activeSection).toBe("chats");+ expect(result.current.canGoBack).toBe(false);++ act(() => {+ result.current.goForward();+ });+ expect(useEventStore.getState().activeSection).toBe("agents");+ });++ it("ignores a back step with no history", () => {+ const { result } = renderHook(() => useSectionHistory());+ expect(result.current.canGoBack).toBe(false);++ let target: string | null = null;+ act(() => {+ target = result.current.goBack();+ });++ expect(target).toBeNull();+ expect(useEventStore.getState().activeSection).toBe("chats");+ });++ it("does not record re-selecting the same section", () => {+ const { result } = renderHook(() => useSectionHistory());+ visit("agents");+ visit("agents");++ act(() => {+ result.current.goBack();+ });+ // One genuine visit back — not stuck on a duplicate entry.+ expect(useEventStore.getState().activeSection).toBe("chats");+ expect(result.current.canGoBack).toBe(false);+ });+});diff --git a/jarvis/ui/web/frontend/src/hooks/useSectionHistory.ts b/jarvis/ui/web/frontend/src/hooks/useSectionHistory.tsnew file mode 100644index 0000000000..40e808f7ef--- /dev/null+++ b/jarvis/ui/web/frontend/src/hooks/useSectionHistory.ts@@ -0,0 +1,144 @@+import { useEffect } from "react";+import { create } from "zustand";++import { useEventStore, type SectionId } from "@/store/events";++/**+ * How many visited sections the back stack keeps.+ *+ * A section change is cheap (one id), but an unbounded array in a long-lived+ * desktop session is not — 50 steps back is far past what anyone reaches for.+ */+const MAX_HISTORY = 50;++interface SectionNavHistoryState {+ /** The section the stacks were last reconciled with. Null until observed. */+ current: SectionId | null;+ /** Older sections, oldest first. The last entry is where "back" goes. */+ past: SectionId[];+ /** Sections undone by "back", oldest first. Cleared by any new visit. */+ future: SectionId[];+ /** True while a back/forward navigation is in flight to the store. */+ navigating: boolean;+ /** Reconcile the stacks with a newly observed section. */+ record: (section: SectionId) => void;+ /** Step one section back. Returns the target, or null when there is none. */+ goBack: () => SectionId | null;+ /** Re-apply one undone step. Returns the target, or null when there is none. */+ goForward: () => SectionId | null;+ /** Test-only reset to a pristine history. */+ reset: () => void;+}++export const useSectionNavHistory = create<SectionNavHistoryState>((set, get) => ({+ current: null,+ past: [],+ future: [],+ navigating: false,++ record: (section) => {+ const { current, past, navigating } = get();+ if (current === section) {+ // A back/forward navigation lands here through the store subscription:+ // the stacks were already moved by goBack/goForward, so only clear the+ // in-flight flag instead of recording a duplicate visit.+ if (navigating) set({ navigating: false });+ return;+ }+ if (navigating) {+ // Same flight, observed before goBack/goForward set `current` — adopt.+ set({ current: section, navigating: false });+ return;+ }+ if (current === null) {+ set({ current: section });+ return;+ }+ set({+ current: section,+ past: [...past, current].slice(-MAX_HISTORY),+ future: [],+ });+ },++ goBack: () => {+ const { current, past, future } = get();+ if (current === null || past.length === 0) return null;+ const target = past[past.length - 1];+ if (target === current) {+ set({ past: past.slice(0, -1) });+ return get().goBack();+ }+ set({+ current: target,+ past: past.slice(0, -1),+ future: [current, ...future].slice(0, MAX_HISTORY),+ navigating: true,+ });+ useEventStore.getState().setActiveSection(target);+ return target;+ },++ goForward: () => {+ const { current, past, future } = get();+ if (current === null || future.length === 0) return null;+ const [target, ...rest] = future;+ if (target === current) {+ set({ future: rest });+ return get().goForward();+ }+ set({+ current: target,+ past: [...past, current].slice(-MAX_HISTORY),+ future: rest,+ navigating: true,+ });+ useEventStore.getState().setActiveSection(target);+ return target;+ },++ reset: () => set({ current: null, past: [], future: [], navigating: false }),+}));++/** Clear the navigation history — tests only. */+export function resetSectionHistory(): void {+ useSectionNavHistory.getState().reset();+}++export interface SectionHistory {+ canGoBack: boolean;+ canGoForward: boolean;+ goBack: () => SectionId | null;+ goForward: () => SectionId | null;+}++/**+ * Browser-style section history for the caption back/forward buttons.+ *+ * Mounted once per window (the TopBar owns it): every section change flows+ * through `activeSection` — sidebar clicks, voice commands, deck jumps, staged+ * requests — so watching the value covers all of them, where hooking one click+ * path would cover one. "Back" returns to the previously visited section and+ * "forward" only re-applies an undone step: it stays disabled until a step was+ * undone, and any new visit clears the redo stack, because a section never+ * visited cannot be gone to.+ */+export function useSectionHistory(): SectionHistory {+ const activeSection = useEventStore((s) => s.activeSection);+ const record = useSectionNavHistory((s) => s.record);+ const past = useSectionNavHistory((s) => s.past);+ const future = useSectionNavHistory((s) => s.future);+ const goBack = useSectionNavHistory((s) => s.goBack);+ const goForward = useSectionNavHistory((s) => s.goForward);++ useEffect(() => {+ record(activeSection);+ }, [activeSection, record]);++ return {+ canGoBack: past.length > 0,+ canGoForward: future.length > 0,+ goBack,+ goForward,+ };+}