Skip to content

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.

@ fix(agentic-ide): come back to the workspace you left, not to the wizard

Ruben Lütked5ac3dc04b3c
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
index 9f25e07886..75b389615a 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
@@ -293,7 +293,7 @@ afterEach(() => {
function renderGrid(session = BASE, extra: Record<string, unknown> = {}) {
const onSessionChanged = vi.fn();
const onClose = vi.fn();
- render(
+ const props = (override: Record<string, unknown>) => (
<AgenticGrid
session={session}
focusMode={false}
@@ -301,9 +301,16 @@ function renderGrid(session = BASE, extra: Record<string, unknown> = {}) {
onClose={onClose}
onSessionChanged={onSessionChanged}
{...extra}
- />,
+ {...override}
+ />
);
- return { onSessionChanged, onClose };
+ const view = render(props({}));
+ // Re-render the SAME grid with a prop changed — for the tests that assert on
+ // what a live grid does when something about it changes, as opposed to how a
+ // fresh one starts up.
+ const rerender = (override: Record<string, unknown>) =>
+ view.rerender(props(override));
+ return { onSessionChanged, onClose, rerender };
}
describe("pane actions", () => {
@@ -1533,6 +1540,37 @@ describe("session recaps", () => {
);
});
+ /**
+ * The grid outlives the section being on screen (see MainView): it is hidden
+ * rather than unmounted so its terminals survive a trip to another view. That
+ * makes "is anyone looking?" a real question — `/recaps` walks every pane's
+ * replay buffer through the summarizer, every five seconds, on the same event
+ * loop that carries the wake microphone.
+ */
+ it("asks nothing at all while its section is off screen", async () => {
+ renderGrid(BASE, { onScreen: false });
+ // The read on mount is the poller's first act, and the interval is created
+ // beside it — so no read here means no interval either, and a hidden
+ // workspace costs the backend nothing.
+ await act(async () => {});
+
+ expect(api.fetchTerminalRecaps).not.toHaveBeenCalled();
+ });
+
+ it("catches its headers up the moment it comes back", async () => {
+ const { rerender } = renderGrid(BASE, { onScreen: false });
+ await act(async () => {});
+ expect(api.fetchTerminalRecaps).not.toHaveBeenCalled();
+
+ // Not merely "resumes polling" — reads AT ONCE. A grid that spent five
+ // minutes hidden has headers five minutes old, and waiting out another
+ // interval before correcting them is why this is asserted separately.
+ rerender({ onScreen: true });
+ await waitFor(() =>
+ expect(api.fetchTerminalRecaps).toHaveBeenCalledWith("ide_test"),
+ );
+ });
+
it("hands each pane the recap that came back for it", async () => {
vi.mocked(api.fetchTerminalRecaps).mockResolvedValue({
workspace_id: "ide_test",
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
index 077b42178b..1e0ee68dcc 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
@@ -41,6 +41,7 @@ import {
import { cn } from "@/lib/utils";
import { useT } from "@/i18n";
import { useThemeValue } from "@/hooks/useTheme";
+import { useDocumentVisible } from "@/hooks/useDocumentVisible";
import { useResizablePane } from "@/hooks/useResizablePane";
import { PaneResizer } from "@/components/layout/PaneResizer";
import { useEventStore } from "@/store/events";
@@ -117,6 +118,16 @@ interface AgenticGridProps {
accounts?: IdeAccountState[];
/** The settings panel changed the workspace state — the owner applies it. */
onStateChanged?: (state: IdeState) => void;
+ /**
+ * Is the section holding this grid the one on screen?
+ *
+ * The Agentic IDE is hidden rather than unmounted when the user goes to
+ * another section, so this grid stays alive behind whatever they are looking
+ * at — and its polling would otherwise go on asking the backend what a dozen
+ * panes are doing for nobody. Defaults to true, which is what a grid rendered
+ * on its own has always been.
+ */
+ onScreen?: boolean;
/**
* The row of open workspaces, rendered INSIDE this workspace's toolbar.
*
@@ -391,6 +402,7 @@ export function AgenticGrid({
onStateChanged,
workspaceBar,
appActions,
+ onScreen = true,
}: AgenticGridProps) {
const t = useT();
const pushToast = useEventStore((s) => s.pushToast);
@@ -482,11 +494,24 @@ export function AgenticGrid({
* it. A failed read keeps whatever the headers already say: the backend
* warming up, or a workspace closed in another window, is not a reason to
* blank eight labels — and the recap is a convenience, never the pane.
+ *
+ * Also bound to whether anyone can SEE the headers, which is two independent
+ * questions with one answer: the window may be minimized or behind another
+ * (`visible`), and the user may be in another section of the app while this
+ * grid stays mounted behind it (`onScreen` — see MainView). A poll that runs
+ * regardless is not free: `/recaps` walks every pane's replay buffer through
+ * the summarizer, on the same event loop that carries the wake microphone.
+ *
+ * Re-mounting the effect on the way back is what catches the headers up: a
+ * grid that spent five minutes hidden skipped every tick, and its first act
+ * on return is a fresh read rather than a five-second-old sentence.
*/
+ const documentVisible = useDocumentVisible();
+ const pollRecaps = onScreen && documentVisible;
useEffect(() => {
+ if (!pollRecaps) return;
let cancelled = false;
const pull = async () => {
- if (typeof document !== "undefined" && document.hidden) return;
try {
const answer = await fetchTerminalRecaps(session.id);
if (cancelled) return;
@@ -499,19 +524,11 @@ export function AgenticGrid({
};
void pull();
const timer = window.setInterval(() => void pull(), RECAP_POLL_MS);
- // A window coming back to the foreground has skipped every tick it spent
- // hidden, so its headers are as old as the time away. Catch up at once
- // rather than showing minute-old work for another five seconds.
- const onVisible = () => {
- if (!document.hidden) void pull();
- };
- document.addEventListener("visibilitychange", onVisible);
return () => {
cancelled = true;
window.clearInterval(timer);
- document.removeEventListener("visibilitychange", onVisible);
};
- }, [session.id]);
+ }, [session.id, pollRecaps]);
/*
* The three things a user may do about a pane's recap.
@@ -1257,7 +1274,7 @@ export function AgenticGrid({
and were never told to carry on, and the one click that tells them.
The pane headers catch up on their own — a continued agent starts
printing, and the recap poll above is already watching for that. */}
- <ContinueInterrupted busy={busy || working} />
+ <ContinueInterrupted busy={busy || working} onScreen={onScreen} />
{/* Which subscription the next terminal spends, and the way to change
it without leaving the workspace. */}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/ContinueInterrupted.tsx b/jarvis/ui/web/frontend/src/components/agentic/ContinueInterrupted.tsx
index 5d0297dcd4..387e3bdb24 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/ContinueInterrupted.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/ContinueInterrupted.tsx
@@ -36,6 +36,7 @@ import { AlertCircle, FolderGit2, Loader2, PlayCircle, Terminal, X } from "lucid
import { useT } from "@/i18n";
import { cn } from "@/lib/utils";
+import { useDocumentVisible } from "@/hooks/useDocumentVisible";
import {
continueInterrupted,
fetchInterrupted,
@@ -64,6 +65,12 @@ const EMPTY: InterruptedOffer = {
interface ContinueInterruptedProps {
/** Disable the control while the workspace is busy with something else. */
busy?: boolean;
+ /**
+ * Is the section holding this control the one on screen? The workspace stays
+ * mounted behind other sections (see MainView), and this poll runs for as
+ * long as it is open. Defaults to true — the behaviour before it could hide.
+ */
+ onScreen?: boolean;
}
/** One line of plain language for what the button will actually do. */
@@ -206,7 +213,10 @@ function PaneRow({
);
}
-export function ContinueInterrupted({ busy = false }: ContinueInterruptedProps) {
+export function ContinueInterrupted({
+ busy = false,
+ onScreen = true,
+}: ContinueInterruptedProps) {
const t = useT();
const pushToast = useEventStore((s) => s.pushToast);
const [offer, setOffer] = useState<InterruptedOffer>(EMPTY);
@@ -229,27 +239,27 @@ export function ContinueInterrupted({ busy = false }: ContinueInterruptedProps)
}
}, []);
+ /*
+ * Poll only while there is somebody to show a count to.
+ *
+ * Two ways for that to be false and one answer for both: the window is
+ * minimized or behind another (`documentVisible`), or the user is in another
+ * section while this workspace stays mounted behind it (`onScreen`).
+ *
+ * Binding the effect to that answer rather than checking it inside the tick
+ * is also the catch-up: coming back rebuilds the effect, and the first thing
+ * a rebuilt effect does is read. That matters here more than most — the
+ * restart that interrupts the panes is exactly the event that happens while
+ * nobody is looking.
+ */
+ const documentVisible = useDocumentVisible();
+ const polling = onScreen && documentVisible;
useEffect(() => {
- const pull = () => {
- // A hidden window has nobody to show a count to, and this poll runs for
- // as long as the workspace is open.
- if (typeof document !== "undefined" && document.hidden) return;
- void refresh();
- };
- pull();
- const timer = window.setInterval(pull, POLL_MS);
- // Coming back to the foreground skips every tick spent hidden — and the
- // restart that interrupts the panes is exactly the event that happens while
- // nobody is looking.
- const onVisible = () => {
- if (!document.hidden) void refresh();
- };
- document.addEventListener("visibilitychange", onVisible);
- return () => {
- window.clearInterval(timer);
- document.removeEventListener("visibilitychange", onVisible);
- };
- }, [refresh]);
+ if (!polling) return;
+ void refresh();
+ const timer = window.setInterval(() => void refresh(), POLL_MS);
+ return () => window.clearInterval(timer);
+ }, [refresh, polling]);
const run = async (names?: string[]) => {
// Which panes this press owns, marked BEFORE the request goes out.
diff --git a/jarvis/ui/web/frontend/src/components/layout/MainView.sticky.test.tsx b/jarvis/ui/web/frontend/src/components/layout/MainView.sticky.test.tsx
new file mode 100644
index 0000000000..94df6a1668
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/layout/MainView.sticky.test.tsx
@@ -0,0 +1,146 @@
+/**
+ * The Agentic IDE survives a section change; every other section does not.
+ *
+ * Why this test exists (2026-07-29): sections were all switched the same way —
+ * one mounted, the rest thrown away — and for a section whose contents are
+ * live terminals that is destructive rather than economical. Leaving the IDE
+ * disposed a dozen xterm instances and their sockets; coming back built new
+ * ones and had the backend replay every pane's screen into them, and until
+ * that finished the freshly mounted view knew of no workspace at all and drew
+ * its ONBOARDING WIZARD in front of a workspace that had never stopped running
+ * (maintainer report, ~3 s of "start over" on the way back).
+ *
+ * So the assertions here are about identity, not appearance: the same instance
+ * must still be there afterwards, un-remounted, merely hidden — and it must be
+ * TOLD it is hidden, because a `display: none` subtree cannot measure that for
+ * itself and its polling would otherwise run for nobody.
+ */
+import { act, cleanup, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { MainView } from "@/components/layout/MainView";
+import { useEventStore } from "@/store/events";
+
+/**
+ * Mount/render bookkeeping for the stubbed IDE.
+ *
+ * `mounts` is what proves the instance survived: a remount is invisible in the
+ * DOM (the same markup comes back) and shows up only as a second mount.
+ */
+const ide = vi.hoisted(() => ({ mounts: 0, lastOnScreen: undefined as unknown }));
+
+vi.mock("@/views/AgenticIdeView", async () => {
+ const { useEffect } = await vi.importActual<typeof import("react")>("react");
+ return {
+ AgenticIdeView: ({ onScreen }: { onScreen?: boolean }) => {
+ ide.lastOnScreen = onScreen;
+ useEffect(() => {
+ ide.mounts += 1;
+ }, []);
+ return <div data-testid="ide-stub">workspace</div>;
+ },
+ };
+});
+
+// The default section, statically imported by MainView — stubbed so this test
+// pays for none of the chat surface.
+vi.mock("@/views/ChatsView", () => ({
+ ChatsView: () => <div data-testid="chats-stub">chats</div>,
+ ViewHeader: () => null,
+}));
+
+vi.mock("@/views/OutputsView", () => ({
+ OutputsView: () => <div data-testid="outputs-stub">outputs</div>,
+}));
+
+function goTo(section: string) {
+ act(() => {
+ useEventStore.getState().setActiveSection(section as never);
+ });
+}
+
+beforeEach(() => {
+ ide.mounts = 0;
+ ide.lastOnScreen = undefined;
+ goTo("chats");
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe("MainView — the Agentic IDE is sticky", () => {
+ it("does not mount the IDE for a user who never opens it", async () => {
+ render(<MainView />);
+ await screen.findByTestId("chats-stub");
+
+ // Sticky, not always-mounted: the section is only worth keeping once it has
+ // something to keep.
+ expect(screen.queryByTestId("sticky-agentic-ide")).toBeNull();
+ expect(ide.mounts).toBe(0);
+ });
+
+ it("keeps the same instance mounted across a section change", async () => {
+ render(<MainView />);
+ goTo("agentic-ide");
+ await screen.findByTestId("ide-stub");
+ expect(ide.mounts).toBe(1);
+
+ goTo("outputs");
+ await screen.findByTestId("outputs-stub");
+
+ // Still there, and still the FIRST one: a second mount would mean a dozen
+ // terminals were torn down and rebuilt for a section change.
+ expect(screen.getByTestId("ide-stub")).toBeTruthy();
+ expect(ide.mounts).toBe(1);
+
+ goTo("agentic-ide");
+ await waitFor(() =>
+ expect(screen.queryByTestId("outputs-stub")).toBeNull(),
+ );
+ expect(ide.mounts).toBe(1);
+ });
+
+ it("hides the IDE while another section is on screen", async () => {
+ render(<MainView />);
+ goTo("agentic-ide");
+ await screen.findByTestId("ide-stub");
+
+ const sticky = screen.getByTestId("sticky-agentic-ide");
+ expect(sticky.className).not.toContain("hidden");
+ expect(sticky.getAttribute("aria-hidden")).toBe("false");
+
+ goTo("outputs");
+ await screen.findByTestId("outputs-stub");
+
+ expect(sticky.className).toContain("hidden");
+ expect(sticky.getAttribute("aria-hidden")).toBe("true");
+ });
+
+ it("tells the IDE whether it is the section on screen", async () => {
+ render(<MainView />);
+ goTo("agentic-ide");
+ await screen.findByTestId("ide-stub");
+ expect(ide.lastOnScreen).toBe(true);
+
+ goTo("outputs");
+ await screen.findByTestId("outputs-stub");
+
+ // The view cannot measure this itself once it is `display: none`, and its
+ // pollers need the answer to stop asking the backend about panes nobody is
+ // looking at.
+ await waitFor(() => expect(ide.lastOnScreen).toBe(false));
+ });
+
+ it("shows only the IDE while it is the active section", async () => {
+ render(<MainView />);
+ goTo("agentic-ide");
+ await screen.findByTestId("ide-stub");
+
+ // Two live copies of a workspace would fight over every pane's output
+ // stream, so the ordinary switch must render nothing at all here.
+ expect(screen.queryByTestId("chats-stub")).toBeNull();
+ expect(screen.queryByTestId("outputs-stub")).toBeNull();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/layout/MainView.tsx b/jarvis/ui/web/frontend/src/components/layout/MainView.tsx
index 6688619025..d0e7ef48aa 100644
--- a/jarvis/ui/web/frontend/src/components/layout/MainView.tsx
+++ b/jarvis/ui/web/frontend/src/components/layout/MainView.tsx
@@ -2,11 +2,15 @@ import {
lazy,
Suspense,
useEffect,
+ useState,
type ComponentType,
type LazyExoticComponent,
} from "react";
import { useEventStore } from "@/store/events";
+import { cn } from "@/lib/utils";
import { ViewErrorBoundary } from "@/components/ViewErrorBoundary";
+// Type-only, so the section's chunk stays split out of the entry bundle.
+import type { AgenticIdeViewProps } from "@/views/AgenticIdeView";
// The default section is the one view that must be on screen the moment React
// mounts, so it stays statically linked into the entry chunk. Every other view
// is code-split below.
@@ -29,14 +33,36 @@ import { ChatsView } from "@/views/ChatsView";
type ViewModule = { default: ComponentType };
type ViewLoader = () => Promise<ViewModule>;
-/** Loaders for every split view, in the order the idle prefetch warms them. */
-const prefetchQueue: ViewLoader[] = [];
+/**
+ * Loaders for every split view, in the order the idle prefetch warms them.
+ *
+ * Typed as returning `unknown` because warming a chunk only cares that the
+ * import RAN — the module's shape is the caller's business, and pinning the
+ * props-free shape here would keep `lazyPropView` out of the warm-up.
+ */
+const prefetchQueue: (() => Promise<unknown>)[] = [];
function lazyView(loader: ViewLoader): LazyExoticComponent<ComponentType> {
prefetchQueue.push(loader);
return lazy(loader);
}
+/**
+ * The same, for the one view the shell has to tell something.
+ *
+ * Sections are otherwise self-contained and take no props — a section knows
+ * which one it is and reads the rest from the store. The Agentic IDE is the
+ * exception because it is the one section that stays mounted while hidden, and
+ * "are you the section on screen right now?" is a question only the shell can
+ * answer for it (see `MainView`).
+ */
+function lazyPropView<P>(
+ loader: () => Promise<{ default: ComponentType<P> }>,
+): LazyExoticComponent<ComponentType<P>> {
+ prefetchQueue.push(loader);
+ return lazy(loader);
+}
+
// Ordered roughly by how likely a section is to be opened, so the warm-up
// front-loads what the user reaches for first. Views are named exports, hence
// the explicit unwrap into the { default } shape React.lazy expects.
@@ -57,7 +83,10 @@ const ApiKeysView = lazyView(() =>
const ExtensionsView = lazyView(() =>
import("@/views/ExtensionsView").then((m) => ({ default: m.ExtensionsView })),
);
-const AgenticIdeView = lazyView(() =>
+// The prop type is named rather than inferred: inferring it from the loader's
+// return value is circular (the loader's contextual type is what depends on it),
+// and TypeScript resolves that by falling back to `never`.
+const AgenticIdeView = lazyPropView<AgenticIdeViewProps>(() =>
import("@/views/AgenticIdeView").then((m) => ({ default: m.AgenticIdeView })),
);
const TasksView = lazyView(() =>
@@ -190,11 +219,32 @@ function ViewLoadingFallback() {
return <div className="h-full w-full" aria-busy="true" />;
}
+/** The one section that is hidden rather than unmounted — see `MainView`. */
+const STICKY_SECTION = "agentic-ide";
+
/**
- * Main area to the right of the sidebar. All views are switched the classic
- * way (one view active, the others unmounted) — this saves render load and is
+ * Main area to the right of the sidebar. Views are switched the classic way
+ * (one view active, the others unmounted) — this saves render load and is
* semantically fine because they rehydrate their state from React Query / the
* store.
+ *
+ * The Agentic IDE is the ONE exception, and it is not an optimisation: its
+ * panes are live terminals, and unmounting them is destructive in a way no
+ * other section's state is. Leaving the section tore down a dozen xterm
+ * instances and their sockets, and coming back rebuilt every one of them —
+ * each re-attach replays up to `REPLAY_LIMIT_CHARS` of raw output per pane, so
+ * a workspace of eleven terminals pushed well over a megabyte through the main
+ * thread just to show what was already on screen three seconds earlier. Worse,
+ * the remounted view starts out knowing of no workspace at all, so the first
+ * thing the user saw on the way back was the onboarding wizard asking which
+ * folder to open — in front of a workspace that had never stopped running
+ * (maintainer report 2026-07-29).
+ *
+ * So once opened, it stays mounted and is hidden with CSS instead. That costs
+ * nothing while it is away: the panes' `IntersectionObserver` already treats
+ * `display: none` as off-screen and parks their output (see AgenticTerminal),
+ * and their `ResizeObserver` re-fits them when they come back. Sticky rather
+ * than always-mounted so a user who never opens the section never pays for it.
*/
export function MainView() {
const active = useEventStore((s) => s.activeSection);
@@ -202,18 +252,55 @@ export function MainView() {
useIdleViewPrefetch();
+ const stickyActive = active === STICKY_SECTION;
+ const [stickyMounted, setStickyMounted] = useState(stickyActive);
+ useEffect(() => {
+ if (stickyActive) setStickyMounted(true);
+ }, [stickyActive]);
+
return (
- <ViewErrorBoundary
- viewName={active}
- resetKey={active}
- onRecover={() => setActive("chats")}
- >
- {/* Keyed on the active section so switching away from a still-loading
- view cannot leave the previous section's fallback on screen. */}
- <Suspense key={active} fallback={<ViewLoadingFallback />}>
- <SwitchOnActiveSection active={active} />
- </Suspense>
- </ViewErrorBoundary>
+ <>
+ {stickyMounted && (
+ <div
+ className={cn("h-full w-full", !stickyActive && "hidden")}
+ data-testid="sticky-agentic-ide"
+ // Hidden from assistive technology too while it is off screen: the
+ // panes stay in the DOM, and a screen reader walking a workspace's
+ // worth of terminal output behind the visible section would be a
+ // wall of noise nobody asked for.
+ aria-hidden={!stickyActive}
+ >
+ {/* Its own boundary, un-keyed: this instance must survive every
+ section change, which is the entire point of keeping it. */}
+ <ViewErrorBoundary
+ viewName={STICKY_SECTION}
+ resetKey={STICKY_SECTION}
+ onRecover={() => setActive("chats")}
+ >
+ <Suspense fallback={<ViewLoadingFallback />}>
+ {/* Told rather than measured: a `display: none` subtree has no
+ geometry to read, and the view's background polling has to
+ know it is off screen so it can stop asking the backend what
+ a dozen panes are doing while nobody is watching them. */}
+ <AgenticIdeView onScreen={stickyActive} />
+ </Suspense>
+ </ViewErrorBoundary>
+ </div>
+ )}
+ {!stickyActive && (
+ <ViewErrorBoundary
+ viewName={active}
+ resetKey={active}
+ onRecover={() => setActive("chats")}
+ >
+ {/* Keyed on the active section so switching away from a still-loading
+ view cannot leave the previous section's fallback on screen. */}
+ <Suspense key={active} fallback={<ViewLoadingFallback />}>
+ <SwitchOnActiveSection active={active} />
+ </Suspense>
+ </ViewErrorBoundary>
+ )}
+ </>
);
}
@@ -288,8 +375,13 @@ function SwitchOnActiveSection({ active }: { active: string }) {
return <FeedbackView />;
case "agent-instructions":
return <AgentInstructionsView />;
- case "agentic-ide":
- return <AgenticIdeView />;
+ // Deliberately nothing: the Agentic IDE is rendered by the STICKY branch in
+ // `MainView` above, which keeps it mounted across section changes. This
+ // switch is not rendered at all while that section is active, so reaching
+ // here would mean two live copies of a workspace's terminals — the second
+ // of which would steal every pane's output stream from the first.
+ case STICKY_SECTION:
+ return null;
default:
return <ChatsView />;
}
diff --git a/jarvis/ui/web/frontend/src/hooks/useDocumentVisible.ts b/jarvis/ui/web/frontend/src/hooks/useDocumentVisible.ts
new file mode 100644
index 0000000000..023d9e414c
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/hooks/useDocumentVisible.ts
@@ -0,0 +1,40 @@
+/**
+ * Is the document on screen at all — or is the window minimized, behind another
+ * one, or sitting in a background tab?
+ *
+ * Existed inline in every polling effect that cared, as a `document.hidden`
+ * check at the top of the tick plus a `visibilitychange` listener to catch up
+ * afterwards. Both halves are needed and it is the second one that gets
+ * forgotten: skipping ticks while hidden is only correct if something reads
+ * again on the way back, or the screen keeps showing whatever it last managed
+ * to fetch for as long as the window stays open.
+ *
+ * As a piece of STATE rather than a check, a poller expresses the same thing by
+ * binding its effect to the answer: hidden tears the interval down, visible
+ * builds it again — and building it again is the catch-up read, for free.
+ *
+ * Answers `true` where there is no `document` (SSR, a bare test environment),
+ * because "cannot tell" must not silently switch polling off everywhere.
+ */
+import { useEffect, useState } from "react";
+
+function currentlyVisible(): boolean {
+ if (typeof document === "undefined") return true;
+ return document.hidden !== true;
+}
+
+export function useDocumentVisible(): boolean {
+ const [visible, setVisible] = useState(currentlyVisible);
+
+ useEffect(() => {
+ if (typeof document === "undefined") return;
+ const onChange = () => setVisible(currentlyVisible());
+ // Read once on mount too: the document may have been hidden between the
+ // initial state above and this effect running.
+ onChange();
+ document.addEventListener("visibilitychange", onChange);
+ return () => document.removeEventListener("visibilitychange", onChange);
+ }, []);
+
+ return visible;
+}
diff --git a/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx b/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx
index 99efa7ebd6..a07e3d9dc6 100644
--- a/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx
@@ -298,6 +298,58 @@ afterEach(() => {
vi.clearAllMocks();
});
+describe("Agentic IDE — before the first read lands", () => {
+ /**
+ * A workspace the view has not heard about yet is NOT "no workspace".
+ *
+ * This view used to fall straight through to the wizard while it waited, so
+ * a user returning to a running workspace was met by step 1 of the onboarding
+ * flow asking which folder the agents should work in — in front of eleven
+ * agents that had never stopped (maintainer report 2026-07-29). Being told to
+ * wait a moment is a far better answer than being told to start over.
+ */
+ it("shows a neutral placeholder rather than the onboarding wizard", async () => {
+ // Both reads hang: this is the state the view is in on every cold start,
+ // held open so it can be asserted on.
+ vi.mocked(api.fetchIdeState).mockReturnValue(new Promise(() => {}));
+ vi.mocked(api.fetchIdeAgents).mockReturnValue(new Promise(() => {}));
+
+ render(<AgenticIdeView />);
+
+ expect(await screen.findByTestId("agentic-ide-loading")).toBeTruthy();
+ // The two things that would read as "there is nothing open here".
+ expect(screen.queryByText(/which folder should the agents work in/i)).toBeNull();
+ expect(screen.queryByRole("button", { name: /next/i })).toBeNull();
+ });
+
+ it("draws a running workspace without waiting for the CLI sweep", async () => {
+ // `/agents` starts one subprocess per registered CLI and takes over a
+ // second on a cold cache. The grid never asks what is installed, so it must
+ // not wait for the answer — this is the other half of the 3 s on the way
+ // back into the section.
+ vi.mocked(api.fetchIdeAgents).mockReturnValue(new Promise(() => {}));
+ vi.mocked(api.fetchIdeState).mockResolvedValue(
+ stateWith(sessionWith(["Mika", "Nova"])),
+ );
+
+ render(<AgenticIdeView />);
+
+ expect(await screen.findByTestId("pane-Mika")).toBeTruthy();
+ });
+
+ it("holds the placeholder until the wizard has agents to offer", async () => {
+ // The reverse: with no workspace open, the wizard's agent step is the whole
+ // point of the sweep, so showing the wizard before it lands would offer an
+ // empty list.
+ vi.mocked(api.fetchIdeAgents).mockReturnValue(new Promise(() => {}));
+
+ render(<AgenticIdeView />);
+
+ expect(await screen.findByTestId("agentic-ide-loading")).toBeTruthy();
+ expect(screen.queryByRole("button", { name: /next/i })).toBeNull();
+ });
+});
+
describe("Agentic IDE wizard", () => {
it("starts on the folder step and blocks Next until a folder is picked", async () => {
render(<AgenticIdeView />);
diff --git a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx
index cef7d46035..310271f55c 100644
--- a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx
+++ b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx
@@ -112,7 +112,23 @@ function buildPlan(
});
}
-export function AgenticIdeView() {
+export interface AgenticIdeViewProps {
+ /**
+ * Is this view the section currently on screen?
+ *
+ * Unlike every other section, this one is HIDDEN rather than unmounted when
+ * the user goes elsewhere (see MainView) — its panes are live terminals, and
+ * tearing them down to rebuild them seconds later is what put an onboarding
+ * wizard in front of a running workspace. Being hidden with CSS means the
+ * view cannot measure whether anyone can see it, so the shell says so.
+ *
+ * Defaults to true: rendered on its own (tests, any future embedding), a view
+ * that is there IS on screen, which is how this behaved before it could hide.
+ */
+ onScreen?: boolean;
+}
+
+export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {
const t = useT();
const pushToast = useEventStore((s) => s.pushToast);
const setActiveSection = useEventStore((s) => s.setActiveSection);
@@ -157,12 +173,27 @@ export function AgenticIdeView() {
const [offer, setOffer] = useState<ResumeOffer | null>(null);
const refresh = useCallback(async () => {
+ /*
+ * Both reads start together, but the workspace is applied WITHOUT waiting
+ * for the agent sweep.
+ *
+ * `/agents` starts one subprocess per registered CLI — 1.1-1.4 s on a cold
+ * cache, and on Windows every one of those is an npm shim (see
+ * `_DETECTION_TTL_S` in jarvis/workspace/agents.py). Awaiting the two
+ * together meant a running workspace could not be drawn until a question
+ * about which CLIs are installed had been answered, which is a question the
+ * grid never asks. The wizard needs the answer; the grid does not, and the
+ * grid is what the user is coming back to.
+ */
+ const sweep = fetchIdeAgents().then(setMeta, () => {
+ // Swallowed on purpose, and it costs exactly what it did when this was
+ // one `Promise.all`: `meta` stays as it was, so the wizard opens without
+ // its install callouts and the agent step offers whatever it had before.
+ // A failed sweep must not take the workspace state down with it — that
+ // state is the half of this read that the user is here for.
+ });
try {
- const [state, agents] = await Promise.all([
- fetchIdeState(),
- fetchIdeAgents(),
- ]);
- setMeta(agents);
+ const state = await fetchIdeState();
setSession(state.session);
setWorkspaces(state.workspaces ?? []);
setMaxWorkspaces(state.max_workspaces ?? 6);
@@ -189,6 +220,12 @@ export function AgenticIdeView() {
} catch {
/* backend still warming or headless — keep whatever we had */
} finally {
+ // What `loading` gates is the WIZARD (see the render below), and a wizard
+ // shown before the sweep lands is one whose agent step has nothing to
+ // offer — so the placeholder holds until it is in. A workspace that is
+ // already open never waits for this: the running branch is chosen before
+ // `loading` is read at all.
+ await sweep;
setLoading(false);
}
}, []);
@@ -308,7 +345,11 @@ export function AgenticIdeView() {
});
observer.observe(node);
return () => observer.disconnect();
- }, [session]);
+ // Both states decide WHICH element (if any) carries `shellRef`, so both have
+ // to re-run the measurement. `loading` is easy to forget and silent when it
+ // is: the first read finds no node, gives up, and the preview then promises
+ // an arrangement computed from a width of zero for the rest of the session.
+ }, [session, loading]);
useEffect(() => {
if (!session || session.focus_mode || optedOutRef.current) return;
@@ -696,6 +737,7 @@ export function AgenticIdeView() {
onSessionChanged={setSession}
accounts={ideAccounts}
onStateChanged={applyStateFromSettings}
+ onScreen={onScreen}
/>
</div>
{modeIntroFor === session.id && (
@@ -712,6 +754,38 @@ export function AgenticIdeView() {
);
}
+ /*
+ * ------------------------------------------------------------- still asking
+ *
+ * Before the first read lands, this view does not know whether a workspace is
+ * open — and "I do not know yet" must not be drawn as "there is none".
+ *
+ * It used to fall straight through to the wizard and merely add a line of
+ * "Checking this machine…" to it, which put the four-step ONBOARDING flow
+ * ("Which folder should the agents work in?") in front of a user whose eleven
+ * agents were running the whole time (maintainer report 2026-07-29). Being
+ * asked to start over is a far worse answer than being told to wait a moment,
+ * and the two states are indistinguishable to whoever is reading the screen.
+ *
+ * `loading` is a first-read flag: it is set once, cleared in `refresh`, and
+ * never raised again — so this never covers a workspace that is already up,
+ * and later refreshes redraw in place.
+ */
+ if (loading) {
+ return (
+ <div
+ className="flex h-full w-full items-center justify-center"
+ data-testid="agentic-ide-loading"
+ aria-busy="true"
+ >
+ <div className="flex items-center gap-2 text-sm text-muted-foreground">
+ <Loader2 className="h-4 w-4 animate-spin" />
+ Checking this machine…
+ </div>
+ </div>
+ );
+ }
+
// ------------------------------------------------------------------ wizard
const canAdvance =
(step === 0 && Boolean(folder)) ||
@@ -753,13 +827,6 @@ export function AgenticIdeView() {
<StepRail step={step} />
- {loading && (
- <div className="flex items-center gap-2 text-sm text-muted-foreground">
- <Loader2 className="h-4 w-4 animate-spin" />
- Checking this machine…
- </div>
- )}
-
{meta && !meta.terminal_available && (
<Callout tone="error">
This machine has no usable terminal backend, so agent panes cannot