diff --git a/web/src/components/app-shell.tsx b/web/src/components/app-shell.tsx index a60ec07..a68a970 100644 --- a/web/src/components/app-shell.tsx +++ b/web/src/components/app-shell.tsx @@ -17,7 +17,7 @@ import { useConnectionStore } from "@/stores/connection"; import { useSessionsStore } from "@/stores/sessions"; import { useWorkspacesStore } from "@/stores/workspaces"; import { Link, Outlet, useNavigate, useRouterState } from "@tanstack/react-router"; -import { useQuery } from "@tanstack/react-query"; +import { useQuery, useQueryClient } from "@tanstack/react-query"; function RouteTitle({ pathname }: { pathname: string }) { const { t } = useTranslation(); @@ -105,6 +105,7 @@ export function AppShell() { const wsState = useConnectionStore((state) => state.wsState); const setWsState = useConnectionStore((state) => state.setWsState); const disconnect = useConnectionStore((state) => state.disconnect); + const queryClient = useQueryClient(); const isConnect = pathname.startsWith("/connect"); // The chat page owns its own socket and already publishes wsState. const ownsSocket = !pathname.startsWith("/chat"); @@ -173,6 +174,9 @@ export function AppShell() { const client = new PiWsClient({ url: defaultWsUrl(), token: getDeviceToken(), + // `instance_state` frames otherwise go nowhere on these pages: the card + // grid reads the workspace row, so invalidate it (coalesced in ws.ts). + queryClient, handlers: { onState: (state: WsConnectionState) => { if (active) setWsState(state); @@ -192,7 +196,7 @@ export function AppShell() { active = false; client.close(); }; - }, [disconnect, href, isConnect, navigate, ownsSocket, paired, setWsState]); + }, [disconnect, href, isConnect, navigate, ownsSocket, paired, queryClient, setWsState]); /** ⌘K / Ctrl-K opens the palette on every navigation page (never on /connect). */ useEffect(() => { diff --git a/web/src/features/workspaces/commands.ts b/web/src/features/workspaces/commands.ts index 9208b2c..9ed3700 100644 --- a/web/src/features/workspaces/commands.ts +++ b/web/src/features/workspaces/commands.ts @@ -21,22 +21,61 @@ function extractWorkspaceId(result: CommandResult): string | undefined { ); } +/** Trailing slashes are noise; the daemon stores the canonical path either way. */ +function samePath(a: string, b: string): boolean { + const normalize = (value: string) => value.trim().replace(/\/+$/, ""); + return normalize(a) === normalize(b); +} + +function matchesName(workspace: WorkspaceInfo, name: string): boolean { + return (workspace.name?.trim() || workspace.alias?.trim()) === name; +} + function findCreated(list: WorkspaceInfo[], cwd: string, name: string): WorkspaceInfo | undefined { - const exact = list.find((item) => item.cwd === cwd && (name ? item.name === name : true)); - if (exact) return exact; - return list.find((item) => item.cwd === cwd); + // `~` paths never match on cwd (the daemon expands them), so fall back to the + // display name the caller just typed. + const byPathAndName = list.find((item) => samePath(item.cwd, cwd) && (name ? matchesName(item, name) : true)); + if (byPathAndName) return byPathAndName; + const byPath = list.find((item) => samePath(item.cwd, cwd)); + if (byPath) return byPath; + return name ? list.find((item) => matchesName(item, name)) : undefined; +} + +/** + * `workspace.add` succeeded but its instance did not start. The workspace id is + * already known, so the dialog can retry `instance.ensure` without adding twice. + */ +export class InstanceStartError extends Error { + readonly workspaceId: string; + /** Whatever `instance.ensure` threw (usually an `ApiError`). */ + readonly detail: unknown; + + constructor(workspaceId: string, detail: unknown) { + super(detail instanceof Error ? detail.message : String(detail)); + this.name = "InstanceStartError"; + this.workspaceId = workspaceId; + this.detail = detail; + } +} + +/** `instance.ensure` is idempotent (docs/protocol.md §3), so retrying it is safe. */ +export async function ensureInstance(workspaceId: string): Promise { + await api.command({ method: "instance.ensure", params: { workspaceId } }); } /** * `workspace.add` → resolve the new workspace id (the command response is not * required to carry it, so fall back to a fresh GET) → `instance.ensure`. + * + * The daemon owns path expansion: `~/…` and `~` are sent verbatim and resolved + * there, and the display name travels as `alias` (the field it persists). */ export async function openWorkspace(input: { cwd: string; name?: string }): Promise { const cwd = input.cwd.trim(); const name = input.name?.trim() ?? ""; const added = (await api.command({ method: "workspace.add", - params: { cwd, ...(name ? { name } : {}) }, + params: { cwd, ...(name ? { alias: name } : {}) }, })) as unknown as CommandResult; let workspaceId = extractWorkspaceId(added); @@ -48,7 +87,11 @@ export async function openWorkspace(input: { cwd: string; name?: string }): Prom throw new Error("workspace.add returned no workspace id"); } - await api.command({ method: "instance.ensure", params: { workspaceId } }); + try { + await ensureInstance(workspaceId); + } catch (error) { + throw new InstanceStartError(workspaceId, error); + } return workspaceId; } diff --git a/web/src/features/workspaces/new-workspace-dialog.tsx b/web/src/features/workspaces/new-workspace-dialog.tsx index 92dc446..b42ab52 100644 --- a/web/src/features/workspaces/new-workspace-dialog.tsx +++ b/web/src/features/workspaces/new-workspace-dialog.tsx @@ -1,5 +1,6 @@ import { useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; +import type { TFunction } from "i18next"; import { Icon } from "@/components/icons"; import { Button } from "@/components/ui/button"; @@ -7,6 +8,8 @@ import { Modal } from "@/components/ui/dialog"; import { Field, Input } from "@/components/ui/input"; import { ApiError, errorI18nKey } from "@/lib/api"; +import { ensureInstance, InstanceStartError } from "./commands"; + export interface NewWorkspaceInput { cwd: string; name?: string; @@ -16,15 +19,95 @@ export interface NewWorkspaceDialogProps { open: boolean; onOpenChange: (open: boolean) => void; onCreate: (input: NewWorkspaceInput) => Promise; + /** Runs after a successful retry of `instance.ensure`; the page finishes the open. */ + onRetryOpen?: (workspaceId: string) => void | Promise; } -/** Path is required, display name optional; validation is inline, not a toast. */ -export function NewWorkspaceDialog({ open, onOpenChange, onCreate }: NewWorkspaceDialogProps) { +/** Longest daemon message echoed back: they are debug strings, not UI copy. */ +const MAX_DETAIL = 200; + +/** + * A path the daemon accepts as typed: absolute, or `~` / `~/…` (it expands the + * home directory itself — `~user/…` is deliberately the daemon's call, not ours). + */ +export function isAbsoluteOrHomePath(value: string): boolean { + const trimmed = value.trim(); + return trimmed.startsWith("/") || trimmed === "~" || trimmed.startsWith("~/"); +} + +/** Shorten a daemon message; never echo a JSON blob back at the user. */ +export function humanDetail(message: string | undefined): string | undefined { + const text = message?.trim(); + if (!text) return undefined; + if (text.startsWith("{") || text.startsWith("[")) return undefined; + return text.length > MAX_DETAIL ? `${text.slice(0, MAX_DETAIL - 1)}…` : text; +} + +interface FailureText { + message: string; + /** Extra daemon text, rendered monospace and wrapped. */ + detail?: string; + /** The message itself embeds a reason, so it needs the monospace/wrap treatment. */ + reasonStyle?: boolean; +} + +function reasonFrom(error: ApiError): string | undefined { + const fromDetails = error.details?.["reason"]; + const raw = typeof fromDetails === "string" ? fromDetails : error.message; + return humanDetail(raw); +} + +/** + * Turn an open failure into something specific: code → status → daemon message. + * The user must learn *why* nothing happened, not read `E_FORBIDDEN`. + */ +export function describeOpenFailure(error: unknown, t: TFunction): FailureText { + if (!(error instanceof ApiError)) { + const detail = humanDetail(error instanceof Error ? error.message : undefined); + return { message: t("workspaces.addFailed"), ...(detail ? { detail } : {}) }; + } + + const message = error.message ?? ""; + const lower = message.toLowerCase(); + + if (error.status === 404 || error.code === "E_NOT_FOUND") { + return { message: t("workspaces.errNotFound") }; + } + + if (error.status === 403 || error.code === "E_FORBIDDEN") { + if (lower.includes("root")) return { message: t("workspaces.errOutsideRoots") }; + if (lower.includes("readable") || lower.includes("writable") || lower.includes("access")) { + return { message: t("workspaces.errPermission") }; + } + return { message: t(errorI18nKey(error.code)) }; + } + + if (error.status === 400 || error.code === "E_BAD_REQUEST") { + if (lower.includes("absolute") || lower.includes("~")) return { message: t("workspaces.errNotAbsolute") }; + return { message: t("workspaces.errBadPath") }; + } + + if (error.code === "E_INSTANCE_STARTING" || error.code === "E_INSTANCE_UNAVAILABLE") { + const reason = reasonFrom(error) ?? t("workspaces.errInstanceUnknown"); + return { message: t("workspaces.errInstanceFailed", { reason }), reasonStyle: true }; + } + + const detail = humanDetail(message); + return { message: t(errorI18nKey(error.code)), ...(detail ? { detail } : {}) }; +} + +/** + * Path is required, display name optional; validation is inline, not a toast. + * A failed open keeps the dialog open with the concrete reason, and a failure + * that happened after `workspace.add` offers a retry of `instance.ensure` only. + */ +export function NewWorkspaceDialog({ open, onOpenChange, onCreate, onRetryOpen }: NewWorkspaceDialogProps) { const { t } = useTranslation(); const [cwd, setCwd] = useState(""); const [name, setName] = useState(""); const [pathError, setPathError] = useState(null); - const [formError, setFormError] = useState(null); + const [failure, setFailure] = useState(null); + const [retryId, setRetryId] = useState(null); const [busy, setBusy] = useState(false); useEffect(() => { @@ -32,7 +115,8 @@ export function NewWorkspaceDialog({ open, onOpenChange, onCreate }: NewWorkspac setCwd(""); setName(""); setPathError(null); - setFormError(null); + setFailure(null); + setRetryId(null); setBusy(false); }, [open]); @@ -42,18 +126,44 @@ export function NewWorkspaceDialog({ open, onOpenChange, onCreate }: NewWorkspac const trimmed = cwd.trim(); if (!trimmed) { setPathError(t("workspaces.pathRequired")); - setFormError(null); + setFailure(null); + return; + } + if (!isAbsoluteOrHomePath(trimmed)) { + setPathError(t("workspaces.errNotAbsolute")); + setFailure(null); return; } setPathError(null); - setFormError(null); + setFailure(null); + setRetryId(null); setBusy(true); try { await onCreate({ cwd: trimmed, ...(name.trim() ? { name: name.trim() } : {}) }); onOpenChange(false); } catch (error) { - const key = error instanceof ApiError ? errorI18nKey(error.code) : "workspaces.addFailed"; - setFormError(t(key)); + if (error instanceof InstanceStartError) { + setRetryId(error.workspaceId); + setFailure(describeOpenFailure(error.detail, t)); + } else { + setFailure(describeOpenFailure(error, t)); + } + } finally { + setBusy(false); + } + } + + /** Re-run only `instance.ensure` for the workspace that was already created. */ + async function retry() { + if (!retryId || busy) return; + setBusy(true); + setFailure(null); + try { + await ensureInstance(retryId); + await onRetryOpen?.(retryId); + onOpenChange(false); + } catch (error) { + setFailure(describeOpenFailure(error, t)); } finally { setBusy(false); } @@ -69,6 +179,11 @@ export function NewWorkspaceDialog({ open, onOpenChange, onCreate }: NewWorkspac + {retryId ? ( + + ) : null} @@ -103,10 +218,19 @@ export function NewWorkspaceDialog({ open, onOpenChange, onCreate }: NewWorkspac - {formError ? ( -
+ {failure ? ( +
- {formError} + {failure.message} + {failure.detail ? ( + + {failure.detail} + + ) : null}
) : null} diff --git a/web/src/features/workspaces/workspace-card.tsx b/web/src/features/workspaces/workspace-card.tsx index 831e599..5016946 100644 --- a/web/src/features/workspaces/workspace-card.tsx +++ b/web/src/features/workspaces/workspace-card.tsx @@ -19,7 +19,10 @@ import { isSecondary, reasonLabelKey } from "./visibility"; */ export function instanceState(workspace: WorkspaceInfo): { status: DotStatus; labelKey: string } { if (!workspace.exists) return { status: "err", labelKey: "workspaces.instanceMissing" }; - switch (workspace.instance?.status) { + // No instance row at all means "not started yet": this daemon starts one on + // demand (opening the workspace), so "stopped" would be a lie. + if (!workspace.instance) return { status: "idle", labelKey: "workspaces.instanceNotStarted" }; + switch (workspace.instance.status) { case "ready": return { status: "ok", labelKey: "workspaces.instanceReady" }; case "starting": @@ -36,6 +39,20 @@ export function instanceState(workspace: WorkspaceInfo): { status: DotStatus; la } } +/** Statuses where the daemon's `instance.reason` explains the label below it. */ +const REASON_STATUSES: ReadonlySet = new Set(["degraded", "stopped", "unmanaged"]); + +/** + * The instance's own explanation, but only for the states where it adds + * information (a `ready` instance can still carry a stale reason). + */ +export function instanceReason(workspace: WorkspaceInfo): string | undefined { + const instance = workspace.instance; + const reason = instance?.reason?.trim(); + if (!instance || !reason) return undefined; + return REASON_STATUSES.has(instance.status) ? reason : undefined; +} + export interface WorkspaceCardProps { workspace: WorkspaceInfo; } @@ -56,6 +73,7 @@ export function WorkspaceCard({ workspace }: WorkspaceCardProps) { // *whether* they render at all (see features/workspaces/visibility.ts). const secondary = isSecondary(workspace); const reasonKey = secondary ? reasonLabelKey(workspace) : null; + const detail = instanceReason(workspace); return (
{workspace.cwd}
+ {detail ? ( + // Full text stays in `title`; the line itself is ellipsized by CSS. +
+ {detail} +
+ ) : null}
{count > 0 ? ( <> diff --git a/web/src/lib/ws.ts b/web/src/lib/ws.ts index f83af77..92b3d04 100644 --- a/web/src/lib/ws.ts +++ b/web/src/lib/ws.ts @@ -10,8 +10,45 @@ * The auth frame is the first frame on every socket, before any subscribe. */ +import type { QueryClient } from "@tanstack/react-query"; + export type WsConnectionState = "idle" | "connecting" | "authenticating" | "open" | "reconnecting" | "closed"; +/** + * Query keys a live `instance_state` makes stale. A workspace card renders + * `WorkspaceInfo.instance`, which the frame does not carry, so refetching the row + * is the only honest update. + */ +const INSTANCE_STATE_QUERY_KEYS: readonly (readonly string[])[] = [["workspaces"], ["health"]]; + +/** Burst window: `starting → ready` lands inside one startup step. */ +export const INSTANCE_STATE_COALESCE_MS = 250; + +let invalidationTimer: ReturnType | null = null; +let invalidationClient: QueryClient | null = null; + +/** + * Coalesce `instance_state` bursts into a single invalidation round. Module-level + * on purpose: the console opens more than one socket (shell probe + chat), and a + * per-client timer would refetch twice per state change. + */ +export function scheduleInstanceStateInvalidation( + queryClient: QueryClient, + delayMs: number = INSTANCE_STATE_COALESCE_MS, +): void { + invalidationClient = queryClient; + if (invalidationTimer !== null) return; + invalidationTimer = setTimeout(() => { + const client = invalidationClient; + invalidationTimer = null; + invalidationClient = null; + if (!client) return; + for (const queryKey of INSTANCE_STATE_QUERY_KEYS) { + void client.invalidateQueries({ queryKey: [...queryKey] }); + } + }, delayMs); +} + export interface WsFrame { v?: number; type: string; @@ -72,6 +109,13 @@ export interface PiWsOptions { authTimeoutMs?: number; /** 0 disables the keep-alive ping. */ heartbeatMs?: number; + /** + * Optional cache handle: an `instance_state` frame invalidates `['workspaces']` + * and `['health']` through it (coalesced) instead of being dropped. + */ + queryClient?: QueryClient | null; + /** Override for the `instance_state` coalescing window (tests). */ + instanceStateCoalesceMs?: number; handlers?: WsHandlers; } @@ -118,6 +162,8 @@ export class PiWsClient { private socket: WebSocketLike | null = null; private state: WsConnectionState = "idle"; private token: string | null; + private queryClient: QueryClient | null; + private readonly instanceStateCoalesceMs: number; private attempt = 0; private reconnectTimer: ReturnType | null = null; private authTimer: ReturnType | null = null; @@ -136,6 +182,8 @@ export class PiWsClient { this.backoffMultiplier = options.backoffMultiplier ?? 2; this.authTimeoutMs = options.authTimeoutMs ?? 8_000; this.heartbeatMs = options.heartbeatMs ?? 25_000; + this.queryClient = options.queryClient ?? null; + this.instanceStateCoalesceMs = options.instanceStateCoalesceMs ?? INSTANCE_STATE_COALESCE_MS; this.handlers = options.handlers ?? {}; } @@ -159,6 +207,11 @@ export class PiWsClient { this.token = token; } + /** Late-bound cache handle (the app mounts the provider after the client). */ + setQueryClient(queryClient: QueryClient | null): void { + this.queryClient = queryClient; + } + connect(): void { if (this.state === "connecting" || this.state === "authenticating" || this.state === "open") return; this.manuallyClosed = false; @@ -433,6 +486,15 @@ export class PiWsClient { } break; } + case "instance_state": { + // The frame carries the instance status (and its sessions), but the + // workspace row itself lives in `['workspaces']`; patch-free updates + // mean a refetch rather than a guess. Unknown frames stay ignored. + if (this.queryClient) { + scheduleInstanceStateInvalidation(this.queryClient, this.instanceStateCoalesceMs); + } + break; + } case "pong": case "presence": case "dropped": diff --git a/web/src/locales/en.json b/web/src/locales/en.json index 504f945..1512311 100644 --- a/web/src/locales/en.json +++ b/web/src/locales/en.json @@ -667,11 +667,19 @@ "workspaces.emptyText": "Open a working directory (cwd) to get started.", "workspaces.emptyTitle": "No workspaces yet", "workspaces.enter": "Enter →", + "workspaces.errPermission": "The daemon cannot read and write that directory", + "workspaces.errOutsideRoots": "That path is outside the workspace roots the daemon allows", + "workspaces.errNotFound": "No such directory on the server", + "workspaces.errNotAbsolute": "Enter an absolute path, or a path that starts with ~/", + "workspaces.errInstanceUnknown": "no reason reported by the server", + "workspaces.errInstanceFailed": "The workspace was added, but its Neovim instance did not start: {reason}", + "workspaces.errBadPath": "The server rejected that path. Check the directory name and try again.", "workspaces.hiddenHint": "These entries stay out of the list by default.", "workspaces.hideHidden": "Hide {n} hidden", "workspaces.idle": "Idle", "workspaces.instanceDegraded": "Instance degraded", "workspaces.instanceMissing": "Working directory is missing", + "workspaces.instanceNotStarted": "Not started · opens on demand", "workspaces.instanceReady": "Instance ready", "workspaces.instanceStarting": "Instance starting", "workspaces.instanceStopped": "Instance stopped", @@ -695,6 +703,7 @@ "workspaces.reason.outside-roots": "outside roots", "workspaces.reason.stale": "stale", "workspaces.reason.temp": "temp", + "workspaces.retry": "Retry starting Neovim", "workspaces.serverSummary": "{sessions} sessions · {running} running", "workspaces.sessionCount": "{n} sessions", "workspaces.sessionCount.one": "{n} session", diff --git a/web/src/locales/zh.json b/web/src/locales/zh.json index 7bac24a..008ca5e 100644 --- a/web/src/locales/zh.json +++ b/web/src/locales/zh.json @@ -667,11 +667,19 @@ "workspaces.emptyText": "打开一个工作目录(cwd)开始。", "workspaces.emptyTitle": "还没有工作空间", "workspaces.enter": "进入 →", + "workspaces.errPermission": "守护进程没有该目录的读写权限", + "workspaces.errOutsideRoots": "这个路径不在守护进程允许的工作区根目录内", + "workspaces.errNotFound": "服务器上找不到这个目录", + "workspaces.errNotAbsolute": "请填入绝对路径,或以 ~/ 开头的路径", + "workspaces.errInstanceUnknown": "服务器没有给出原因", + "workspaces.errInstanceFailed": "工作区已添加,但 Neovim 实例没能启动:{reason}", + "workspaces.errBadPath": "服务器不接受这个路径,请检查目录名后重试", "workspaces.hiddenHint": "这些条目默认不出现在列表中。", "workspaces.hideHidden": "隐藏 {n} 个隐藏项", "workspaces.idle": "空闲", "workspaces.instanceDegraded": "实例降级", "workspaces.instanceMissing": "工作目录不存在", + "workspaces.instanceNotStarted": "未启动 · 打开时自动启动", "workspaces.instanceReady": "实例已就绪", "workspaces.instanceStarting": "实例正在启动", "workspaces.instanceStopped": "实例已停止", @@ -695,6 +703,7 @@ "workspaces.reason.outside-roots": "根目录外", "workspaces.reason.stale": "长期未动", "workspaces.reason.temp": "临时目录", + "workspaces.retry": "重试启动 Neovim", "workspaces.serverSummary": "{sessions} 个会话 · {running} 个运行中", "workspaces.sessionCount": "{n} 个会话", "workspaces.sessionCount.one": "{n} 个会话", diff --git a/web/src/pages/workspaces.tsx b/web/src/pages/workspaces.tsx index ca5a3f7..add07e7 100644 --- a/web/src/pages/workspaces.tsx +++ b/web/src/pages/workspaces.tsx @@ -96,8 +96,13 @@ export function WorkspacesPage() { async function createWorkspace(input: NewWorkspaceInput) { const workspaceId = await openWorkspace(input); + await finishOpen(workspaceId, input.name?.trim() || basename(input.cwd)); + } + + /** Shared tail of a successful open: refresh the grid, toast, enter chat. */ + async function finishOpen(workspaceId: string, label: string) { await queryClient.invalidateQueries({ queryKey: ["workspaces"] }); - toast.success(t("workspaces.opened", { name: input.name?.trim() || basename(input.cwd) })); + toast.success(t("workspaces.opened", { name: label })); navigate({ href: `/chat?workspace=${encodeURIComponent(workspaceId)}` }); } @@ -228,7 +233,16 @@ export function WorkspacesPage() {
- + { + // The workspace already exists; the name is settled server-side. + const row = all.find((item) => item.workspaceId === workspaceId); + return finishOpen(workspaceId, row?.name?.trim() || (row ? basename(row.cwd) : workspaceId)); + }} + /> ); } diff --git a/web/src/styles/pages/workspaces.css b/web/src/styles/pages/workspaces.css index ddc1e2d..d984ce7 100644 --- a/web/src/styles/pages/workspaces.css +++ b/web/src/styles/pages/workspaces.css @@ -118,6 +118,13 @@ font-size: var(--fs-xs); line-height: 1.45; color: var(--muted-foreground); } +/* 实例自己给出的原因(degraded/stopped/unmanaged):单行截断,完整文本在 title 里 */ +.ws-card__note { + min-width: 0; + font-size: var(--fs-2xs); line-height: 1.45; + color: var(--destructive); + font-family: var(--font-mono); +} .ws-card__last { display: flex; align-items: baseline; gap: 6px; min-width: 0; @@ -244,12 +251,31 @@ .ws-form .field { margin-bottom: 0; } .ws-form__error { display: flex; align-items: flex-start; gap: var(--space-2); + flex-wrap: wrap; padding: var(--space-1) 0 var(--space-1) var(--space-3); border-left: 2px solid var(--destructive); color: var(--destructive); font-size: var(--fs-sm); } .ws-form__error svg { flex: none; margin-top: 2px; } +.ws-form__error .ws-form__message { min-width: 0; } +/* 守护进程的原文:等宽 + 换行,绝不二次截断成一行 */ +.ws-form__error--reason .ws-form__message { + white-space: pre-wrap; + overflow-wrap: anywhere; + word-break: break-word; + font-family: var(--font-mono); + font-size: var(--fs-xs); +} +.ws-form__detail { + flex: 1 1 100%; + margin-top: 2px; + padding-left: calc(var(--space-2) + 12px); + white-space: pre-wrap; + overflow-wrap: anywhere; + font-size: var(--fs-2xs); + color: var(--muted-foreground); +} .ws-modal-example { margin-top: calc(-1 * var(--space-2)); padding: 6px 9px; diff --git a/web/tests/workspaces-page.test.tsx b/web/tests/workspaces-page.test.tsx index 12bd14b..04fa25f 100644 --- a/web/tests/workspaces-page.test.tsx +++ b/web/tests/workspaces-page.test.tsx @@ -379,10 +379,201 @@ describe("WorkspacesPage", () => { const commands = commandCalls(fetchMock); expect(commands.map((command) => command.method)).toEqual(["workspace.add", "instance.ensure"]); + // The daemon persists the display name as `alias` (`name` is not a param). + expect(commands[0]?.params).toEqual({ cwd: "/work/new", alias: "New project" }); expect(commands[1]?.params).toEqual({ workspaceId: "ws-new" }); expect(await screen.findByText("Chat destination")).toBeInTheDocument(); }); + it("rejects a relative path inline instead of round-tripping to the daemon", async () => { + const fetchMock = mockApi([ + { path: "/api/v1/info", handler: () => ({ body: infoBody }) }, + { + path: "/api/v1/workspaces", + handler: () => ({ body: [workspace({ workspaceId: "ws-old", cwd: "/work/old", name: "Old project" })] }), + }, + recentRoute(), + ]); + + await renderPage(routes(), "/workspaces", { paired: true }); + await waitForCards(1); + + fireEvent.click(screen.getByRole("button", { name: "Open new workspace" })); + const dialog = await screen.findByRole("dialog"); + fireEvent.change(within(dialog).getByLabelText("Path"), { target: { value: "work/relative" } }); + fireEvent.click(within(dialog).getByRole("button", { name: "Open" })); + + expect( + await within(dialog).findByText("Enter an absolute path, or a path that starts with ~/"), + ).toBeInTheDocument(); + expect(commandCalls(fetchMock)).toHaveLength(0); + // Stays open so the path can be corrected in place. + expect(screen.getByRole("dialog")).toBeInTheDocument(); + }); + + it("sends a ~ path verbatim and lets the daemon expand it", async () => { + const fetchMock = mockApi([ + { path: "/api/v1/info", handler: () => ({ body: infoBody }) }, + { + path: "/api/v1/workspaces", + handler: () => ({ body: [workspace({ workspaceId: "ws-old", cwd: "/work/old", name: "Old project" })] }), + }, + recentRoute(), + { + method: "POST", + path: "/api/v1/cmd", + handler: ({ body }) => { + const command = body as { method?: string }; + if (command.method === "workspace.add") return { body: { accepted: true, workspaceId: "ws-home" } }; + return { body: { accepted: true } }; + }, + }, + ]); + + const { router } = await renderPage(routes(), "/workspaces", { paired: true }); + await waitForCards(1); + + fireEvent.click(screen.getByRole("button", { name: "Open new workspace" })); + const dialog = await screen.findByRole("dialog"); + fireEvent.change(within(dialog).getByLabelText("Path"), { target: { value: "~/Workspace/Misc/my-project" } }); + fireEvent.change(within(dialog).getByLabelText("Display name"), { target: { value: "My project" } }); + fireEvent.click(within(dialog).getByRole("button", { name: "Open" })); + + await waitFor(() => expect(router.state.location.pathname).toBe("/chat")); + const commands = commandCalls(fetchMock); + expect(commands.map((command) => command.method)).toEqual(["workspace.add", "instance.ensure"]); + // Verbatim `~`: the daemon owns home expansion, the browser must not guess. + expect(commands[0]?.params).toEqual({ cwd: "~/Workspace/Misc/my-project", alias: "My project" }); + expect(commands[1]?.params).toEqual({ workspaceId: "ws-home" }); + }); + + it("keeps the dialog open with the daemon reason, then retries only instance.ensure", async () => { + let ensures = 0; + let items = [workspace({ workspaceId: "ws-old", cwd: "/work/old", name: "Old project" })]; + const fetchMock = mockApi([ + { path: "/api/v1/info", handler: () => ({ body: infoBody }) }, + { path: "/api/v1/workspaces", handler: () => ({ body: items }) }, + recentRoute(), + { + method: "POST", + path: "/api/v1/cmd", + handler: ({ body }) => { + const command = body as { method?: string }; + if (command.method === "workspace.add") { + items = [...items, workspace({ workspaceId: "ws-new", cwd: "/work/new", name: "New project" })]; + return { body: { accepted: true, workspaceId: "ws-new" } }; + } + ensures += 1; + if (ensures === 1) { + return { + status: 503, + body: { + error: { + code: "E_INSTANCE_UNAVAILABLE", + message: "nvim exited during startup (code 1)", + retryable: true, + }, + }, + }; + } + return { body: { accepted: true } }; + }, + }, + ]); + + const { router } = await renderPage(routes(), "/workspaces", { paired: true }); + await waitForCards(1); + + fireEvent.click(screen.getByRole("button", { name: "Open new workspace" })); + const dialog = await screen.findByRole("dialog"); + fireEvent.change(within(dialog).getByLabelText("Path"), { target: { value: "/work/new" } }); + fireEvent.change(within(dialog).getByLabelText("Display name"), { target: { value: "New project" } }); + fireEvent.click(within(dialog).getByRole("button", { name: "Open" })); + + const alert = await within(dialog).findByTestId("workspace-form-error"); + // The reason the user can act on, not a code and never a JSON blob. + expect(alert).toHaveTextContent("nvim exited during startup (code 1)"); + expect(alert.textContent ?? "").not.toContain("E_INSTANCE_UNAVAILABLE"); + expect(alert.textContent ?? "").not.toContain("{"); + expect(alert.className).toContain("ws-form__error--reason"); + expect(screen.getByRole("dialog")).toBeInTheDocument(); + expect(router.state.location.pathname).toBe("/workspaces"); + + fireEvent.click(within(dialog).getByRole("button", { name: "Retry starting Neovim" })); + + await waitFor(() => expect(router.state.location.pathname).toBe("/chat")); + expect(router.state.location.href).toContain("workspace=ws-new"); + const commands = commandCalls(fetchMock); + // One extra instance.ensure only: the workspace was not added a second time. + expect(commands.map((command) => command.method)).toEqual(["workspace.add", "instance.ensure", "instance.ensure"]); + expect(commands[2]?.params).toEqual({ workspaceId: "ws-new" }); + }); + + it("renders a not-yet-started workspace as idle and explains a degraded instance", async () => { + const items = [ + workspace({ workspaceId: "ws-new", cwd: "/work/new", name: "Not started" }), + workspace({ + workspaceId: "ws-bad", + cwd: "/work/bad", + name: "Degraded", + instance: { + workspaceId: "ws-bad", + instanceId: "inst-bad", + status: "degraded", + nvimPid: 42, + pluginVersion: null, + hasUI: false, + attachedClients: 0, + listenAddr: null, + startedAt: 1_000, + reason: "plugin handshake timed out after 1500ms", + }, + }), + workspace({ + workspaceId: "ws-busy", + cwd: "/work/busy", + name: "Running", + instance: { + workspaceId: "ws-busy", + instanceId: "inst-busy", + status: "ready", + nvimPid: 43, + pluginVersion: "0.1.1", + hasUI: true, + attachedClients: 1, + listenAddr: "127.0.0.1:7779", + startedAt: 2_000, + reason: "stale startup note", + }, + }), + ]; + mockApi([ + { path: "/api/v1/info", handler: () => ({ body: infoBody }) }, + { path: "/api/v1/workspaces", handler: () => ({ body: items }) }, + recentRoute(), + ]); + + await renderPage(routes(), "/workspaces", { paired: true }); + await waitForCards(3); + + const rows = screen.getAllByTestId("workspace-row"); + const [notStarted, degraded, ready] = rows; + // No instance row means "opens on demand", not "stopped". + expect(notStarted?.querySelector(".ws-card__state .dot")).toHaveClass("dot--idle"); + expect(notStarted?.querySelector(".ws-card__state")).toHaveTextContent("Not started · opens on demand"); + expect(notStarted?.querySelector(".ws-card__state")).not.toHaveTextContent("Instance stopped"); + expect(notStarted?.querySelector('[data-testid="workspace-instance-reason"]')).toBeNull(); + + const reason = degraded?.querySelector('[data-testid="workspace-instance-reason"]'); + expect(reason).toHaveTextContent("plugin handshake timed out after 1500ms"); + expect(reason).toHaveAttribute("title", "plugin handshake timed out after 1500ms"); + expect(degraded?.querySelector(".ws-card__state")).toHaveTextContent("Instance degraded"); + + // A healthy instance keeps its plain label (a stale reason is not news). + expect(ready?.querySelector(".ws-card__state")).toHaveTextContent("Instance ready"); + expect(ready?.querySelector('[data-testid="workspace-instance-reason"]')).toBeNull(); + }); + it("redirects /workspace/:workspaceId deep links into chat", async () => { mockApi([{ path: "/api/v1/info", handler: () => ({ body: infoBody }) }]); const { router } = await renderPage( diff --git a/web/tests/ws.instance-state.test.ts b/web/tests/ws.instance-state.test.ts new file mode 100644 index 0000000..4048f35 --- /dev/null +++ b/web/tests/ws.instance-state.test.ts @@ -0,0 +1,146 @@ +import { QueryClient, QueryObserver } from "@tanstack/react-query"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import type { WorkspaceInfo } from "@/lib/protocol"; +import { PiWsClient, type WebSocketLike, type WsFrame } from "@/lib/ws"; + +/** Same fake socket as `ws.test.ts`: no real transport anywhere in unit tests. */ +class FakeSocket implements WebSocketLike { + readyState = 0; + sent: WsFrame[] = []; + closed = false; + onopen: ((event: unknown) => void) | null = null; + onmessage: ((event: { data: unknown }) => void) | null = null; + onclose: ((event: { code?: number; reason?: string }) => void) | null = null; + onerror: ((event: unknown) => void) | null = null; + + send(data: string): void { + this.sent.push(JSON.parse(data) as WsFrame); + } + + close(): void { + this.closed = true; + this.readyState = 3; + this.onclose?.({ code: 1000, reason: "closed" }); + } + + open(): void { + this.readyState = 1; + this.onopen?.({}); + } + + receive(frame: Record): void { + this.onmessage?.({ data: JSON.stringify(frame) }); + } +} + +/** Short window so the coalescing assertions stay fast without fake timers. */ +const COALESCE_MS = 20; + +function connect(queryClient?: QueryClient) { + const sockets: FakeSocket[] = []; + const client = new PiWsClient({ + url: "ws://127.0.0.1:7676/api/v1/ws", + token: "pkt_test", + heartbeatMs: 0, + instanceStateCoalesceMs: COALESCE_MS, + ...(queryClient ? { queryClient } : {}), + socketFactory: () => { + const socket = new FakeSocket(); + sockets.push(socket); + return socket; + }, + }); + client.connect(); + const socket = sockets[0]!; + socket.open(); + socket.receive({ v: 1, type: "hello_ack", payload: {} }); + return { client, socket }; +} + +/** Two queries the workspace page actually runs, observed the way the page does. */ +function observe(queryClient: QueryClient) { + const workspaces = vi.fn(async (): Promise => []); + const health = vi.fn(async () => ({ ok: true, items: [] })); + const observers = [ + new QueryObserver(queryClient, { queryKey: ["workspaces"], queryFn: workspaces }), + new QueryObserver(queryClient, { queryKey: ["health"], queryFn: health }), + ]; + const unsubscribes = observers.map((observer) => observer.subscribe(() => {})); + return { + workspaces, + health, + stop: () => { + for (const unsubscribe of unsubscribes) unsubscribe(); + }, + }; +} + +function newQueryClient() { + return new QueryClient({ + defaultOptions: { queries: { retry: false, staleTime: Infinity, gcTime: Infinity } }, + }); +} + +afterEach(() => { + vi.useRealTimers(); +}); + +describe("instance_state frames", () => { + it("refetches the workspaces list (and health) instead of being dropped", async () => { + const queryClient = newQueryClient(); + const observed = observe(queryClient); + await vi.waitFor(() => expect(observed.workspaces).toHaveBeenCalledTimes(1)); + expect(observed.health).toHaveBeenCalledTimes(1); + + const { client, socket } = connect(queryClient); + socket.receive({ + v: 1, + type: "instance_state", + workspaceId: "ws-1", + payload: { status: "ready", sessions: [] }, + }); + + // Invalidation, not a local patch: the row (and the health strip) refetch. + await vi.waitFor(() => expect(observed.workspaces).toHaveBeenCalledTimes(2)); + await vi.waitFor(() => expect(observed.health).toHaveBeenCalledTimes(2)); + + client.close(); + observed.stop(); + }); + + it("coalesces a startup burst into a single refetch round", async () => { + const queryClient = newQueryClient(); + const observed = observe(queryClient); + await vi.waitFor(() => expect(observed.workspaces).toHaveBeenCalledTimes(1)); + + const { client, socket } = connect(queryClient); + for (const status of ["starting", "ready", "degraded"]) { + socket.receive({ v: 1, type: "instance_state", workspaceId: "ws-1", payload: { status } }); + } + + await vi.waitFor(() => expect(observed.workspaces).toHaveBeenCalledTimes(2)); + // A burst must not fan out into one refetch per frame. + await new Promise((resolve) => setTimeout(resolve, COALESCE_MS * 3)); + expect(observed.workspaces).toHaveBeenCalledTimes(2); + expect(observed.health).toHaveBeenCalledTimes(2); + + client.close(); + observed.stop(); + }); + + it("stays tolerant without a query client and keeps ignoring unknown frames", () => { + const { client, socket } = connect(); + expect(client.getState()).toBe("open"); + + for (const type of ["instance_state", "mystery_frame", "presence", "pong"]) { + expect(() => socket.receive({ v: 1, type, payload: { status: "ready" } })).not.toThrow(); + } + expect(client.getState()).toBe("open"); + // Still usable afterwards: a second connection state change is still reported. + socket.receive({ v: 1, type: "error", payload: { code: "E_INTERNAL", message: "boom" } }); + expect(client.getState()).toBe("open"); + + client.close(); + }); +});