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:
1 parent
58e247644d
commit
64a1a98c1f
12 files changed
+888
-38
No files matched your search
@@ -90,6 +90,33 @@ Plugin obligations:
|
||||
| `GET /api/v1/resources` | instances, sessions, RSS totals for the soft-limit notice |
|
||||
| `GET /api/v1/diagnostics` | connections, event rates, slow queries, instance table |
|
||||
|
||||
Workspace row (`GET /api/v1/workspaces`) — registry entry ∪ disk discovery ∪ live instance state. Every known workspace is returned; rows are never filtered, so `/workspace/<workspaceId>` deep links always resolve:
|
||||
|
||||
| Field | Notes |
|
||||
|---|---|
|
||||
| `workspaceId` | `sha256(realpath(cwd)).slice(0,16)` |
|
||||
| `cwd`, `name`, `alias` | `name` falls back to `alias`, then `basename(cwd)` |
|
||||
| `pinned`, `hidden`, `trusted` | persisted user intent from `workspaces.json` |
|
||||
| `exists` | `false` = ghost (the cwd is gone; the session files are not) |
|
||||
| `sessionCount`, `liveCount`, `lastActiveAt` | disk projection (`lastActiveAt` may be `null`) |
|
||||
| `instance` | live `InstanceState` or `null` |
|
||||
| `visibility?: "default" \| "secondary"` | derived, never persisted: the workspace-noise policy. Missing ⇒ `default` |
|
||||
| `visibilityReason?` | `hidden` \| `ghost` \| `temp` \| `outside-roots` \| `stale`; absent for `default` rows |
|
||||
|
||||
The classification is advisory and client-side only (precedence, first match wins):
|
||||
|
||||
1. `hidden: true` → `secondary`/`hidden` — explicit user intent always wins, no rescue.
|
||||
2. A live instance (`instance != null` or `liveCount > 0`), `pinned` or `trusted` → `default` (rescue).
|
||||
3. `PI2_WORKSPACE_HIDE_TEMP=1` (default `1`) and `cwd` is under `$TMPDIR`, `/tmp`, `/var/tmp`, `/var/folders` or `/private/var/folders` → `secondary`/`temp`.
|
||||
4. `PI2_WORKSPACE_HIDE_GHOSTS=1` (default `1`) and `exists === false` → `secondary`/`ghost`.
|
||||
5. `PI2_WORKSPACE_HIDE_OUTSIDE_ROOTS=1` (default `0`) and `cwd` is outside `PI2_WORKSPACE_ROOTS` → `secondary`/`outside-roots`.
|
||||
6. `PI2_WORKSPACE_STALE_DAYS=<n>` (default `0` = off) and `lastActiveAt` older than `n` days → `secondary`/`stale` (`lastActiveAt: null` never counts).
|
||||
7. Otherwise `default`.
|
||||
|
||||
A client that lets the user *choose* a workspace should list only `default` rows by
|
||||
default; `secondary` rows belong behind a “show hidden” toggle. Lookups by
|
||||
`workspaceId` must ignore `visibility` entirely.
|
||||
|
||||
Session row (`GET /api/v1/workspaces/:id/sessions`) — a subset of `SessionState` plus list metadata (`usage`, `flags`, `entries` and `attention` arrive via snapshot/events, not on this row):
|
||||
|
||||
| Field | Notes |
|
||||
|
||||
@@ -278,8 +278,21 @@ export interface WorkspaceInfo {
|
||||
liveCount: number;
|
||||
lastActiveAt: number | null;
|
||||
instance: InstanceState | null;
|
||||
/**
|
||||
* Derived, non-persisted noise classification (see docs/protocol.md).
|
||||
* `secondary` rows are still served and addressable — a client decides
|
||||
* whether to list them behind a "show hidden" toggle. Older daemons omit
|
||||
* the field; treat a missing value as `default`.
|
||||
*/
|
||||
visibility?: WorkspaceVisibility;
|
||||
/** Why a row is `secondary`; absent for `default` rows. */
|
||||
visibilityReason?: WorkspaceVisibilityReason;
|
||||
}
|
||||
|
||||
export type WorkspaceVisibility = "default" | "secondary";
|
||||
|
||||
export type WorkspaceVisibilityReason = "hidden" | "ghost" | "temp" | "outside-roots" | "stale";
|
||||
|
||||
export type DaemonCommandMethod =
|
||||
| "instance.ensure"
|
||||
| "instance.shutdown"
|
||||
|
||||
+184
-15
@@ -2,8 +2,12 @@
|
||||
* WorkspaceStore: merges the durable registry, disk discovery and live
|
||||
* instance state into the `WorkspaceInfo` shape served by the daemon.
|
||||
*
|
||||
* Ordering and hiding are intentionally left to the UI; `list()` returns every
|
||||
* known workspace (including `hidden` ones) with stable registry-first order.
|
||||
* `list()` returns every known workspace (including `hidden` ones) with stable
|
||||
* registry-first order: rows are never filtered, so `/workspace/<id>` deep
|
||||
* links keep resolving. Instead every row carries a derived, non-persisted
|
||||
* `visibility` (`default` | `secondary`) + `visibilityReason` that the UI uses
|
||||
* to collapse workspace noise (ghosts, temp dirs, …) into a "show hidden"
|
||||
* section. Ordering and presentation stay with the UI.
|
||||
*/
|
||||
|
||||
import { accessSync, constants, realpathSync, statSync } from "node:fs";
|
||||
@@ -12,7 +16,12 @@ import { basename, isAbsolute, join, relative, resolve, sep } from "node:path";
|
||||
import type { InstanceManager, WorkspaceStore as WorkspaceStoreContract } from "../core/interfaces.js";
|
||||
import { dataDir, realpathSafe, workspaceIdForCwd } from "../core/paths.js";
|
||||
import { ERROR_CODES } from "../protocol/errors.js";
|
||||
import type { InstanceState, WorkspaceInfo } from "../protocol/types.js";
|
||||
import type {
|
||||
InstanceState,
|
||||
WorkspaceInfo,
|
||||
WorkspaceVisibility,
|
||||
WorkspaceVisibilityReason,
|
||||
} from "../protocol/types.js";
|
||||
import {
|
||||
createDiscovery,
|
||||
type DiscoveredWorkspace,
|
||||
@@ -28,6 +37,8 @@ import {
|
||||
type WorkspacePatch,
|
||||
} from "./registry.js";
|
||||
|
||||
export type WorkspaceEnv = Record<string, string | undefined>;
|
||||
|
||||
export interface WorkspaceStoreOptions {
|
||||
/** Defaults to a discovery over `sessionsRoot()`. */
|
||||
discovery?: Discovery;
|
||||
@@ -43,6 +54,13 @@ export interface WorkspaceStoreOptions {
|
||||
* anywhere the user already opened nvim.
|
||||
*/
|
||||
roots?: readonly string[];
|
||||
/**
|
||||
* Environment used for `PI2_WORKSPACE_*` (roots + visibility policy);
|
||||
* injectable so tests stay hermetic. Defaults to `process.env`.
|
||||
*/
|
||||
env?: WorkspaceEnv;
|
||||
/** Clock for the `PI2_WORKSPACE_STALE_DAYS` comparison; defaults to `Date.now`. */
|
||||
now?: () => number;
|
||||
}
|
||||
|
||||
export interface WorkspaceStoreHandle extends WorkspaceStoreContract {
|
||||
@@ -62,9 +80,13 @@ class WorkspaceStore implements WorkspaceStoreHandle {
|
||||
private readonly instances: Pick<InstanceManager, "list" | "instanceStates"> | undefined;
|
||||
private readonly logger: WorkspaceStoreOptions["logger"] | undefined;
|
||||
private readonly roots: readonly string[] | undefined;
|
||||
private readonly env: WorkspaceEnv;
|
||||
private readonly now: () => number;
|
||||
|
||||
constructor(options: WorkspaceStoreOptions = {}) {
|
||||
this.logger = options.logger;
|
||||
this.env = options.env ?? process.env;
|
||||
this.now = options.now ?? Date.now;
|
||||
this.discovery = options.discovery ?? createDiscovery({ ...(options.logger ? { logger: options.logger } : {}) });
|
||||
this.registry =
|
||||
options.registry ??
|
||||
@@ -157,15 +179,16 @@ class WorkspaceStore implements WorkspaceStoreHandle {
|
||||
}
|
||||
|
||||
await this.registry.ensureForCwd(real);
|
||||
const patch: WorkspacePatch = {};
|
||||
// Explicitly reopen: `registry.update()` only touches the keys it is
|
||||
// given, so a previously hidden workspace would otherwise stay hidden
|
||||
// and vanish from the list after the user just asked to open it.
|
||||
const patch: WorkspacePatch = { hidden: false };
|
||||
if (input.alias !== undefined) {
|
||||
const alias = input.alias.trim();
|
||||
patch.alias = alias.length > 0 ? alias : null;
|
||||
}
|
||||
if (input.trust !== undefined) patch.trusted = input.trust;
|
||||
if (Object.keys(patch).length > 0) {
|
||||
await this.registry.update(workspaceIdForCwd(real), patch);
|
||||
}
|
||||
await this.registry.update(workspaceIdForCwd(real), patch);
|
||||
|
||||
return this.requireInfo(workspaceIdForCwd(real));
|
||||
}
|
||||
@@ -274,19 +297,40 @@ class WorkspaceStore implements WorkspaceStoreHandle {
|
||||
): WorkspaceInfo {
|
||||
const cwd = entry?.cwd ?? discovered?.cwd ?? "";
|
||||
const alias = entry?.alias ?? null;
|
||||
const pinned = entry?.pinned ?? false;
|
||||
const hidden = entry?.hidden ?? false;
|
||||
const trusted = entry?.trusted ?? false;
|
||||
const exists = discovered?.exists ?? isDirectory(cwd);
|
||||
const lastActiveAt = discovered?.lastActiveAt ?? null;
|
||||
const liveCount = views.live.get(workspaceId) ?? 0;
|
||||
const instance = views.instances.get(workspaceId) ?? null;
|
||||
const classification = classifyWorkspace({
|
||||
cwd,
|
||||
hidden,
|
||||
pinned,
|
||||
trusted,
|
||||
exists,
|
||||
lastActiveAt,
|
||||
liveCount,
|
||||
instance,
|
||||
roots: this.allowlist(),
|
||||
env: this.env,
|
||||
now: this.now(),
|
||||
});
|
||||
return {
|
||||
workspaceId,
|
||||
cwd,
|
||||
name: alias ?? (basename(cwd) || cwd),
|
||||
alias,
|
||||
pinned: entry?.pinned ?? false,
|
||||
hidden: entry?.hidden ?? false,
|
||||
trusted: entry?.trusted ?? false,
|
||||
exists: discovered?.exists ?? isDirectory(cwd),
|
||||
pinned,
|
||||
hidden,
|
||||
trusted,
|
||||
exists,
|
||||
sessionCount: discovered?.sessionCount ?? 0,
|
||||
liveCount: views.live.get(workspaceId) ?? 0,
|
||||
lastActiveAt: discovered?.lastActiveAt ?? null,
|
||||
instance: views.instances.get(workspaceId) ?? null,
|
||||
liveCount,
|
||||
lastActiveAt,
|
||||
instance,
|
||||
...classification,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -326,7 +370,7 @@ class WorkspaceStore implements WorkspaceStoreHandle {
|
||||
if (configured !== undefined) {
|
||||
return configured.map((root) => canonicalRoot(root)).filter((root): root is string => root.length > 0);
|
||||
}
|
||||
return rootsFromEnv(process.env.PI2_WORKSPACE_ROOTS);
|
||||
return rootsFromEnv(this.env.PI2_WORKSPACE_ROOTS);
|
||||
}
|
||||
|
||||
private assertAllowed(candidate: string, roots: readonly string[]): void {
|
||||
@@ -342,6 +386,131 @@ export function createWorkspaceStore(options: WorkspaceStoreOptions = {}): Works
|
||||
return new WorkspaceStore(options);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Workspace visibility policy (derived, never persisted) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
const DAY_MS = 86_400_000;
|
||||
const TRUE_VALUES = new Set(["1", "true", "yes", "on"]);
|
||||
const FALSE_VALUES = new Set(["0", "false", "no", "off"]);
|
||||
|
||||
/** Built-in temp roots, in addition to `$TMPDIR` when it is set and absolute. */
|
||||
const DEFAULT_TEMP_ROOTS: readonly string[] = ["/tmp", "/var/tmp", "/var/folders", "/private/var/folders"];
|
||||
|
||||
export interface ClassifyWorkspaceInput {
|
||||
cwd: string;
|
||||
hidden?: boolean | undefined;
|
||||
pinned?: boolean | undefined;
|
||||
trusted?: boolean | undefined;
|
||||
exists: boolean;
|
||||
lastActiveAt: number | null;
|
||||
/** Live instance for this workspace (`WorkspaceInfo.instance`). */
|
||||
instance?: InstanceState | null | undefined;
|
||||
/** Live sessions reported by the instance (`WorkspaceInfo.liveCount`). */
|
||||
liveCount?: number | undefined;
|
||||
/** Roots for the `outside-roots` rule; defaults to `PI2_WORKSPACE_ROOTS` / `$HOME`. */
|
||||
roots?: readonly string[] | undefined;
|
||||
/** Policy switches; defaults to `process.env`. */
|
||||
env?: WorkspaceEnv | undefined;
|
||||
/** Clock for `PI2_WORKSPACE_STALE_DAYS`; defaults to `Date.now()`. */
|
||||
now?: number | undefined;
|
||||
}
|
||||
|
||||
export interface WorkspaceClassification {
|
||||
visibility: WorkspaceVisibility;
|
||||
visibilityReason?: WorkspaceVisibilityReason;
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive the workspace-noise policy for one row. Pure and non-persisted so the
|
||||
* same inputs always produce the same classification. Precedence (first match
|
||||
* wins):
|
||||
*
|
||||
* 1. `hidden` → secondary/hidden (explicit intent)
|
||||
* 2. live instance, pinned or trusted → default (rescue)
|
||||
* 3. `PI2_WORKSPACE_HIDE_TEMP` (1) → secondary/temp
|
||||
* 4. `PI2_WORKSPACE_HIDE_GHOSTS` (1) → secondary/ghost
|
||||
* 5. `PI2_WORKSPACE_HIDE_OUTSIDE_ROOTS` (0) → secondary/outside-roots
|
||||
* 6. `PI2_WORKSPACE_STALE_DAYS` (0=off) → secondary/stale
|
||||
* 7. otherwise → default
|
||||
*/
|
||||
export function classifyWorkspace(input: ClassifyWorkspaceInput): WorkspaceClassification {
|
||||
const env = input.env ?? process.env;
|
||||
const cwd = typeof input.cwd === "string" ? input.cwd : "";
|
||||
const real = cwd.length > 0 ? realpathSafe(cwd) : "";
|
||||
|
||||
if (input.hidden === true) return secondary("hidden");
|
||||
|
||||
const liveCount = typeof input.liveCount === "number" && Number.isFinite(input.liveCount) ? input.liveCount : 0;
|
||||
if (input.instance != null || liveCount > 0 || input.pinned === true || input.trusted === true) {
|
||||
return { visibility: "default" };
|
||||
}
|
||||
|
||||
if (parseBooleanEnv(env.PI2_WORKSPACE_HIDE_TEMP, true) && real !== "" && isTempPath(real, env)) {
|
||||
return secondary("temp");
|
||||
}
|
||||
|
||||
if (parseBooleanEnv(env.PI2_WORKSPACE_HIDE_GHOSTS, true) && input.exists === false) {
|
||||
return secondary("ghost");
|
||||
}
|
||||
|
||||
if (parseBooleanEnv(env.PI2_WORKSPACE_HIDE_OUTSIDE_ROOTS, false)) {
|
||||
// Both sides canonicalised, mirroring the `add()` allowlist.
|
||||
const roots = (input.roots ?? rootsFromEnv(env.PI2_WORKSPACE_ROOTS)).map((root) => realpathSafe(root));
|
||||
if (real !== "" && !roots.some((root) => isWithin(root, real))) return secondary("outside-roots");
|
||||
}
|
||||
|
||||
const staleDays = parseNonNegativeInt(env.PI2_WORKSPACE_STALE_DAYS);
|
||||
if (staleDays > 0 && typeof input.lastActiveAt === "number" && Number.isFinite(input.lastActiveAt)) {
|
||||
const now = typeof input.now === "number" && Number.isFinite(input.now) ? input.now : Date.now();
|
||||
if (now - input.lastActiveAt > staleDays * DAY_MS) return secondary("stale");
|
||||
}
|
||||
|
||||
return { visibility: "default" };
|
||||
}
|
||||
|
||||
/** `1/true/yes/on` enable, `0/false/no/off` disable, anything else → `fallback`. Never throws. */
|
||||
export function parseBooleanEnv(raw: string | undefined, fallback: boolean): boolean {
|
||||
if (typeof raw !== "string") return fallback;
|
||||
const value = raw.trim().toLowerCase();
|
||||
if (TRUE_VALUES.has(value)) return true;
|
||||
if (FALSE_VALUES.has(value)) return false;
|
||||
return fallback;
|
||||
}
|
||||
|
||||
/** Non-negative integer days, or `0` (policy disabled) for garbage. Never throws. */
|
||||
export function parseNonNegativeInt(raw: string | undefined): number {
|
||||
if (typeof raw !== "string") return 0;
|
||||
const value = raw.trim();
|
||||
if (!/^\d+$/.test(value)) return 0;
|
||||
const parsed = Number(value);
|
||||
return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : 0;
|
||||
}
|
||||
|
||||
/** `$TMPDIR` (when set) plus the platform defaults, realpath'd and deduped. */
|
||||
export function tempRoots(env: WorkspaceEnv = process.env): string[] {
|
||||
const candidates = [env.TMPDIR, ...DEFAULT_TEMP_ROOTS];
|
||||
const roots: string[] = [];
|
||||
for (const candidate of candidates) {
|
||||
if (typeof candidate !== "string") continue;
|
||||
const value = candidate.trim();
|
||||
if (value.length === 0 || !isAbsolute(value)) continue;
|
||||
roots.push(realpathSafe(value));
|
||||
}
|
||||
return [...new Set(roots)];
|
||||
}
|
||||
|
||||
/** True for a temp root itself or any path below one (both sides realpath'd). */
|
||||
export function isTempPath(cwd: string, env: WorkspaceEnv = process.env): boolean {
|
||||
if (typeof cwd !== "string" || cwd.length === 0) return false;
|
||||
const real = realpathSafe(cwd);
|
||||
return tempRoots(env).some((root) => isWithin(root, real));
|
||||
}
|
||||
|
||||
function secondary(reason: WorkspaceVisibilityReason): WorkspaceClassification {
|
||||
return { visibility: "secondary", visibilityReason: reason };
|
||||
}
|
||||
|
||||
export function rootsFromEnv(raw: string | undefined, fallback: string = homedir()): string[] {
|
||||
const parts = (raw ?? "")
|
||||
.split(",")
|
||||
|
||||
@@ -128,6 +128,55 @@ describe("workspace store", () => {
|
||||
expect(store.get(bId)?.hidden).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps secondary rows in list() and get() so deep links still resolve", async () => {
|
||||
// The sandbox lives under $TMPDIR, so temp-hiding is switched off here to
|
||||
// isolate the hidden/ghost rules (and to exercise the env injection).
|
||||
const { store } = setup({ env: { PI2_WORKSPACE_HIDE_TEMP: "0" } });
|
||||
const bId = workspaceIdForCwd(projectB);
|
||||
await store.update(bId, { hidden: true });
|
||||
const ghostId = workspaceIdForCwd(projectGhost);
|
||||
|
||||
const all = store.list();
|
||||
expect(all).toHaveLength(3);
|
||||
expect(all.map((workspace) => workspace.workspaceId).sort()).toEqual(
|
||||
[workspaceIdForCwd(projectA), bId, ghostId].sort(),
|
||||
);
|
||||
|
||||
expect(store.get(bId)).toMatchObject({ hidden: true, visibility: "secondary", visibilityReason: "hidden" });
|
||||
expect(store.get(ghostId)).toMatchObject({
|
||||
exists: false,
|
||||
visibility: "secondary",
|
||||
visibilityReason: "ghost",
|
||||
});
|
||||
expect(store.get(workspaceIdForCwd(projectA))).toMatchObject({ visibility: "default" });
|
||||
expect(store.get(workspaceIdForCwd(projectA))).not.toHaveProperty("visibilityReason");
|
||||
});
|
||||
|
||||
it("classifies sandbox paths under $TMPDIR as temp when the policy is on", () => {
|
||||
const { store } = setup({ env: {} });
|
||||
expect(store.get(workspaceIdForCwd(projectA))).toMatchObject({
|
||||
visibility: "secondary",
|
||||
visibilityReason: "temp",
|
||||
});
|
||||
});
|
||||
|
||||
it("add() clears hidden on a previously hidden workspace", async () => {
|
||||
const { store, registry } = setup({ env: { PI2_WORKSPACE_HIDE_TEMP: "0" } });
|
||||
const info = await store.add({ cwd: projectA });
|
||||
await store.update(info.workspaceId, { hidden: true });
|
||||
expect(store.get(info.workspaceId)).toMatchObject({
|
||||
hidden: true,
|
||||
visibility: "secondary",
|
||||
visibilityReason: "hidden",
|
||||
});
|
||||
|
||||
const reopened = await store.add({ cwd: projectA });
|
||||
expect(reopened).toMatchObject({ hidden: false, visibility: "default" });
|
||||
expect(reopened).not.toHaveProperty("visibilityReason");
|
||||
expect(registry.get(info.workspaceId)?.entry.hidden).toBe(false);
|
||||
expect(registry.list()).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("adds existing, readable, writable directories inside the allowlist", async () => {
|
||||
const { store, registry } = setup();
|
||||
const info = await store.add({ cwd: projectA, alias: " Alpha ", trust: true });
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
import { mkdirSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
|
||||
import type { InstanceState } from "../../src/protocol/types.js";
|
||||
import {
|
||||
classifyWorkspace,
|
||||
isTempPath,
|
||||
parseBooleanEnv,
|
||||
parseNonNegativeInt,
|
||||
tempRoots,
|
||||
type ClassifyWorkspaceInput,
|
||||
} from "../../src/workspaces/index.js";
|
||||
import { cleanup, makeSandbox } from "./helpers.js";
|
||||
|
||||
const DAY = 86_400_000;
|
||||
const NOW = Date.UTC(2026, 9, 15, 12, 0, 0);
|
||||
|
||||
function instanceState(workspaceId: string): InstanceState {
|
||||
return {
|
||||
workspaceId,
|
||||
instanceId: "i-1",
|
||||
status: "ready",
|
||||
nvimPid: 4242,
|
||||
pluginVersion: "1.8.0",
|
||||
hasUI: true,
|
||||
attachedClients: 1,
|
||||
listenAddr: null,
|
||||
startedAt: NOW,
|
||||
};
|
||||
}
|
||||
|
||||
describe("classifyWorkspace", () => {
|
||||
// Synthetic, non-existent roots: the test must not depend on the host's
|
||||
// $HOME or on the mkdtemp sandbox (which itself lives under /tmp).
|
||||
const home = "/pi2-test-home";
|
||||
const other = "/pi2-test-other";
|
||||
const third = "/pi2-test-third";
|
||||
let sandbox: string;
|
||||
let temp: string;
|
||||
|
||||
beforeEach(() => {
|
||||
sandbox = makeSandbox("pi2-daemon-visibility-");
|
||||
temp = join(sandbox, "temp");
|
||||
mkdirSync(temp, { recursive: true });
|
||||
});
|
||||
|
||||
afterEach(() => cleanup(sandbox));
|
||||
|
||||
/** Hermetic base row: no env leakage from the host, roots pinned to `home`. */
|
||||
function row(overrides: Partial<ClassifyWorkspaceInput> = {}): ClassifyWorkspaceInput {
|
||||
return {
|
||||
cwd: join(home, "code", "alpha"),
|
||||
exists: true,
|
||||
lastActiveAt: NOW - DAY,
|
||||
roots: [home],
|
||||
env: { TMPDIR: temp },
|
||||
now: NOW,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
it("defaults to a visible row with no reason", () => {
|
||||
expect(classifyWorkspace(row())).toEqual({ visibility: "default" });
|
||||
});
|
||||
|
||||
it("precedence 1: hidden wins over every rescue", () => {
|
||||
const classified = classifyWorkspace(
|
||||
row({
|
||||
hidden: true,
|
||||
pinned: true,
|
||||
trusted: true,
|
||||
liveCount: 2,
|
||||
instance: instanceState("ws-1"),
|
||||
exists: false,
|
||||
cwd: join(temp, "scratch"),
|
||||
}),
|
||||
);
|
||||
expect(classified).toEqual({ visibility: "secondary", visibilityReason: "hidden" });
|
||||
});
|
||||
|
||||
it("precedence 2: a live instance, pin or trust rescues temp/ghost/stale rows", () => {
|
||||
const tempGhostStale = {
|
||||
cwd: join(temp, "scratch", "deep"),
|
||||
exists: false,
|
||||
lastActiveAt: NOW - 365 * DAY,
|
||||
env: { TMPDIR: temp, PI2_WORKSPACE_STALE_DAYS: "7" },
|
||||
};
|
||||
expect(classifyWorkspace(row(tempGhostStale))).toMatchObject({
|
||||
visibility: "secondary",
|
||||
visibilityReason: "temp",
|
||||
});
|
||||
for (const rescue of [
|
||||
{ instance: instanceState("ws-1") },
|
||||
{ liveCount: 1 },
|
||||
{ pinned: true },
|
||||
{ trusted: true },
|
||||
]) {
|
||||
expect(classifyWorkspace(row({ ...tempGhostStale, ...rescue })), JSON.stringify(rescue)).toEqual({
|
||||
visibility: "default",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("precedence 3: temp paths hide by default, including trailing subpaths", () => {
|
||||
expect(classifyWorkspace(row({ cwd: temp }))).toEqual({ visibility: "secondary", visibilityReason: "temp" });
|
||||
expect(classifyWorkspace(row({ cwd: join(temp, "a", "b", "c") }))).toEqual({
|
||||
visibility: "secondary",
|
||||
visibilityReason: "temp",
|
||||
});
|
||||
// Built-in roots work without TMPDIR.
|
||||
expect(classifyWorkspace(row({ cwd: "/tmp/pi2-not-created", env: {} }))).toEqual({
|
||||
visibility: "secondary",
|
||||
visibilityReason: "temp",
|
||||
});
|
||||
expect(classifyWorkspace(row({ env: { TMPDIR: temp, PI2_WORKSPACE_HIDE_TEMP: "0" } }))).toEqual({
|
||||
visibility: "default",
|
||||
});
|
||||
});
|
||||
|
||||
it("precedence 4: ghosts hide by default and beat outside-roots/stale", () => {
|
||||
const elsewhere = join(other, "gone");
|
||||
expect(classifyWorkspace(row({ cwd: elsewhere, exists: false }))).toEqual({
|
||||
visibility: "secondary",
|
||||
visibilityReason: "ghost",
|
||||
});
|
||||
expect(
|
||||
classifyWorkspace(
|
||||
row({
|
||||
cwd: elsewhere,
|
||||
exists: false,
|
||||
lastActiveAt: NOW - 400 * DAY,
|
||||
env: { TMPDIR: temp, PI2_WORKSPACE_HIDE_OUTSIDE_ROOTS: "1", PI2_WORKSPACE_STALE_DAYS: "30" },
|
||||
}),
|
||||
),
|
||||
).toEqual({ visibility: "secondary", visibilityReason: "ghost" });
|
||||
expect(
|
||||
classifyWorkspace(row({ exists: false, env: { TMPDIR: temp, PI2_WORKSPACE_HIDE_GHOSTS: "0" } })),
|
||||
).toEqual({ visibility: "default" });
|
||||
});
|
||||
|
||||
it("precedence 5: outside-roots is opt-in and parses PI2_WORKSPACE_ROOTS as a list", () => {
|
||||
const outside = row({ cwd: join(other, "project"), roots: [home], env: { TMPDIR: temp } });
|
||||
// Default is 0 → still visible.
|
||||
expect(classifyWorkspace(outside)).toEqual({ visibility: "default" });
|
||||
expect(classifyWorkspace({ ...outside, env: { TMPDIR: temp, PI2_WORKSPACE_HIDE_OUTSIDE_ROOTS: "1" } })).toEqual(
|
||||
{ visibility: "secondary", visibilityReason: "outside-roots" },
|
||||
);
|
||||
|
||||
// Both roots from the env list are honoured; the third path is outside.
|
||||
const roots = `${home}, ${other}`;
|
||||
const env = { TMPDIR: temp, PI2_WORKSPACE_HIDE_OUTSIDE_ROOTS: "1", PI2_WORKSPACE_ROOTS: roots };
|
||||
expect(classifyWorkspace(row({ cwd: join(home, "a"), roots: undefined, env }))).toEqual({
|
||||
visibility: "default",
|
||||
});
|
||||
expect(classifyWorkspace(row({ cwd: join(other, "b"), roots: undefined, env }))).toEqual({
|
||||
visibility: "default",
|
||||
});
|
||||
expect(classifyWorkspace(row({ cwd: join(third, "c"), roots: undefined, env }))).toEqual({
|
||||
visibility: "secondary",
|
||||
visibilityReason: "outside-roots",
|
||||
});
|
||||
});
|
||||
|
||||
it("precedence 6: stale is opt-in and never applies to lastActiveAt === null", () => {
|
||||
const old = row({ lastActiveAt: NOW - 31 * DAY, env: { TMPDIR: temp } });
|
||||
// Default 0 = disabled.
|
||||
expect(classifyWorkspace(old)).toEqual({ visibility: "default" });
|
||||
expect(classifyWorkspace({ ...old, env: { TMPDIR: temp, PI2_WORKSPACE_STALE_DAYS: "30" } })).toEqual({
|
||||
visibility: "secondary",
|
||||
visibilityReason: "stale",
|
||||
});
|
||||
const fresh = row({ lastActiveAt: NOW - 29 * DAY, env: { TMPDIR: temp, PI2_WORKSPACE_STALE_DAYS: "30" } });
|
||||
expect(classifyWorkspace(fresh)).toEqual({ visibility: "default" });
|
||||
expect(
|
||||
classifyWorkspace(
|
||||
row({ lastActiveAt: null, env: { TMPDIR: temp, PI2_WORKSPACE_STALE_DAYS: "1" } }),
|
||||
),
|
||||
).toEqual({ visibility: "default" });
|
||||
});
|
||||
|
||||
it("never throws on garbage env values", () => {
|
||||
const garbage = {
|
||||
PI2_WORKSPACE_HIDE_TEMP: "maybe",
|
||||
PI2_WORKSPACE_HIDE_GHOSTS: " ",
|
||||
PI2_WORKSPACE_HIDE_OUTSIDE_ROOTS: "2",
|
||||
PI2_WORKSPACE_STALE_DAYS: "-3",
|
||||
};
|
||||
// Garbage booleans fall back to the defaults (temp+ghost on, roots off);
|
||||
// garbage stale-days falls back to 0 (off).
|
||||
expect(classifyWorkspace(row({ cwd: join(temp, "x"), env: garbage }))).toEqual({
|
||||
visibility: "secondary",
|
||||
visibilityReason: "temp",
|
||||
});
|
||||
expect(classifyWorkspace(row({ exists: false, env: garbage }))).toEqual({
|
||||
visibility: "secondary",
|
||||
visibilityReason: "ghost",
|
||||
});
|
||||
expect(classifyWorkspace(row({ cwd: join(other, "x"), lastActiveAt: null, env: garbage }))).toEqual({
|
||||
visibility: "default",
|
||||
});
|
||||
// Unknown cwd / missing roots must not throw.
|
||||
expect(classifyWorkspace({ cwd: "", exists: true, lastActiveAt: null, env: garbage })).toEqual({
|
||||
visibility: "default",
|
||||
});
|
||||
});
|
||||
|
||||
it("parseBooleanEnv accepts 1/true/yes/on and 0/false/no/off, else the fallback", () => {
|
||||
for (const raw of ["1", "true", "TRUE", "yes", "on", " on "]) {
|
||||
expect(parseBooleanEnv(raw, false), raw).toBe(true);
|
||||
}
|
||||
for (const raw of ["0", "false", "False", "no", "off", " off "]) {
|
||||
expect(parseBooleanEnv(raw, true), raw).toBe(false);
|
||||
}
|
||||
for (const raw of [undefined, "", "maybe", "2", "enabled"]) {
|
||||
expect(parseBooleanEnv(raw, true), String(raw)).toBe(true);
|
||||
expect(parseBooleanEnv(raw, false), String(raw)).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("parseNonNegativeInt keeps positive integers and falls back to 0", () => {
|
||||
expect(parseNonNegativeInt("30")).toBe(30);
|
||||
expect(parseNonNegativeInt(" 7 ")).toBe(7);
|
||||
expect(parseNonNegativeInt("0")).toBe(0);
|
||||
for (const raw of [undefined, "", "-1", "1.5", "abc", "1e3", "999999999999999999999"]) {
|
||||
expect(parseNonNegativeInt(raw), String(raw)).toBe(0);
|
||||
}
|
||||
});
|
||||
|
||||
it("tempRoots includes $TMPDIR plus the platform defaults and isTempPath matches subpaths", () => {
|
||||
const roots = tempRoots({ TMPDIR: temp });
|
||||
expect(roots).toContain(temp);
|
||||
expect(roots).toContain("/tmp");
|
||||
expect(new Set(roots).size).toBe(roots.length);
|
||||
expect(isTempPath(join(temp, "x", "y"), { TMPDIR: temp })).toBe(true);
|
||||
expect(isTempPath(temp, { TMPDIR: temp })).toBe(true);
|
||||
expect(isTempPath(join(home, "code"), { TMPDIR: temp })).toBe(false);
|
||||
expect(isTempPath("", { TMPDIR: temp })).toBe(false);
|
||||
});
|
||||
|
||||
it("hides a temp ghost as temp (temp precedes ghost)", () => {
|
||||
expect(classifyWorkspace(row({ cwd: join(temp, "gone"), exists: false }))).toEqual({
|
||||
visibility: "secondary",
|
||||
visibilityReason: "temp",
|
||||
});
|
||||
});
|
||||
|
||||
it("classifies rows with an unknown workspaceId-shaped input safely", () => {
|
||||
// Registry-only rows can carry an empty cwd; no path rule may fire.
|
||||
expect(classifyWorkspace(row({ cwd: "", exists: false, env: { PI2_WORKSPACE_HIDE_OUTSIDE_ROOTS: "1" } }))).toEqual(
|
||||
{ visibility: "secondary", visibilityReason: "ghost" },
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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
@@ -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": "临时目录"
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user