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

+191
View File
@@ -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(
+146
View File
@@ -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();
});
});