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:
yuez committed 2026-10-28 17:32:53 +08:00
1 parent b95ff6055b
commit d5d205a7eb
11 files changed
+673 -21

No files matched your search

+48 -5
View File
@@ -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<void> {
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<string> {
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;
}
@@ -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<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. */
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<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);
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
<Button variant="ghost" onClick={() => onOpenChange(false)} disabled={busy}>
{t("common.cancel")}
</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}>
{busy ? t("workspaces.creating") : t("common.open")}
</Button>
@@ -103,10 +218,19 @@ export function NewWorkspaceDialog({ open, onOpenChange, onCreate }: NewWorkspac
<div className="ws-modal-example mono" aria-hidden="true">
~/Workspace/Misc/my-project
</div>
{formError ? (
<div className="ws-form__error" role="alert">
{failure ? (
<div
className={failure.reasonStyle ? "ws-form__error ws-form__error--reason" : "ws-form__error"}
role="alert"
data-testid="workspace-form-error"
>
<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>
) : null}
</form>
+25 -1
View File
@@ -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<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 {
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 (
<Link
@@ -80,6 +98,12 @@ export function WorkspaceCard({ workspace }: WorkspaceCardProps) {
</span>
</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">
{count > 0 ? (
<>