feat(web): explain a failed open, keep the dialog, and follow instance_state
Opening a project showed a toast on success and a bare code (`E_FORBIDDEN`) on failure: no reason, no retry, and a workspace card that kept claiming "Instance stopped" because `instance_state` frames were dropped by the socket layer. - The dialog validates a non-absolute path inline, sends `alias` (the field the daemon persists), maps the daemon's status/code/message to a specific sentence (`~` expansions, missing directory, roots allowlist, permissions), and keeps itself open on a spawn failure with the daemon's reason plus a retry that re-sends only `instance.ensure`. - `lib/ws` handles `instance_state` by invalidating `workspaces`/`health` (coalesced at 250 ms across sockets) so the grid reflects reality. - A never-started workspace renders as "not started · opens on demand" instead of "stopped", and a degraded/stopped instance shows `instance.reason`.
This commit is contained in:
1 parent
b95ff6055b
commit
d5d205a7eb
11 files changed
+673
-21
No files matched your search
@@ -17,7 +17,7 @@ import { useConnectionStore } from "@/stores/connection";
|
|||||||
import { useSessionsStore } from "@/stores/sessions";
|
import { useSessionsStore } from "@/stores/sessions";
|
||||||
import { useWorkspacesStore } from "@/stores/workspaces";
|
import { useWorkspacesStore } from "@/stores/workspaces";
|
||||||
import { Link, Outlet, useNavigate, useRouterState } from "@tanstack/react-router";
|
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 }) {
|
function RouteTitle({ pathname }: { pathname: string }) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
@@ -105,6 +105,7 @@ export function AppShell() {
|
|||||||
const wsState = useConnectionStore((state) => state.wsState);
|
const wsState = useConnectionStore((state) => state.wsState);
|
||||||
const setWsState = useConnectionStore((state) => state.setWsState);
|
const setWsState = useConnectionStore((state) => state.setWsState);
|
||||||
const disconnect = useConnectionStore((state) => state.disconnect);
|
const disconnect = useConnectionStore((state) => state.disconnect);
|
||||||
|
const queryClient = useQueryClient();
|
||||||
const isConnect = pathname.startsWith("/connect");
|
const isConnect = pathname.startsWith("/connect");
|
||||||
// The chat page owns its own socket and already publishes wsState.
|
// The chat page owns its own socket and already publishes wsState.
|
||||||
const ownsSocket = !pathname.startsWith("/chat");
|
const ownsSocket = !pathname.startsWith("/chat");
|
||||||
@@ -173,6 +174,9 @@ export function AppShell() {
|
|||||||
const client = new PiWsClient({
|
const client = new PiWsClient({
|
||||||
url: defaultWsUrl(),
|
url: defaultWsUrl(),
|
||||||
token: getDeviceToken(),
|
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: {
|
handlers: {
|
||||||
onState: (state: WsConnectionState) => {
|
onState: (state: WsConnectionState) => {
|
||||||
if (active) setWsState(state);
|
if (active) setWsState(state);
|
||||||
@@ -192,7 +196,7 @@ export function AppShell() {
|
|||||||
active = false;
|
active = false;
|
||||||
client.close();
|
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). */
|
/** ⌘K / Ctrl-K opens the palette on every navigation page (never on /connect). */
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|||||||
@@ -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 {
|
function findCreated(list: WorkspaceInfo[], cwd: string, name: string): WorkspaceInfo | undefined {
|
||||||
const exact = list.find((item) => item.cwd === cwd && (name ? item.name === name : true));
|
// `~` paths never match on cwd (the daemon expands them), so fall back to the
|
||||||
if (exact) return exact;
|
// display name the caller just typed.
|
||||||
return list.find((item) => item.cwd === cwd);
|
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<void> {
|
||||||
|
await api.command({ method: "instance.ensure", params: { workspaceId } });
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* `workspace.add` → resolve the new workspace id (the command response is not
|
* `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`.
|
* 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<string> {
|
export async function openWorkspace(input: { cwd: string; name?: string }): Promise<string> {
|
||||||
const cwd = input.cwd.trim();
|
const cwd = input.cwd.trim();
|
||||||
const name = input.name?.trim() ?? "";
|
const name = input.name?.trim() ?? "";
|
||||||
const added = (await api.command({
|
const added = (await api.command({
|
||||||
method: "workspace.add",
|
method: "workspace.add",
|
||||||
params: { cwd, ...(name ? { name } : {}) },
|
params: { cwd, ...(name ? { alias: name } : {}) },
|
||||||
})) as unknown as CommandResult;
|
})) as unknown as CommandResult;
|
||||||
|
|
||||||
let workspaceId = extractWorkspaceId(added);
|
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");
|
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;
|
return workspaceId;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
import type { TFunction } from "i18next";
|
||||||
|
|
||||||
import { Icon } from "@/components/icons";
|
import { Icon } from "@/components/icons";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
@@ -7,6 +8,8 @@ import { Modal } from "@/components/ui/dialog";
|
|||||||
import { Field, Input } from "@/components/ui/input";
|
import { Field, Input } from "@/components/ui/input";
|
||||||
import { ApiError, errorI18nKey } from "@/lib/api";
|
import { ApiError, errorI18nKey } from "@/lib/api";
|
||||||
|
|
||||||
|
import { ensureInstance, InstanceStartError } from "./commands";
|
||||||
|
|
||||||
export interface NewWorkspaceInput {
|
export interface NewWorkspaceInput {
|
||||||
cwd: string;
|
cwd: string;
|
||||||
name?: string;
|
name?: string;
|
||||||
@@ -16,15 +19,95 @@ export interface NewWorkspaceDialogProps {
|
|||||||
open: boolean;
|
open: boolean;
|
||||||
onOpenChange: (open: boolean) => void;
|
onOpenChange: (open: boolean) => void;
|
||||||
onCreate: (input: NewWorkspaceInput) => Promise<void>;
|
onCreate: (input: NewWorkspaceInput) => Promise<void>;
|
||||||
|
/** Runs after a successful retry of `instance.ensure`; the page finishes the open. */
|
||||||
|
onRetryOpen?: (workspaceId: string) => void | Promise<void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Path is required, display name optional; validation is inline, not a toast. */
|
/** Longest daemon message echoed back: they are debug strings, not UI copy. */
|
||||||
export function NewWorkspaceDialog({ open, onOpenChange, onCreate }: NewWorkspaceDialogProps) {
|
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 { t } = useTranslation();
|
||||||
const [cwd, setCwd] = useState("");
|
const [cwd, setCwd] = useState("");
|
||||||
const [name, setName] = useState("");
|
const [name, setName] = useState("");
|
||||||
const [pathError, setPathError] = useState<string | null>(null);
|
const [pathError, setPathError] = useState<string | null>(null);
|
||||||
const [formError, setFormError] = useState<string | null>(null);
|
const [failure, setFailure] = useState<FailureText | null>(null);
|
||||||
|
const [retryId, setRetryId] = useState<string | null>(null);
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -32,7 +115,8 @@ export function NewWorkspaceDialog({ open, onOpenChange, onCreate }: NewWorkspac
|
|||||||
setCwd("");
|
setCwd("");
|
||||||
setName("");
|
setName("");
|
||||||
setPathError(null);
|
setPathError(null);
|
||||||
setFormError(null);
|
setFailure(null);
|
||||||
|
setRetryId(null);
|
||||||
setBusy(false);
|
setBusy(false);
|
||||||
}, [open]);
|
}, [open]);
|
||||||
|
|
||||||
@@ -42,18 +126,44 @@ export function NewWorkspaceDialog({ open, onOpenChange, onCreate }: NewWorkspac
|
|||||||
const trimmed = cwd.trim();
|
const trimmed = cwd.trim();
|
||||||
if (!trimmed) {
|
if (!trimmed) {
|
||||||
setPathError(t("workspaces.pathRequired"));
|
setPathError(t("workspaces.pathRequired"));
|
||||||
setFormError(null);
|
setFailure(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!isAbsoluteOrHomePath(trimmed)) {
|
||||||
|
setPathError(t("workspaces.errNotAbsolute"));
|
||||||
|
setFailure(null);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setPathError(null);
|
setPathError(null);
|
||||||
setFormError(null);
|
setFailure(null);
|
||||||
|
setRetryId(null);
|
||||||
setBusy(true);
|
setBusy(true);
|
||||||
try {
|
try {
|
||||||
await onCreate({ cwd: trimmed, ...(name.trim() ? { name: name.trim() } : {}) });
|
await onCreate({ cwd: trimmed, ...(name.trim() ? { name: name.trim() } : {}) });
|
||||||
onOpenChange(false);
|
onOpenChange(false);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const key = error instanceof ApiError ? errorI18nKey(error.code) : "workspaces.addFailed";
|
if (error instanceof InstanceStartError) {
|
||||||
setFormError(t(key));
|
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 {
|
} finally {
|
||||||
setBusy(false);
|
setBusy(false);
|
||||||
}
|
}
|
||||||
@@ -69,6 +179,11 @@ export function NewWorkspaceDialog({ open, onOpenChange, onCreate }: NewWorkspac
|
|||||||
<Button variant="ghost" onClick={() => onOpenChange(false)} disabled={busy}>
|
<Button variant="ghost" onClick={() => onOpenChange(false)} disabled={busy}>
|
||||||
{t("common.cancel")}
|
{t("common.cancel")}
|
||||||
</Button>
|
</Button>
|
||||||
|
{retryId ? (
|
||||||
|
<Button variant="ghost" onClick={() => void retry()} disabled={busy} data-testid="workspace-retry-instance">
|
||||||
|
{t("workspaces.retry")}
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
<Button variant="primary" type="submit" form="new-workspace-form" disabled={busy}>
|
<Button variant="primary" type="submit" form="new-workspace-form" disabled={busy}>
|
||||||
{busy ? t("workspaces.creating") : t("common.open")}
|
{busy ? t("workspaces.creating") : t("common.open")}
|
||||||
</Button>
|
</Button>
|
||||||
@@ -103,10 +218,19 @@ export function NewWorkspaceDialog({ open, onOpenChange, onCreate }: NewWorkspac
|
|||||||
<div className="ws-modal-example mono" aria-hidden="true">
|
<div className="ws-modal-example mono" aria-hidden="true">
|
||||||
~/Workspace/Misc/my-project
|
~/Workspace/Misc/my-project
|
||||||
</div>
|
</div>
|
||||||
{formError ? (
|
{failure ? (
|
||||||
<div className="ws-form__error" role="alert">
|
<div
|
||||||
|
className={failure.reasonStyle ? "ws-form__error ws-form__error--reason" : "ws-form__error"}
|
||||||
|
role="alert"
|
||||||
|
data-testid="workspace-form-error"
|
||||||
|
>
|
||||||
<Icon name="alert" />
|
<Icon name="alert" />
|
||||||
<span>{formError}</span>
|
<span className="ws-form__message">{failure.message}</span>
|
||||||
|
{failure.detail ? (
|
||||||
|
<span className="ws-form__detail mono" title={failure.detail}>
|
||||||
|
{failure.detail}
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
@@ -19,7 +19,10 @@ import { isSecondary, reasonLabelKey } from "./visibility";
|
|||||||
*/
|
*/
|
||||||
export function instanceState(workspace: WorkspaceInfo): { status: DotStatus; labelKey: string } {
|
export function instanceState(workspace: WorkspaceInfo): { status: DotStatus; labelKey: string } {
|
||||||
if (!workspace.exists) return { status: "err", labelKey: "workspaces.instanceMissing" };
|
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":
|
case "ready":
|
||||||
return { status: "ok", labelKey: "workspaces.instanceReady" };
|
return { status: "ok", labelKey: "workspaces.instanceReady" };
|
||||||
case "starting":
|
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<string> = 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 {
|
export interface WorkspaceCardProps {
|
||||||
workspace: WorkspaceInfo;
|
workspace: WorkspaceInfo;
|
||||||
}
|
}
|
||||||
@@ -56,6 +73,7 @@ export function WorkspaceCard({ workspace }: WorkspaceCardProps) {
|
|||||||
// *whether* they render at all (see features/workspaces/visibility.ts).
|
// *whether* they render at all (see features/workspaces/visibility.ts).
|
||||||
const secondary = isSecondary(workspace);
|
const secondary = isSecondary(workspace);
|
||||||
const reasonKey = secondary ? reasonLabelKey(workspace) : null;
|
const reasonKey = secondary ? reasonLabelKey(workspace) : null;
|
||||||
|
const detail = instanceReason(workspace);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Link
|
<Link
|
||||||
@@ -80,6 +98,12 @@ export function WorkspaceCard({ workspace }: WorkspaceCardProps) {
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="ws-card__cwd mono truncate">{workspace.cwd}</div>
|
<div className="ws-card__cwd mono truncate">{workspace.cwd}</div>
|
||||||
|
{detail ? (
|
||||||
|
// Full text stays in `title`; the line itself is ellipsized by CSS.
|
||||||
|
<div className="ws-card__note truncate" title={detail} data-testid="workspace-instance-reason">
|
||||||
|
{detail}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
<div className="ws-card__last">
|
<div className="ws-card__last">
|
||||||
{count > 0 ? (
|
{count > 0 ? (
|
||||||
<>
|
<>
|
||||||
|
|||||||
@@ -10,8 +10,45 @@
|
|||||||
* The auth frame is the first frame on every socket, before any subscribe.
|
* 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";
|
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<typeof setTimeout> | 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 {
|
export interface WsFrame {
|
||||||
v?: number;
|
v?: number;
|
||||||
type: string;
|
type: string;
|
||||||
@@ -72,6 +109,13 @@ export interface PiWsOptions {
|
|||||||
authTimeoutMs?: number;
|
authTimeoutMs?: number;
|
||||||
/** 0 disables the keep-alive ping. */
|
/** 0 disables the keep-alive ping. */
|
||||||
heartbeatMs?: number;
|
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;
|
handlers?: WsHandlers;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -118,6 +162,8 @@ export class PiWsClient {
|
|||||||
private socket: WebSocketLike | null = null;
|
private socket: WebSocketLike | null = null;
|
||||||
private state: WsConnectionState = "idle";
|
private state: WsConnectionState = "idle";
|
||||||
private token: string | null;
|
private token: string | null;
|
||||||
|
private queryClient: QueryClient | null;
|
||||||
|
private readonly instanceStateCoalesceMs: number;
|
||||||
private attempt = 0;
|
private attempt = 0;
|
||||||
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
private authTimer: ReturnType<typeof setTimeout> | null = null;
|
private authTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
@@ -136,6 +182,8 @@ export class PiWsClient {
|
|||||||
this.backoffMultiplier = options.backoffMultiplier ?? 2;
|
this.backoffMultiplier = options.backoffMultiplier ?? 2;
|
||||||
this.authTimeoutMs = options.authTimeoutMs ?? 8_000;
|
this.authTimeoutMs = options.authTimeoutMs ?? 8_000;
|
||||||
this.heartbeatMs = options.heartbeatMs ?? 25_000;
|
this.heartbeatMs = options.heartbeatMs ?? 25_000;
|
||||||
|
this.queryClient = options.queryClient ?? null;
|
||||||
|
this.instanceStateCoalesceMs = options.instanceStateCoalesceMs ?? INSTANCE_STATE_COALESCE_MS;
|
||||||
this.handlers = options.handlers ?? {};
|
this.handlers = options.handlers ?? {};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -159,6 +207,11 @@ export class PiWsClient {
|
|||||||
this.token = token;
|
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 {
|
connect(): void {
|
||||||
if (this.state === "connecting" || this.state === "authenticating" || this.state === "open") return;
|
if (this.state === "connecting" || this.state === "authenticating" || this.state === "open") return;
|
||||||
this.manuallyClosed = false;
|
this.manuallyClosed = false;
|
||||||
@@ -433,6 +486,15 @@ export class PiWsClient {
|
|||||||
}
|
}
|
||||||
break;
|
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 "pong":
|
||||||
case "presence":
|
case "presence":
|
||||||
case "dropped":
|
case "dropped":
|
||||||
|
|||||||
@@ -667,11 +667,19 @@
|
|||||||
"workspaces.emptyText": "Open a working directory (cwd) to get started.",
|
"workspaces.emptyText": "Open a working directory (cwd) to get started.",
|
||||||
"workspaces.emptyTitle": "No workspaces yet",
|
"workspaces.emptyTitle": "No workspaces yet",
|
||||||
"workspaces.enter": "Enter →",
|
"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.hiddenHint": "These entries stay out of the list by default.",
|
||||||
"workspaces.hideHidden": "Hide {n} hidden",
|
"workspaces.hideHidden": "Hide {n} hidden",
|
||||||
"workspaces.idle": "Idle",
|
"workspaces.idle": "Idle",
|
||||||
"workspaces.instanceDegraded": "Instance degraded",
|
"workspaces.instanceDegraded": "Instance degraded",
|
||||||
"workspaces.instanceMissing": "Working directory is missing",
|
"workspaces.instanceMissing": "Working directory is missing",
|
||||||
|
"workspaces.instanceNotStarted": "Not started · opens on demand",
|
||||||
"workspaces.instanceReady": "Instance ready",
|
"workspaces.instanceReady": "Instance ready",
|
||||||
"workspaces.instanceStarting": "Instance starting",
|
"workspaces.instanceStarting": "Instance starting",
|
||||||
"workspaces.instanceStopped": "Instance stopped",
|
"workspaces.instanceStopped": "Instance stopped",
|
||||||
@@ -695,6 +703,7 @@
|
|||||||
"workspaces.reason.outside-roots": "outside roots",
|
"workspaces.reason.outside-roots": "outside roots",
|
||||||
"workspaces.reason.stale": "stale",
|
"workspaces.reason.stale": "stale",
|
||||||
"workspaces.reason.temp": "temp",
|
"workspaces.reason.temp": "temp",
|
||||||
|
"workspaces.retry": "Retry starting Neovim",
|
||||||
"workspaces.serverSummary": "{sessions} sessions · {running} running",
|
"workspaces.serverSummary": "{sessions} sessions · {running} running",
|
||||||
"workspaces.sessionCount": "{n} sessions",
|
"workspaces.sessionCount": "{n} sessions",
|
||||||
"workspaces.sessionCount.one": "{n} session",
|
"workspaces.sessionCount.one": "{n} session",
|
||||||
|
|||||||
@@ -667,11 +667,19 @@
|
|||||||
"workspaces.emptyText": "打开一个工作目录(cwd)开始。",
|
"workspaces.emptyText": "打开一个工作目录(cwd)开始。",
|
||||||
"workspaces.emptyTitle": "还没有工作空间",
|
"workspaces.emptyTitle": "还没有工作空间",
|
||||||
"workspaces.enter": "进入 →",
|
"workspaces.enter": "进入 →",
|
||||||
|
"workspaces.errPermission": "守护进程没有该目录的读写权限",
|
||||||
|
"workspaces.errOutsideRoots": "这个路径不在守护进程允许的工作区根目录内",
|
||||||
|
"workspaces.errNotFound": "服务器上找不到这个目录",
|
||||||
|
"workspaces.errNotAbsolute": "请填入绝对路径,或以 ~/ 开头的路径",
|
||||||
|
"workspaces.errInstanceUnknown": "服务器没有给出原因",
|
||||||
|
"workspaces.errInstanceFailed": "工作区已添加,但 Neovim 实例没能启动:{reason}",
|
||||||
|
"workspaces.errBadPath": "服务器不接受这个路径,请检查目录名后重试",
|
||||||
"workspaces.hiddenHint": "这些条目默认不出现在列表中。",
|
"workspaces.hiddenHint": "这些条目默认不出现在列表中。",
|
||||||
"workspaces.hideHidden": "隐藏 {n} 个隐藏项",
|
"workspaces.hideHidden": "隐藏 {n} 个隐藏项",
|
||||||
"workspaces.idle": "空闲",
|
"workspaces.idle": "空闲",
|
||||||
"workspaces.instanceDegraded": "实例降级",
|
"workspaces.instanceDegraded": "实例降级",
|
||||||
"workspaces.instanceMissing": "工作目录不存在",
|
"workspaces.instanceMissing": "工作目录不存在",
|
||||||
|
"workspaces.instanceNotStarted": "未启动 · 打开时自动启动",
|
||||||
"workspaces.instanceReady": "实例已就绪",
|
"workspaces.instanceReady": "实例已就绪",
|
||||||
"workspaces.instanceStarting": "实例正在启动",
|
"workspaces.instanceStarting": "实例正在启动",
|
||||||
"workspaces.instanceStopped": "实例已停止",
|
"workspaces.instanceStopped": "实例已停止",
|
||||||
@@ -695,6 +703,7 @@
|
|||||||
"workspaces.reason.outside-roots": "根目录外",
|
"workspaces.reason.outside-roots": "根目录外",
|
||||||
"workspaces.reason.stale": "长期未动",
|
"workspaces.reason.stale": "长期未动",
|
||||||
"workspaces.reason.temp": "临时目录",
|
"workspaces.reason.temp": "临时目录",
|
||||||
|
"workspaces.retry": "重试启动 Neovim",
|
||||||
"workspaces.serverSummary": "{sessions} 个会话 · {running} 个运行中",
|
"workspaces.serverSummary": "{sessions} 个会话 · {running} 个运行中",
|
||||||
"workspaces.sessionCount": "{n} 个会话",
|
"workspaces.sessionCount": "{n} 个会话",
|
||||||
"workspaces.sessionCount.one": "{n} 个会话",
|
"workspaces.sessionCount.one": "{n} 个会话",
|
||||||
|
|||||||
@@ -96,8 +96,13 @@ export function WorkspacesPage() {
|
|||||||
|
|
||||||
async function createWorkspace(input: NewWorkspaceInput) {
|
async function createWorkspace(input: NewWorkspaceInput) {
|
||||||
const workspaceId = await openWorkspace(input);
|
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"] });
|
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)}` });
|
navigate({ href: `/chat?workspace=${encodeURIComponent(workspaceId)}` });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -228,7 +233,16 @@ export function WorkspacesPage() {
|
|||||||
<ActivityColumn workspaces={items} />
|
<ActivityColumn workspaces={items} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<NewWorkspaceDialog open={dialogOpen} onOpenChange={setDialogOpen} onCreate={createWorkspace} />
|
<NewWorkspaceDialog
|
||||||
|
open={dialogOpen}
|
||||||
|
onOpenChange={setDialogOpen}
|
||||||
|
onCreate={createWorkspace}
|
||||||
|
onRetryOpen={(workspaceId) => {
|
||||||
|
// 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));
|
||||||
|
}}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -118,6 +118,13 @@
|
|||||||
font-size: var(--fs-xs); line-height: 1.45;
|
font-size: var(--fs-xs); line-height: 1.45;
|
||||||
color: var(--muted-foreground);
|
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 {
|
.ws-card__last {
|
||||||
display: flex; align-items: baseline; gap: 6px;
|
display: flex; align-items: baseline; gap: 6px;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
@@ -244,12 +251,31 @@
|
|||||||
.ws-form .field { margin-bottom: 0; }
|
.ws-form .field { margin-bottom: 0; }
|
||||||
.ws-form__error {
|
.ws-form__error {
|
||||||
display: flex; align-items: flex-start; gap: var(--space-2);
|
display: flex; align-items: flex-start; gap: var(--space-2);
|
||||||
|
flex-wrap: wrap;
|
||||||
padding: var(--space-1) 0 var(--space-1) var(--space-3);
|
padding: var(--space-1) 0 var(--space-1) var(--space-3);
|
||||||
border-left: 2px solid var(--destructive);
|
border-left: 2px solid var(--destructive);
|
||||||
color: var(--destructive);
|
color: var(--destructive);
|
||||||
font-size: var(--fs-sm);
|
font-size: var(--fs-sm);
|
||||||
}
|
}
|
||||||
.ws-form__error svg { flex: none; margin-top: 2px; }
|
.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 {
|
.ws-modal-example {
|
||||||
margin-top: calc(-1 * var(--space-2));
|
margin-top: calc(-1 * var(--space-2));
|
||||||
padding: 6px 9px;
|
padding: 6px 9px;
|
||||||
|
|||||||
@@ -379,10 +379,201 @@ describe("WorkspacesPage", () => {
|
|||||||
|
|
||||||
const commands = commandCalls(fetchMock);
|
const commands = commandCalls(fetchMock);
|
||||||
expect(commands.map((command) => command.method)).toEqual(["workspace.add", "instance.ensure"]);
|
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(commands[1]?.params).toEqual({ workspaceId: "ws-new" });
|
||||||
expect(await screen.findByText("Chat destination")).toBeInTheDocument();
|
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 () => {
|
it("redirects /workspace/:workspaceId deep links into chat", async () => {
|
||||||
mockApi([{ path: "/api/v1/info", handler: () => ({ body: infoBody }) }]);
|
mockApi([{ path: "/api/v1/info", handler: () => ({ body: infoBody }) }]);
|
||||||
const { router } = await renderPage(
|
const { router } = await renderPage(
|
||||||
|
|||||||
@@ -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<string, unknown>): 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<WorkspaceInfo[]> => []);
|
||||||
|
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();
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user