feat(daemon): collapse workspace noise into a "show hidden" section

Discovery returns every pi session directory ever seen, so the console opened on
47 rows on this machine: 20 ghosts (cwd deleted) and 21 scratch dirs under /tmp
next to the real projects. Every row now carries a derived, non-persisted
`visibility`/`visibilityReason`; nothing is filtered server-side, so
`/workspace/<id>` deep links and the chat page's id lookup still resolve.

Precedence: explicit `hidden` wins; a live instance, `pinned` or `trusted`
rescues a row; then temp paths (`PI2_WORKSPACE_HIDE_TEMP`, on), ghosts
(`PI2_WORKSPACE_HIDE_GHOSTS`, on), outside roots (`PI2_WORKSPACE_HIDE_OUTSIDE_ROOTS`,
off) and staleness (`PI2_WORKSPACE_STALE_DAYS`, off). Measured on real data:
47 → 26 default rows, 0 openable rows lost.

The browser collapses the secondary rows behind a persisted toggle and dims them
with a reason badge; `workspace.add` now clears `hidden`.
This commit is contained in:
yuez committed 2026-10-23 10:08:15 +08:00
1 parent 58e247644d
commit 64a1a98c1f
12 files changed
+888 -38

No files matched your search

+73
View File
@@ -0,0 +1,73 @@
/**
* Workspace-noise policy, browser side.
*
* The daemon classifies every row (`visibility: "default" | "secondary"` +
* `visibilityReason`) but never filters the list, so `/workspace/<id>` deep
* links keep resolving. This module only partitions the served rows for
* list/picker surfaces: `primary` is what the user normally wants, `secondary`
* is noise (explicitly hidden, ghosts, temp dirs, …) behind a toggle.
*/
import type { WorkspaceInfo } from "@/lib/protocol";
/** Persisted toggle: "show N hidden" on the workspaces page. */
export const SHOW_ALL_STORAGE_KEY = "pi2-workspaces-show-all";
export interface WorkspacePartition {
primary: WorkspaceInfo[];
secondary: WorkspaceInfo[];
}
/** Legacy daemons omit `visibility`; `hidden` alone still means secondary. */
export function isSecondary(workspace: WorkspaceInfo): boolean {
if (workspace.visibility === "secondary") return true;
return workspace.hidden === true;
}
/** Reason for the badge; `hidden` is inferred for pre-classification daemons. */
export function visibilityReason(workspace: WorkspaceInfo): string | null {
if (typeof workspace.visibilityReason === "string" && workspace.visibilityReason.length > 0) {
return workspace.visibilityReason;
}
return workspace.hidden === true ? "hidden" : null;
}
/** i18n key for the reason badge (or `null` for a default row). */
export function reasonLabelKey(workspace: WorkspaceInfo): string | null {
const reason = visibilityReason(workspace);
return reason === null ? null : `workspaces.reason.${reason}`;
}
/** Split served rows into the normal list and the collapsed noise. */
export function partitionWorkspaces(list: readonly WorkspaceInfo[], _showAll = false): WorkspacePartition {
const primary: WorkspaceInfo[] = [];
const secondary: WorkspaceInfo[] = [];
for (const workspace of list) {
if (isSecondary(workspace)) secondary.push(workspace);
else primary.push(workspace);
}
return { primary, secondary };
}
/** How many rows the "show N hidden" toggle would reveal (0 hides the toggle). */
export function countSecondary(list: readonly WorkspaceInfo[]): number {
return partitionWorkspaces(list).secondary.length;
}
/** `localStorage` read; default off and any failure means off. */
export function readShowAll(): boolean {
try {
return localStorage.getItem(SHOW_ALL_STORAGE_KEY) === "1";
} catch {
return false;
}
}
/** `localStorage` write; storage failures must never break the page. */
export function writeShowAll(showAll: boolean): void {
try {
localStorage.setItem(SHOW_ALL_STORAGE_KEY, showAll ? "1" : "0");
} catch {
// private mode / quota: the in-memory toggle still works
}
}
+18 -1
View File
@@ -10,6 +10,7 @@ import { plural } from "@/lib/i18n";
import type { WorkspaceInfo } from "@/lib/protocol";
import { workspaceName } from "./commands";
import { isSecondary, reasonLabelKey } from "./visibility";
function serverDot(status: ServerIdentity["status"]): DotStatus {
if (status === "online") return "ok";
@@ -78,9 +79,20 @@ export function WorkspaceRow({ workspace }: WorkspaceRowProps) {
const { t } = useTranslation();
const dot = instanceDot(workspace);
const count = Math.max(workspace.liveCount || 0, workspace.sessionCount || 0);
// Secondary rows are dimmed and carry the policy reason; the page decides
// *whether* they render (see features/workspaces/visibility.ts).
const secondary = isSecondary(workspace);
const reasonKey = secondary ? reasonLabelKey(workspace) : null;
return (
<div className="list-row" data-workspace-id={workspace.workspaceId} data-testid="workspace-row">
<div
className={secondary ? "list-row list-row--secondary" : "list-row"}
style={secondary ? { opacity: 0.55 } : undefined}
data-workspace-id={workspace.workspaceId}
data-testid="workspace-row"
data-visibility={secondary ? "secondary" : "default"}
data-visibility-reason={reasonKey ? workspace.visibilityReason ?? "hidden" : undefined}
>
<span className="ico list-row__icon">
<Icon name="folder" />
</span>
@@ -88,6 +100,11 @@ export function WorkspaceRow({ workspace }: WorkspaceRowProps) {
<div className="list-row__name">{workspaceName(workspace, t("workspaces.unnamed"))}</div>
<div className="list-row__cwd mono muted truncate">{workspace.cwd}</div>
</div>
{reasonKey ? (
<Badge className="list-row__count" data-testid="workspace-reason">
{t(reasonKey)}
</Badge>
) : null}
<Badge tone="info" className="list-row__count">
{plural("workspaces.sessionCount", count)}
</Badge>
+11 -1
View File
@@ -385,6 +385,11 @@
"time.minutesAgo": "{n}m ago",
"workspaces.activeRecently": "Active in the last hour",
"workspaces.addFailed": "Could not open the workspace. Check that the path is accessible.",
"workspaces.allHidden": "All workspaces are hidden",
"workspaces.allHiddenText": "Turn on “Show {n} hidden” to list them.",
"workspaces.hideHidden": "Hide {n} hidden",
"workspaces.showHidden": "Show {n} hidden",
"workspaces.showHiddenAria": "Show hidden workspaces",
"workspaces.contextAria": "Current server",
"workspaces.count": "{n} workspaces",
"workspaces.count.one": "{n} workspace",
@@ -420,5 +425,10 @@
"workspaces.sessionCount.other": "{n} sessions",
"workspaces.subtitle": "A workspace is a Neovim working directory (cwd); sessions are isolated per cwd.",
"workspaces.title": "Workspaces",
"workspaces.unnamed": "Untitled"
"workspaces.unnamed": "Untitled",
"workspaces.reason.ghost": "missing",
"workspaces.reason.hidden": "hidden",
"workspaces.reason.outside-roots": "outside roots",
"workspaces.reason.stale": "stale",
"workspaces.reason.temp": "temp"
}
+11 -1
View File
@@ -385,6 +385,11 @@
"time.minutesAgo": "{n} 分钟前",
"workspaces.activeRecently": "最近 1 小时有活动",
"workspaces.addFailed": "打开工作空间失败,请检查路径是否可访问",
"workspaces.allHidden": "所有工作空间都被隐藏了",
"workspaces.allHiddenText": "打开“显示 {n} 个隐藏项”以查看。",
"workspaces.hideHidden": "隐藏 {n} 个隐藏项",
"workspaces.showHidden": "显示 {n} 个隐藏项",
"workspaces.showHiddenAria": "显示隐藏的工作空间",
"workspaces.contextAria": "当前服务器",
"workspaces.count": "{n} 个工作空间",
"workspaces.count.one": "{n} 个工作空间",
@@ -420,5 +425,10 @@
"workspaces.sessionCount.other": "{n} 个会话",
"workspaces.subtitle": "工作空间 = Neovim 工作目录(cwd),会话严格按 cwd 隔离。",
"workspaces.title": "工作空间",
"workspaces.unnamed": "未命名"
"workspaces.unnamed": "未命名",
"workspaces.reason.ghost": "目录不存在",
"workspaces.reason.hidden": "已隐藏",
"workspaces.reason.outside-roots": "根目录外",
"workspaces.reason.stale": "长期未动",
"workspaces.reason.temp": "临时目录"
}
+6 -3
View File
@@ -15,8 +15,7 @@ import { ConnectionCard } from "@/features/status/connection-card";
import { deviceKey, DevicesCard } from "@/features/status/devices-card";
import { HealthCard } from "@/features/status/health-card";
import { ModelsCard } from "@/features/status/models-card";
import {
mergeTasks,
import { mergeTasks,
sessionTasks,
useDevicesQuery,
useHealthQuery,
@@ -34,6 +33,7 @@ import { ResourcesCard } from "@/features/status/resources-card";
import { deriveServerIdentity, type InfoExtras } from "@/features/status/server";
import { ServerInfoCard } from "@/features/status/server-info-card";
import { TasksCard } from "@/features/status/tasks-card";
import { partitionWorkspaces } from "@/features/workspaces/visibility";
import { ApiError, api, errorI18nKey } from "@/lib/api";
import { useConnectionStore } from "@/stores/connection";
import { useSessionsStore } from "@/stores/sessions";
@@ -72,7 +72,10 @@ export function StatusPage() {
const pairCode = usePairCodeQuery(paired);
const workspaces = workspacesQuery.data ?? [];
const visibleWorkspaces = workspaces.filter((workspace) => !workspace.hidden);
// Counters, the models probe and the task list only consider the rows the
// workspace-noise policy keeps in the default view: a ghost or a /tmp
// scratch dir must not become the "first workspace" used for `/models`.
const { primary: visibleWorkspaces } = partitionWorkspaces(workspaces);
const workspaceCount = visibleWorkspaces.length;
const sessionCount = visibleWorkspaces.reduce((total, workspace) => total + (workspace.sessionCount || 0), 0);
const modelsWorkspaceId = visibleWorkspaces[0]?.workspaceId ?? null;
+56 -17
View File
@@ -13,6 +13,12 @@ import { deriveServerIdentity, type InfoExtras } from "@/features/status/server"
import { useInfoQuery, useWorkspacesQuery } from "@/features/status/queries";
import { openWorkspace } from "@/features/workspaces/commands";
import { NewWorkspaceDialog, type NewWorkspaceInput } from "@/features/workspaces/new-workspace-dialog";
import {
countSecondary,
partitionWorkspaces,
readShowAll,
writeShowAll,
} from "@/features/workspaces/visibility";
import {
ServerContextBar,
WorkspaceRow,
@@ -48,13 +54,25 @@ export function WorkspacesPage() {
const workspaces = useWorkspacesQuery();
const info = useInfoQuery();
const items = useMemo(
() => (workspaces.data ?? []).filter((workspace) => !workspace.hidden).slice().sort(compareWorkspaces),
[workspaces.data],
);
// Persisted "show N hidden" toggle (localStorage, default off): secondary
// rows (hidden/ghost/temp/…) stay out of the list until asked for.
const [showAll, setShowAll] = useState<boolean>(() => readShowAll());
function toggleShowAll() {
setShowAll((previous) => {
const next = !previous;
writeShowAll(next);
return next;
});
}
const all = useMemo(() => (workspaces.data ?? []).slice().sort(compareWorkspaces), [workspaces.data]);
const secondaryCount = useMemo(() => countSecondary(all), [all]);
const { primary, secondary } = useMemo(() => partitionWorkspaces(all, showAll), [all, showAll]);
const items = showAll ? [...primary, ...secondary].sort(compareWorkspaces) : primary;
const sessionCount = useMemo(
() => items.reduce((total, workspace) => total + Math.max(workspace.liveCount || 0, workspace.sessionCount || 0), 0),
[items],
() => primary.reduce((total, workspace) => total + Math.max(workspace.liveCount || 0, workspace.sessionCount || 0), 0),
[primary],
);
const server = deriveServerIdentity({
@@ -85,10 +103,24 @@ export function WorkspacesPage() {
subtitle={t("workspaces.subtitle")}
docTitle={t("nav.workspaces")}
actions={
<Button variant="primary" onClick={() => setDialogOpen(true)}>
<Icon name="plus" />
{t("workspaces.new")}
</Button>
<>
{secondaryCount > 0 ? (
<Button
variant={showAll ? "default" : "ghost"}
aria-pressed={showAll}
aria-label={t("workspaces.showHiddenAria")}
data-testid="workspaces-show-all"
onClick={toggleShowAll}
>
<Icon name="eye" />
{t(showAll ? "workspaces.hideHidden" : "workspaces.showHidden", { n: secondaryCount })}
</Button>
) : null}
<Button variant="primary" onClick={() => setDialogOpen(true)}>
<Icon name="plus" />
{t("workspaces.new")}
</Button>
</>
}
/>
@@ -116,17 +148,24 @@ export function WorkspacesPage() {
}
/>
</Panel>
) : items.length === 0 ? (
) : all.length === 0 || (primary.length === 0 && !showAll) ? (
<Panel>
<Empty
icon={<Icon name="folder" size={28} />}
title={t("workspaces.emptyTitle")}
description={t("workspaces.emptyText")}
title={all.length === 0 ? t("workspaces.emptyTitle") : t("workspaces.allHidden")}
description={all.length === 0 ? t("workspaces.emptyText") : t("workspaces.allHiddenText", { n: secondaryCount })}
action={
<Button variant="primary" onClick={() => setDialogOpen(true)}>
<Icon name="plus" />
{t("workspaces.new")}
</Button>
all.length === 0 ? (
<Button variant="primary" onClick={() => setDialogOpen(true)}>
<Icon name="plus" />
{t("workspaces.new")}
</Button>
) : (
<Button variant="ghost" onClick={toggleShowAll}>
<Icon name="eye" />
{t("workspaces.showHidden", { n: secondaryCount })}
</Button>
)
}
/>
</Panel>
+186
View File
@@ -0,0 +1,186 @@
import { fireEvent, screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { mockApi } from "./helpers/api-mock";
import { renderPage } from "./helpers/render-page";
import {
countSecondary,
partitionWorkspaces,
readShowAll,
reasonLabelKey,
SHOW_ALL_STORAGE_KEY,
writeShowAll,
} from "@/features/workspaces/visibility";
import { setLanguage } from "@/lib/i18n";
import type { WorkspaceInfo, WorkspaceVisibilityReason } from "@/lib/protocol";
import { WorkspacesPage } from "@/pages/workspaces";
const infoBody = {
v: 1,
daemonId: "daemon-1",
machineId: "machine-1",
platform: "linux",
capabilities: ["read", "steer"],
limits: { maxInstances: 5 },
};
function workspace(
overrides: Partial<WorkspaceInfo> & Pick<WorkspaceInfo, "workspaceId" | "cwd" | "name">,
): WorkspaceInfo {
return {
trusted: true,
exists: true,
sessionCount: 0,
liveCount: 0,
lastActiveAt: 0,
instance: null,
visibility: "default",
...overrides,
};
}
function secondary(
workspaceId: string,
name: string,
reason: WorkspaceVisibilityReason,
overrides: Partial<WorkspaceInfo> = {},
): WorkspaceInfo {
return workspace({
workspaceId,
cwd: `/work/${name.toLowerCase()}`,
name,
visibility: "secondary",
visibilityReason: reason,
...overrides,
});
}
const primary = workspace({ workspaceId: "ws-a", cwd: "/work/alpha", name: "Alpha", lastActiveAt: 3_000 });
const ghost = secondary("ws-g", "Ghost", "ghost", { exists: false, lastActiveAt: 2_000 });
const hidden = secondary("ws-h", "Hidden", "hidden", { hidden: true, lastActiveAt: 1_000 });
function routes() {
return [{ path: "/workspaces", component: WorkspacesPage }];
}
function serve(items: WorkspaceInfo[]) {
return mockApi([
{ path: "/api/v1/info", handler: () => ({ body: infoBody }) },
{ path: "/api/v1/workspaces", handler: () => ({ body: items }) },
]);
}
beforeEach(async () => {
await setLanguage("en");
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe("partitionWorkspaces", () => {
it("splits default rows from secondary rows without dropping any", () => {
const legacyHidden = workspace({ workspaceId: "ws-l", cwd: "/work/legacy", name: "Legacy", hidden: true });
delete legacyHidden.visibility;
const list = [primary, ghost, hidden, legacyHidden];
const { primary: shown, secondary: collapsed } = partitionWorkspaces(list);
expect(shown.map((item) => item.workspaceId)).toEqual(["ws-a"]);
// Legacy daemons omit `visibility`; `hidden: true` still means secondary.
expect(collapsed.map((item) => item.workspaceId)).toEqual(["ws-g", "ws-h", "ws-l"]);
expect(partitionWorkspaces(list, true)).toEqual({ primary: shown, secondary: collapsed });
expect(countSecondary(list)).toBe(3);
expect(countSecondary([primary])).toBe(0);
});
it("maps every reason to a badge i18n key", () => {
expect(reasonLabelKey(primary)).toBeNull();
expect(reasonLabelKey(ghost)).toBe("workspaces.reason.ghost");
expect(reasonLabelKey(hidden)).toBe("workspaces.reason.hidden");
expect(reasonLabelKey(secondary("ws-t", "Tmp", "temp"))).toBe("workspaces.reason.temp");
expect(reasonLabelKey(secondary("ws-o", "Out", "outside-roots"))).toBe("workspaces.reason.outside-roots");
expect(reasonLabelKey(secondary("ws-s", "Stale", "stale"))).toBe("workspaces.reason.stale");
// Pre-classification daemon: hidden infers the reason.
const legacy = workspace({ workspaceId: "ws-x", cwd: "/work/x", name: "X", hidden: true });
expect(reasonLabelKey(legacy)).toBe("workspaces.reason.hidden");
});
});
describe("show-all persistence", () => {
it("defaults to off and round-trips through localStorage", () => {
expect(readShowAll()).toBe(false);
writeShowAll(true);
expect(localStorage.getItem(SHOW_ALL_STORAGE_KEY)).toBe("1");
expect(readShowAll()).toBe(true);
writeShowAll(false);
expect(readShowAll()).toBe(false);
});
it("treats an unexpected stored value as off", () => {
localStorage.setItem(SHOW_ALL_STORAGE_KEY, "yes");
expect(readShowAll()).toBe(false);
});
});
describe("WorkspacesPage secondary rows", () => {
it("lists only primary rows by default and counts the hidden ones", async () => {
serve([primary, ghost, hidden]);
const { container } = await renderPage(routes(), "/workspaces");
await screen.findByText("Alpha");
expect(screen.queryByText("Ghost")).not.toBeInTheDocument();
expect(screen.queryByText("Hidden")).not.toBeInTheDocument();
const toggle = await screen.findByTestId("workspaces-show-all");
expect(toggle).toHaveTextContent("Show 2 hidden");
expect(toggle).toHaveAttribute("aria-pressed", "false");
expect(container.querySelectorAll('[data-testid="workspace-row"]')).toHaveLength(1);
expect(readShowAll()).toBe(false);
});
it("reveals dimmed secondary rows with a reason badge on toggle", async () => {
serve([primary, ghost, hidden]);
await renderPage(routes(), "/workspaces");
await screen.findByText("Alpha");
fireEvent.click(screen.getByTestId("workspaces-show-all"));
expect(await screen.findByText("Ghost")).toBeInTheDocument();
expect(screen.getByText("Hidden")).toBeInTheDocument();
const rows = screen.getAllByTestId("workspace-row");
expect(rows.map((row) => row.getAttribute("data-visibility"))).toEqual(["default", "secondary", "secondary"]);
const ghostRow = rows.find((row) => row.getAttribute("data-workspace-id") === "ws-g");
expect(ghostRow).toHaveAttribute("data-visibility-reason", "ghost");
expect(ghostRow).toHaveStyle({ opacity: "0.55" });
expect(ghostRow?.querySelector('[data-testid="workspace-reason"]')).toHaveTextContent("missing");
const toggle = screen.getByTestId("workspaces-show-all");
expect(toggle).toHaveTextContent("Hide 2 hidden");
expect(toggle).toHaveAttribute("aria-pressed", "true");
await waitFor(() => expect(localStorage.getItem(SHOW_ALL_STORAGE_KEY)).toBe("1"));
fireEvent.click(toggle);
await waitFor(() => expect(screen.queryByText("Ghost")).not.toBeInTheDocument());
expect(localStorage.getItem(SHOW_ALL_STORAGE_KEY)).toBe("0");
});
it("honours a persisted toggle on mount", async () => {
serve([primary, ghost, hidden]);
await renderPage(routes(), "/workspaces", { storage: { [SHOW_ALL_STORAGE_KEY]: "1" } });
expect(await screen.findByText("Alpha")).toBeInTheDocument();
expect(await screen.findByText("Ghost")).toBeInTheDocument();
expect(screen.getByText("Hidden")).toBeInTheDocument();
});
it("offers the toggle from the empty state when every row is secondary", async () => {
serve([ghost, hidden]);
await renderPage(routes(), "/workspaces");
expect(await screen.findByText("All workspaces are hidden")).toBeInTheDocument();
fireEvent.click(screen.getByTestId("workspaces-show-all"));
expect(await screen.findByText("Ghost")).toBeInTheDocument();
});
});