fix(web): make the web console work end-to-end
- Pair through the public POST /api/v1/pair and persist the device scopes; keep the allow-listed next deep link. Rename the manual field to pairing code. - Authenticate the WebSocket with the raw device token (strip Bearer) and recover from a 401 by clearing the connection once. - Fix chat payloads: setModel/setThinking, attention/diff responses, subagent dispatch items, queue ids/mode, task output and WS resume since. - Render exactly one assistant message per turn: one-to-one snapshot/history merge plus a stale-delta guard after message_end (fixes PONGONG). - Fix dialogs (content above the overlay), unknown-session deep links (error + retry, no silent fallback), device list/revoke, status identity and live pairing code, reconnect banner and Playwright selectors.
This commit is contained in:
1 parent
5572ac0d84
commit
0ef019f58d
57 files changed
+3549
-684
No files matched your search
@@ -1,4 +1,4 @@
|
||||
import type { Batch, Entry, SessionState, Subagent, TodoItem } from "@protocol/types";
|
||||
import type { Batch, Entry, SessionState, Subagent, TaskItem, TodoItem } from "@protocol/types";
|
||||
|
||||
import { emptySessionState } from "@/features/chat/session-state";
|
||||
|
||||
@@ -27,6 +27,31 @@ export function subagentFixture(overrides: Partial<Subagent> = {}): Subagent {
|
||||
};
|
||||
}
|
||||
|
||||
export function taskFixture(overrides: Partial<TaskItem> = {}): TaskItem {
|
||||
return {
|
||||
id: "t1",
|
||||
command: "pnpm test",
|
||||
status: "completed",
|
||||
startTime: Date.now() - 5_000,
|
||||
durationMs: 4_200,
|
||||
exitCode: 0,
|
||||
outputFile: "/tmp/pi2-task-t1.log",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
/** `task.output` ack for `taskFixture()`. */
|
||||
export function taskOutputFixture(overrides: Record<string, unknown> = {}): Record<string, unknown> {
|
||||
return {
|
||||
output: "$ pnpm test\n42 passed",
|
||||
outputFile: "/tmp/pi2-task-t1.log",
|
||||
status: "completed",
|
||||
exitCode: 0,
|
||||
durationMs: 4_200,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
export function todoFixture(): TodoItem[] {
|
||||
return [
|
||||
{ content: "Inspect callers", status: "completed" },
|
||||
|
||||
@@ -28,7 +28,7 @@ function attention(overrides: Partial<AttentionItem> = {}): AttentionItem {
|
||||
}
|
||||
|
||||
describe("attention dialog", () => {
|
||||
it("renders the request and responds with the chosen option", async () => {
|
||||
it("renders the server title/options and answers `select` with the option id", async () => {
|
||||
const item = attention();
|
||||
const onRespond = vi.fn();
|
||||
render(
|
||||
@@ -40,8 +40,31 @@ describe("attention dialog", () => {
|
||||
);
|
||||
|
||||
expect(await screen.findByText("Run this command?")).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Allow once" }));
|
||||
expect(onRespond).toHaveBeenCalledWith(item, "allow-once");
|
||||
const option = screen.getByRole("button", { name: "Allow once" });
|
||||
expect(option).toHaveAttribute("data-option-id", "allow-once");
|
||||
|
||||
fireEvent.click(option);
|
||||
// `pi.attention.resolve` expects `{value: <option id>}`.
|
||||
expect(onRespond).toHaveBeenCalledWith(item, { value: "allow-once" });
|
||||
});
|
||||
|
||||
it("answers `confirm` with `{confirmed}` and cancels with `{cancelled}`", async () => {
|
||||
const item = attention({ method: "confirm", options: undefined, title: "Proceed?" });
|
||||
const onRespond = vi.fn();
|
||||
render(
|
||||
<AttentionDialog
|
||||
session={sessionFixture({ attention: [item] })}
|
||||
onRespond={onRespond}
|
||||
onRemoteResolved={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(await screen.findByText("Proceed?")).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Confirm" }));
|
||||
expect(onRespond).toHaveBeenLastCalledWith(item, { confirmed: true });
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
|
||||
expect(onRespond).toHaveBeenLastCalledWith(item, { cancelled: true });
|
||||
});
|
||||
|
||||
it("closes and reports when another client resolves the request", async () => {
|
||||
@@ -57,6 +80,7 @@ describe("attention dialog", () => {
|
||||
expect(await screen.findByText("Run this command?")).toBeInTheDocument();
|
||||
expect(onRemoteResolved).not.toHaveBeenCalled();
|
||||
|
||||
// `pi2:attention_resolved` drops the request from `session.attention`.
|
||||
rerender(
|
||||
<AttentionDialog
|
||||
session={sessionFixture({ attention: [] })}
|
||||
@@ -67,6 +91,19 @@ describe("attention dialog", () => {
|
||||
await waitFor(() => expect(onRemoteResolved).toHaveBeenCalledWith("att-1"));
|
||||
});
|
||||
|
||||
it("closes itself when the server timeout has elapsed", async () => {
|
||||
const item = attention({ timeoutSec: 1, receivedAt: Date.now() - 5_000 });
|
||||
render(
|
||||
<AttentionDialog
|
||||
session={sessionFixture({ attention: [item] })}
|
||||
onRespond={vi.fn()}
|
||||
onRemoteResolved={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() => expect(screen.queryByText("Run this command?")).not.toBeInTheDocument());
|
||||
});
|
||||
|
||||
it("renders the diff review variant and sends the plugin's review JSON", async () => {
|
||||
const item = attention({
|
||||
method: "diff",
|
||||
@@ -85,10 +122,37 @@ describe("attention dialog", () => {
|
||||
);
|
||||
|
||||
expect(await screen.findByText("src/auth.ts")).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Accept all" }));
|
||||
const acceptAll = screen.getByRole("button", { name: "Accept all" });
|
||||
expect(acceptAll).toHaveAttribute("data-decision", "accept");
|
||||
|
||||
fireEvent.click(acceptAll);
|
||||
expect(onRespond).toHaveBeenCalledTimes(1);
|
||||
// The plugin decodes `response.value` as JSON: `{result, path?}`.
|
||||
const response = onRespond.mock.calls[0]?.[1];
|
||||
expect(typeof response).toBe("string");
|
||||
expect(JSON.parse(String(response))).toEqual({ result: "Accepted" });
|
||||
expect(response).toHaveProperty("value");
|
||||
expect(JSON.parse(String((response as { value: string }).value))).toEqual({ result: "Accepted" });
|
||||
});
|
||||
|
||||
it("carries the reviewed path on per-file diff decisions", async () => {
|
||||
const item = attention({
|
||||
method: "diff",
|
||||
title: "Review the edit",
|
||||
payload: {
|
||||
files: [{ path: "src/auth.ts", before: "a\n", after: "b\n" }],
|
||||
},
|
||||
});
|
||||
const onRespond = vi.fn();
|
||||
render(
|
||||
<AttentionDialog
|
||||
session={sessionFixture({ attention: [item] })}
|
||||
onRespond={onRespond}
|
||||
onRemoteResolved={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(await screen.findByText("src/auth.ts")).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Reject" }));
|
||||
const answer = onRespond.mock.calls[0]?.[1] as { value: string };
|
||||
expect(JSON.parse(answer.value)).toEqual({ result: "Rejected", path: "src/auth.ts" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,138 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
cancelResponse,
|
||||
chatCommands,
|
||||
confirmResponse,
|
||||
diffAnswer,
|
||||
diffResponse,
|
||||
selectResponse,
|
||||
} from "@/features/chat/commands";
|
||||
|
||||
/**
|
||||
* Payload shapes are owned by the plugin
|
||||
* (`pi2.nvim-web/lua/pi/web/commands.lua`); these assertions are the contract.
|
||||
*/
|
||||
describe("chat command payloads", () => {
|
||||
it("sends prompts with the plugin's modes and images", () => {
|
||||
const plain = chatCommands.sendPrompt("s1", "hi");
|
||||
expect(plain).toMatchObject({ method: "prompt.send", sessionId: "s1", params: { text: "hi" } });
|
||||
// A prompt while idle is a plain prompt: no follow-up/steer wrapper.
|
||||
expect(plain.params).not.toHaveProperty("mode");
|
||||
|
||||
expect(chatCommands.sendPrompt("s1", "hi", [], "follow_up").params).toMatchObject({
|
||||
text: "hi",
|
||||
mode: "follow_up",
|
||||
});
|
||||
expect(chatCommands.sendPrompt("s1", "hi", [], "steer").params).toMatchObject({
|
||||
text: "hi",
|
||||
mode: "steer",
|
||||
});
|
||||
expect(
|
||||
chatCommands.sendPrompt("s1", "hi", [{ mimeType: "image/png", data: "AAA" }], "follow_up").params,
|
||||
).toMatchObject({
|
||||
text: "hi",
|
||||
mode: "follow_up",
|
||||
images: [{ mimeType: "image/png", data: "AAA" }],
|
||||
});
|
||||
});
|
||||
|
||||
it("addresses queue entries by id and sets the steering mode", () => {
|
||||
expect(chatCommands.removeQueued("s1", "q1")).toMatchObject({
|
||||
method: "queue.remove",
|
||||
params: { id: "q1" },
|
||||
});
|
||||
expect(chatCommands.setQueueSteer("s1", true)).toMatchObject({
|
||||
method: "queue.setSteer",
|
||||
params: { mode: "all" },
|
||||
});
|
||||
expect(chatCommands.setQueueSteer("s1", false)).toMatchObject({
|
||||
method: "queue.setSteer",
|
||||
params: { mode: "one-at-a-time" },
|
||||
});
|
||||
});
|
||||
|
||||
it("wraps model and thinking changes in the plugin's fields", () => {
|
||||
expect(chatCommands.setModel("s1", { provider: "anthropic", id: "m" })).toMatchObject({
|
||||
method: "session.setModel",
|
||||
params: { model: { provider: "anthropic", id: "m" } },
|
||||
});
|
||||
expect(chatCommands.setThinking("s1", "high")).toMatchObject({
|
||||
method: "session.setThinking",
|
||||
params: { level: "high" },
|
||||
});
|
||||
});
|
||||
|
||||
it("builds attention answers in the `pi.attention.resolve` shape", () => {
|
||||
expect(selectResponse("allow-once")).toEqual({ value: "allow-once" });
|
||||
expect(confirmResponse(true)).toEqual({ confirmed: true });
|
||||
expect(confirmResponse(false)).toEqual({ confirmed: false });
|
||||
expect(cancelResponse()).toEqual({ cancelled: true });
|
||||
|
||||
expect(chatCommands.respondAttention("s1", "att-1", selectResponse("allow-once"))).toMatchObject({
|
||||
method: "attention.respond",
|
||||
params: { requestId: "att-1", response: { value: "allow-once" } },
|
||||
});
|
||||
expect(chatCommands.respondAttention("s1", "att-1", confirmResponse(true))).toMatchObject({
|
||||
params: { requestId: "att-1", response: { confirmed: true } },
|
||||
});
|
||||
|
||||
// Diff review: the JSON `{result, path?}` string rides inside `value`.
|
||||
expect(diffResponse("Accepted")).toBe(JSON.stringify({ result: "Accepted" }));
|
||||
expect(diffResponse("Rejected", "src/auth.ts")).toBe(
|
||||
JSON.stringify({ result: "Rejected", path: "src/auth.ts" }),
|
||||
);
|
||||
expect(diffAnswer("Accepted")).toEqual({ value: diffResponse("Accepted") });
|
||||
expect(chatCommands.respondAttention("s1", "att-2", diffAnswer("Accepted"))).toMatchObject({
|
||||
params: { requestId: "att-2", response: { value: diffResponse("Accepted") } },
|
||||
});
|
||||
});
|
||||
|
||||
it("dispatches one batch item with the snake_case contract", () => {
|
||||
expect(
|
||||
chatCommands.dispatchSubagent("s1", {
|
||||
task: "do it",
|
||||
name: "worker",
|
||||
model: { provider: "anthropic", id: "m" },
|
||||
thinking: "low",
|
||||
wait: true,
|
||||
cancelSiblingsOnFail: true,
|
||||
}),
|
||||
).toMatchObject({
|
||||
method: "subagent.dispatch",
|
||||
params: {
|
||||
items: [
|
||||
{
|
||||
task: "do it",
|
||||
name: "worker",
|
||||
model: { provider: "anthropic", id: "m" },
|
||||
thinking_level: "low",
|
||||
},
|
||||
],
|
||||
wait: true,
|
||||
cancel_siblings_on_fail: true,
|
||||
},
|
||||
});
|
||||
|
||||
expect(chatCommands.dispatchSubagent("s1", { task: "solo" }).params).toEqual({
|
||||
items: [{ task: "solo" }],
|
||||
wait: false,
|
||||
cancel_siblings_on_fail: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("reads sub-sessions and task output by id", () => {
|
||||
expect(chatCommands.readSubagent("s1", "researcher")).toMatchObject({
|
||||
method: "subagent.read",
|
||||
params: { target: "researcher" },
|
||||
});
|
||||
expect(chatCommands.stopTask("s1", "t1")).toMatchObject({
|
||||
method: "task.stop",
|
||||
params: { taskId: "t1" },
|
||||
});
|
||||
expect(chatCommands.taskOutput("s1", "t1")).toMatchObject({
|
||||
method: "task.output",
|
||||
params: { taskId: "t1" },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,6 @@ import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { Composer } from "@/features/chat/composer";
|
||||
import { chatCommands } from "@/features/chat/commands";
|
||||
import { setLanguage } from "@/lib/i18n";
|
||||
import { sessionFixture } from "./chat-fixtures";
|
||||
|
||||
@@ -41,28 +40,54 @@ function renderComposer(session = sessionFixture()) {
|
||||
}
|
||||
|
||||
describe("composer", () => {
|
||||
it("exposes the stable Playwright selectors", () => {
|
||||
renderComposer(sessionFixture({ status: "busy" }));
|
||||
expect(screen.getByTestId("composer-input")).toHaveClass("composer__ta");
|
||||
expect(screen.getByTestId("composer-send")).toHaveClass("composer__send");
|
||||
expect(screen.getByTestId("composer-abort")).toBeInTheDocument();
|
||||
expect(screen.getByTestId("composer-model")).toHaveAttribute("aria-label", "Model");
|
||||
expect(screen.getByTestId("composer-thinking")).toHaveAttribute("aria-label", "Thinking level");
|
||||
});
|
||||
|
||||
it("sends on Enter and keeps Shift+Enter for a newline", () => {
|
||||
const { onSend } = renderComposer();
|
||||
const textarea = screen.getByRole("textbox", { name: "Message input" });
|
||||
const { onSend } = renderComposer(sessionFixture({ status: "idle" }));
|
||||
const textarea = screen.getByTestId("composer-input");
|
||||
|
||||
fireEvent.change(textarea, { target: { value: "hello" } });
|
||||
fireEvent.keyDown(textarea, { key: "Enter", shiftKey: true });
|
||||
expect(onSend).not.toHaveBeenCalled();
|
||||
|
||||
fireEvent.keyDown(textarea, { key: "Enter" });
|
||||
expect(onSend).toHaveBeenCalledWith("hello", []);
|
||||
// An idle session sends a plain prompt (no `follow_up` / `steer` mode).
|
||||
expect(onSend).toHaveBeenCalledWith("hello", [], undefined);
|
||||
expect(textarea).toHaveValue("");
|
||||
});
|
||||
|
||||
it("turns the send button into an abort button while the session is busy", () => {
|
||||
const session = sessionFixture({ status: "busy" });
|
||||
const { onAbort, onSend } = renderComposer(session);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Abort" }));
|
||||
expect(onAbort).toHaveBeenCalledTimes(1);
|
||||
expect(onSend).not.toHaveBeenCalled();
|
||||
it("queues an Enter send as a follow-up while the session is busy", () => {
|
||||
const { onSend } = renderComposer(sessionFixture({ status: "busy" }));
|
||||
const textarea = screen.getByTestId("composer-input");
|
||||
fireEvent.change(textarea, { target: { value: "next step" } });
|
||||
fireEvent.keyDown(textarea, { key: "Enter" });
|
||||
expect(onSend).toHaveBeenCalledWith("next step", [], "follow_up");
|
||||
});
|
||||
|
||||
it("renders queue chips with steer toggle and remove", () => {
|
||||
it("keeps send for follow-ups and adds steer + abort while the session is busy", () => {
|
||||
const session = sessionFixture({ status: "busy" });
|
||||
const { onAbort, onSend } = renderComposer(session);
|
||||
|
||||
fireEvent.change(screen.getByTestId("composer-input"), { target: { value: "queue me" } });
|
||||
fireEvent.click(screen.getByTestId("composer-send"));
|
||||
expect(onSend).toHaveBeenLastCalledWith("queue me", [], "follow_up");
|
||||
|
||||
fireEvent.change(screen.getByTestId("composer-input"), { target: { value: "interrupt" } });
|
||||
fireEvent.click(screen.getByTestId("composer-steer"));
|
||||
expect(onSend).toHaveBeenLastCalledWith("interrupt", [], "steer");
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Abort" }));
|
||||
expect(onAbort).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("renders queue chips with the session-wide steer toggle and remove", () => {
|
||||
const session = sessionFixture({
|
||||
status: "idle",
|
||||
queue: [{ id: "q1", text: "later please", steer: false }],
|
||||
@@ -71,65 +96,17 @@ describe("composer", () => {
|
||||
|
||||
expect(screen.getByText("later please")).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("checkbox", { name: "Steer" }));
|
||||
expect(onSetSteer).toHaveBeenCalledWith("q1", true);
|
||||
// Steering is a session-wide mode, so the toggle carries no queue id.
|
||||
expect(onSetSteer).toHaveBeenCalledWith(true);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Remove queued message" }));
|
||||
expect(onRemoveQueue).toHaveBeenCalledWith("q1");
|
||||
});
|
||||
|
||||
it("builds the documented command payloads", () => {
|
||||
expect(chatCommands.sendPrompt("s1", "hi")).toMatchObject({
|
||||
method: "prompt.send",
|
||||
sessionId: "s1",
|
||||
params: { text: "hi", mode: "queue" },
|
||||
});
|
||||
expect(chatCommands.sendPrompt("s1", "hi", [{ mimeType: "image/png", data: "AAA" }])).toMatchObject({
|
||||
params: { text: "hi", mode: "queue", images: [{ mimeType: "image/png", data: "AAA" }] },
|
||||
});
|
||||
expect(chatCommands.abort("s1")).toMatchObject({ method: "prompt.abort", sessionId: "s1" });
|
||||
expect(chatCommands.removeQueued("s1", "q1")).toMatchObject({
|
||||
method: "queue.remove",
|
||||
params: { queueId: "q1" },
|
||||
});
|
||||
expect(chatCommands.setQueueSteer("s1", "q1", true)).toMatchObject({
|
||||
method: "queue.setSteer",
|
||||
params: { queueId: "q1", steer: true },
|
||||
});
|
||||
expect(chatCommands.setModel("s1", { provider: "anthropic", id: "m" })).toMatchObject({
|
||||
method: "session.setModel",
|
||||
params: { provider: "anthropic", id: "m" },
|
||||
});
|
||||
expect(chatCommands.setThinking("s1", "high")).toMatchObject({
|
||||
method: "session.setThinking",
|
||||
params: { level: "high" },
|
||||
});
|
||||
expect(chatCommands.respondAttention("s1", "att-1", "allow-once")).toMatchObject({
|
||||
method: "attention.respond",
|
||||
params: { requestId: "att-1", response: "allow-once" },
|
||||
});
|
||||
expect(
|
||||
chatCommands.dispatchSubagent("s1", {
|
||||
task: "do it",
|
||||
name: "worker",
|
||||
model: { provider: "anthropic", id: "m" },
|
||||
thinking: "low",
|
||||
wait: true,
|
||||
cancelSiblingsOnFail: true,
|
||||
}),
|
||||
).toMatchObject({
|
||||
method: "subagent.dispatch",
|
||||
params: {
|
||||
task: "do it",
|
||||
name: "worker",
|
||||
model: { provider: "anthropic", id: "m" },
|
||||
thinking: "low",
|
||||
wait: true,
|
||||
cancelSiblingsOnFail: true,
|
||||
},
|
||||
});
|
||||
expect(chatCommands.stopTask("s1", "t1")).toMatchObject({
|
||||
method: "task.stop",
|
||||
params: { taskId: "t1" },
|
||||
});
|
||||
it("drops the mock-era demo copy from the attachment dialog", () => {
|
||||
renderComposer();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Add attachment" }));
|
||||
expect(screen.queryByText(/Demo only/i)).not.toBeInTheDocument();
|
||||
expect(screen.queryByText(/prototype demo only/i)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -121,6 +121,101 @@ describe("history entry projection", () => {
|
||||
expect(new Set(combined.map((entry) => entry.id)).size).toBe(combined.length);
|
||||
});
|
||||
|
||||
it("dedupes a reload where the snapshot used synthetic ids and the pages raw ids", () => {
|
||||
const history = projectEntries([
|
||||
{ type: "message", id: "u1", message: { role: "user", content: "hello", timestamp: TS } },
|
||||
{
|
||||
type: "message",
|
||||
id: "a1",
|
||||
message: {
|
||||
role: "assistant",
|
||||
timestamp: TS + 1,
|
||||
content: [{ type: "text", text: "on it" }],
|
||||
},
|
||||
},
|
||||
{ type: "message", id: "u2", message: { role: "user", content: "and again", timestamp: TS + 2 } },
|
||||
]);
|
||||
// The live snapshot replays the first two messages under `m<N>` ids.
|
||||
const live = [
|
||||
entryFixture({ id: "m1", role: "user", ts: TS, blocks: [{ type: "text", text: "hello" }] }),
|
||||
entryFixture({ id: "m2", role: "assistant", ts: TS + 1, blocks: [{ type: "text", text: "on it" }] }),
|
||||
];
|
||||
|
||||
const merged = mergeEntries(history, live);
|
||||
// One copy each, still in transcript order, with the live entry winning.
|
||||
expect(merged.map((entry) => entry.id)).toEqual(["m1", "m2", "u2"]);
|
||||
expect(merged.filter((entry) => entry.role === "user")).toHaveLength(2);
|
||||
expect(merged[0]?.ts).toBe(TS);
|
||||
});
|
||||
|
||||
it("keeps live-only entries and drops raw duplicates when prepending a page", () => {
|
||||
const live = [
|
||||
entryFixture({ id: "m1", role: "user", ts: TS, blocks: [{ type: "text", text: "hello" }] }),
|
||||
entryFixture({ id: "m2", role: "assistant", ts: TS + 1, blocks: [{ type: "text", text: "on it" }] }),
|
||||
];
|
||||
const older = projectEntries([
|
||||
{ type: "message", id: "u0", message: { role: "user", content: "first", timestamp: TS - 10 } },
|
||||
{ type: "message", id: "u1", message: { role: "user", content: "hello", timestamp: TS } },
|
||||
]);
|
||||
|
||||
const combined = prependUnique(live, older);
|
||||
expect(combined.map((entry) => entry.id)).toEqual(["u0", "m1", "m2"]);
|
||||
});
|
||||
|
||||
it("renders one assistant entry when a snapshot tail and a raw history page carry the same reply", () => {
|
||||
// The snapshot tail carries plugin-side synthetic ids and the plugin
|
||||
// event clock; the page carries pi's raw ids and message clock, so the
|
||||
// same reply lands in a different second bucket than the live entry.
|
||||
const historyTs = TS + 1;
|
||||
const liveTs = historyTs + 1_400;
|
||||
const history = projectEntries([
|
||||
{ type: "message", id: "u1", message: { role: "user", content: "ping", timestamp: TS } },
|
||||
{
|
||||
type: "message",
|
||||
id: "a1",
|
||||
message: { role: "assistant", timestamp: historyTs, content: [{ type: "text", text: "PONG" }] },
|
||||
},
|
||||
]);
|
||||
const live = [
|
||||
entryFixture({ id: "m1", role: "user", ts: TS, blocks: [{ type: "text", text: "ping" }] }),
|
||||
entryFixture({ id: "m2", role: "assistant", ts: liveTs, blocks: [{ type: "text", text: "PONG" }] }),
|
||||
];
|
||||
|
||||
const merged = mergeEntries(history, live);
|
||||
expect(merged.map((entry) => entry.id)).toEqual(["m1", "m2"]);
|
||||
expect(merged.filter((entry) => entry.role === "assistant")).toHaveLength(1);
|
||||
|
||||
// A reconnect replays the snapshot against the same page: still one each.
|
||||
const replayed = mergeEntries(history, live.map((entry) => ({ ...entry })));
|
||||
expect(replayed.map((entry) => entry.id)).toEqual(["m1", "m2"]);
|
||||
expect(replayed.filter((entry) => entry.role === "assistant")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("keeps genuinely repeated replies instead of collapsing them", () => {
|
||||
const history = projectEntries([
|
||||
{ type: "message", id: "u1", message: { role: "user", content: "hi", timestamp: TS } },
|
||||
{
|
||||
type: "message",
|
||||
id: "a1",
|
||||
message: { role: "assistant", timestamp: TS + 1, content: [{ type: "text", text: "ok" }] },
|
||||
},
|
||||
{ type: "message", id: "u2", message: { role: "user", content: "hi", timestamp: TS + 2 } },
|
||||
{
|
||||
type: "message",
|
||||
id: "a2",
|
||||
message: { role: "assistant", timestamp: TS + 3, content: [{ type: "text", text: "ok" }] },
|
||||
},
|
||||
]);
|
||||
const live = [
|
||||
entryFixture({ id: "m3", role: "user", ts: TS + 2, blocks: [{ type: "text", text: "hi" }] }),
|
||||
entryFixture({ id: "m4", role: "assistant", ts: TS + 3, blocks: [{ type: "text", text: "ok" }] }),
|
||||
];
|
||||
|
||||
const merged = mergeEntries(history, live);
|
||||
expect(merged.map((entry) => entry.id)).toEqual(["u1", "a1", "m3", "m4"]);
|
||||
expect(merged).toHaveLength(4);
|
||||
});
|
||||
|
||||
it("normalizes the entries page cursor", () => {
|
||||
expect(
|
||||
normalizeEntriesPage({
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { sessionMigration } from "@/features/chat/data";
|
||||
import { chatSessionPath, migrateSessionId, onSessionMigration, replaceChatUrl } from "@/features/chat/migration";
|
||||
import { useChatStore } from "@/features/chat/store";
|
||||
import { useSessionsStore } from "@/stores/sessions";
|
||||
|
||||
import { entryFixture, sessionFixture } from "./chat-fixtures";
|
||||
|
||||
beforeEach(() => {
|
||||
useSessionsStore.getState().reset();
|
||||
useChatStore.setState({ history: {}, sending: null, preview: null });
|
||||
window.history.replaceState(null, "", "/chat");
|
||||
});
|
||||
|
||||
describe("session id migration (`tmp-N` → real id)", () => {
|
||||
it("re-keys the session row, history, in-flight prompt and the URL", () => {
|
||||
useSessionsStore.getState().setSessions("w1", [sessionFixture({ sessionId: "tmp-1", name: "New session" })]);
|
||||
useChatStore.getState().receiveInitial("tmp-1", [entryFixture({ id: "u1", role: "user" })], {
|
||||
before: "u1",
|
||||
hasMore: true,
|
||||
});
|
||||
useChatStore.getState().setSending({ sessionId: "tmp-1", text: "hello" });
|
||||
useChatStore.getState().setPreview({ sessionId: "tmp-1", subagentId: "sa1" });
|
||||
window.history.replaceState(null, "", "/chat/tmp-1?workspace=w1");
|
||||
|
||||
const seen: string[] = [];
|
||||
const off = onSessionMigration((migration) => seen.push(`${migration.from}->${migration.to}`));
|
||||
const migration = migrateSessionId("tmp-1", "01a1-real", "w1");
|
||||
off();
|
||||
|
||||
expect(seen).toEqual(["tmp-1->01a1-real"]);
|
||||
expect(migration?.path).toBe("/chat/01a1-real?workspace=w1");
|
||||
|
||||
// The tree row, the history page and the optimistic chip all followed.
|
||||
expect(useSessionsStore.getState().listFor("w1").map((session) => session.sessionId)).toEqual([
|
||||
"01a1-real",
|
||||
]);
|
||||
expect(useSessionsStore.getState().getSession("tmp-1")).toBeUndefined();
|
||||
expect(useChatStore.getState().history["tmp-1"]).toBeUndefined();
|
||||
expect(useChatStore.getState().history["01a1-real"]?.entries).toHaveLength(1);
|
||||
expect(useChatStore.getState().history["01a1-real"]?.cursor).toEqual({ before: "u1", hasMore: true });
|
||||
expect(useChatStore.getState().sending).toEqual({ sessionId: "01a1-real", text: "hello" });
|
||||
expect(useChatStore.getState().preview).toEqual({ sessionId: "01a1-real", subagentId: "sa1" });
|
||||
|
||||
expect(replaceChatUrl("tmp-1", "01a1-real", "w1")).toBe(true);
|
||||
expect(window.location.pathname + window.location.search).toBe("/chat/01a1-real?workspace=w1");
|
||||
});
|
||||
|
||||
it("leaves the URL alone when the route addressed another session", () => {
|
||||
window.history.replaceState(null, "", "/chat/other?workspace=w1");
|
||||
expect(replaceChatUrl("tmp-1", "01a1-real", "w1")).toBe(false);
|
||||
expect(window.location.pathname).toBe("/chat/other");
|
||||
expect(chatSessionPath("01a1-real")).toBe("/chat/01a1-real");
|
||||
});
|
||||
|
||||
it("is a no-op for the same id and never invents a history slice", () => {
|
||||
expect(migrateSessionId("s1", "s1", "w1")).toBeNull();
|
||||
expect(useChatStore.getState().history["s1"]).toBeUndefined();
|
||||
});
|
||||
|
||||
it("reads the migration announcement off the old-id `pi2:session` event", () => {
|
||||
expect(
|
||||
sessionMigration("tmp-1", {
|
||||
type: "pi2:session",
|
||||
session: { sessionId: "01a1-real", previousSessionId: "tmp-1" },
|
||||
}),
|
||||
).toEqual({ from: "tmp-1", to: "01a1-real" });
|
||||
|
||||
// A plain patch on the same id is not a migration.
|
||||
expect(sessionMigration("s1", { type: "pi2:session", session: { sessionId: "s1" } })).toBeUndefined();
|
||||
// A patch about a different session must not steal this subscription.
|
||||
expect(
|
||||
sessionMigration("tmp-1", {
|
||||
type: "pi2:session",
|
||||
session: { sessionId: "01a1-real", previousSessionId: "tmp-9" },
|
||||
}),
|
||||
).toBeUndefined();
|
||||
// Only `pi2:session` announces migrations.
|
||||
expect(
|
||||
sessionMigration("tmp-1", { type: "pi2:todo", session: { sessionId: "01a1-real" } }),
|
||||
).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,134 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { SubagentModal, TaskOutputModal } from "@/features/chat/modals";
|
||||
import { setLanguage } from "@/lib/i18n";
|
||||
|
||||
import { sessionFixture, subagentFixture, taskFixture, taskOutputFixture } from "./chat-fixtures";
|
||||
import { mockApi } from "./helpers/api-mock";
|
||||
|
||||
beforeAll(async () => {
|
||||
await setLanguage("en");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
/** Answer `/api/v1/cmd` from a per-method table (the real plugin ack payloads). */
|
||||
function mockCommands(replies: Record<string, { status?: number; body: unknown }>) {
|
||||
return mockApi([
|
||||
{
|
||||
method: "POST",
|
||||
path: "/api/v1/cmd",
|
||||
handler: ({ body }) => {
|
||||
const method = (body as { method?: string } | undefined)?.method ?? "";
|
||||
const reply = replies[method];
|
||||
if (!reply) return { status: 202, body: { accepted: true } };
|
||||
return reply;
|
||||
},
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
describe("task output modal", () => {
|
||||
it("renders the real task.output payload instead of a fake pid", async () => {
|
||||
const fetchMock = mockCommands({ "task.output": { status: 202, body: taskOutputFixture() } });
|
||||
render(
|
||||
<TaskOutputModal
|
||||
open
|
||||
session={sessionFixture()}
|
||||
task={taskFixture()}
|
||||
onClose={vi.fn()}
|
||||
onStop={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(await screen.findByText(/42 passed/)).toBeInTheDocument();
|
||||
// The mock-era pseudo pid is gone.
|
||||
expect(screen.queryByText("pid")).not.toBeInTheDocument();
|
||||
expect(screen.getAllByText("/tmp/pi2-task-t1.log").length).toBeGreaterThan(0);
|
||||
expect(screen.getByText("exit code")).toBeInTheDocument();
|
||||
expect(screen.getByText("0")).toBeInTheDocument();
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).toMatchObject({
|
||||
method: "task.output",
|
||||
params: { taskId: "t1" },
|
||||
});
|
||||
});
|
||||
|
||||
it("shows a real error state when the plugin does not support the command", async () => {
|
||||
mockCommands({
|
||||
"task.output": {
|
||||
status: 501,
|
||||
body: { error: { code: "E_UNSUPPORTED", message: "unknown method: task.output", retryable: false } },
|
||||
},
|
||||
});
|
||||
render(
|
||||
<TaskOutputModal
|
||||
open
|
||||
session={sessionFixture()}
|
||||
task={taskFixture()}
|
||||
onClose={vi.fn()}
|
||||
onStop={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(await screen.findByText(/Unsupported operation/)).toBeInTheDocument();
|
||||
expect(screen.queryByText("(no output)")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe("subagent preview modal", () => {
|
||||
it("renders the raw pi entries from subagent.read (sessionFile + lines)", async () => {
|
||||
mockCommands({
|
||||
"subagent.read": {
|
||||
status: 202,
|
||||
body: {
|
||||
sessionFile: "/tmp/pi2-subsessions/researcher.jsonl",
|
||||
lines: ["[1] user: fix the auth flow", "[2] assistant: looking at it now", "[3] tool result: ok"],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
render(
|
||||
<SubagentModal
|
||||
open
|
||||
session={sessionFixture()}
|
||||
subagent={subagentFixture()}
|
||||
onClose={vi.fn()}
|
||||
onBack={vi.fn()}
|
||||
onSteer={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(await screen.findByText("fix the auth flow")).toBeInTheDocument();
|
||||
expect(screen.getByText("looking at it now")).toBeInTheDocument();
|
||||
expect(screen.getByText("/tmp/pi2-subsessions/researcher.jsonl")).toBeInTheDocument();
|
||||
expect(screen.getByText("fix the auth flow").closest("article")).toHaveAttribute("data-role", "user");
|
||||
expect(screen.getByText("looking at it now").closest("article")).toHaveAttribute("data-role", "assistant");
|
||||
// No synthetic "preview" copy.
|
||||
expect(screen.queryByText(/Got it\. I'll run with/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows an error state when the sub-session cannot be read", async () => {
|
||||
mockCommands({
|
||||
"subagent.read": {
|
||||
status: 404,
|
||||
body: { error: { code: "E_NOT_FOUND", message: "unknown sub-agent session file", retryable: false } },
|
||||
},
|
||||
});
|
||||
render(
|
||||
<SubagentModal
|
||||
open
|
||||
session={sessionFixture()}
|
||||
subagent={subagentFixture()}
|
||||
onClose={vi.fn()}
|
||||
onBack={vi.fn()}
|
||||
onSteer={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("Not found");
|
||||
});
|
||||
});
|
||||
@@ -5,7 +5,7 @@ import process from "node:process";
|
||||
import type { SessionEvent } from "@protocol/types";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { applySessionEvent, emptySessionState } from "@/features/chat/session-state";
|
||||
import { applySessionEvent, emptySessionState, normalizeSnapshotState } from "@/features/chat/session-state";
|
||||
|
||||
function append(state: ReturnType<typeof emptySessionState>, event: SessionEvent) {
|
||||
return applySessionEvent(state, event);
|
||||
@@ -55,6 +55,59 @@ describe("canonical reducer integration", () => {
|
||||
expect(state.usage).toMatchObject({ input: 10, output: 2, cost: 0.01 });
|
||||
});
|
||||
|
||||
it("renders exactly one assistant entry with the exact streamed text", () => {
|
||||
let state = emptySessionState({ sessionId: "s1", workspaceId: "w1" });
|
||||
state = append(state, { type: "agent_start", ts: 1 });
|
||||
state = append(state, { type: "message_start", ts: 2, message: { role: "assistant", content: [] } });
|
||||
for (const delta of ["P", "O", "N", "G"]) {
|
||||
state = append(state, {
|
||||
type: "message_update",
|
||||
ts: 3,
|
||||
assistantMessageEvent: { type: "text_delta", contentIndex: 0, delta },
|
||||
});
|
||||
}
|
||||
state = append(state, {
|
||||
type: "message_end",
|
||||
ts: 4,
|
||||
message: { role: "assistant", content: [{ type: "text", text: "PONG" }] },
|
||||
});
|
||||
|
||||
expect(state.entries).toHaveLength(1);
|
||||
expect(state.entries[0]?.blocks).toEqual([{ type: "text", text: "PONG" }]);
|
||||
expect(state.entries[0]?.done).toBe(true);
|
||||
|
||||
// The bridge coalesces deltas and stamps their seq when the frame is
|
||||
// written, so the tail of the message can arrive after `message_end`.
|
||||
// Replaying it must not append the tail a second time (`PONGONG`).
|
||||
state = append(state, {
|
||||
type: "message_update",
|
||||
ts: 5,
|
||||
assistantMessageEvent: { type: "text_delta", contentIndex: 0, delta: "ONG" },
|
||||
});
|
||||
expect(state.entries).toHaveLength(1);
|
||||
expect(state.entries[0]?.blocks).toEqual([{ type: "text", text: "PONG" }]);
|
||||
});
|
||||
|
||||
it("ignores stale deltas after a snapshot took over a settled session", () => {
|
||||
const ts = Date.now();
|
||||
const snapshot = normalizeSnapshotState("s1", "w1", {
|
||||
state: {
|
||||
status: "idle",
|
||||
entries: [
|
||||
{ id: "m1", role: "user", ts, done: true, blocks: [{ type: "text", text: "ping" }] },
|
||||
{ id: "m2", role: "assistant", ts, done: true, blocks: [{ type: "text", text: "PONG" }] },
|
||||
],
|
||||
},
|
||||
});
|
||||
const next = append(snapshot, {
|
||||
type: "message_update",
|
||||
ts: ts + 10,
|
||||
assistantMessageEvent: { type: "text_delta", contentIndex: 0, delta: "ONG" },
|
||||
});
|
||||
expect(next.entries.filter((entry) => entry.role === "assistant")).toHaveLength(1);
|
||||
expect(next.entries[1]?.blocks).toEqual([{ type: "text", text: "PONG" }]);
|
||||
});
|
||||
|
||||
it("applies entry_appended for user messages and folds tool results into the tool block", () => {
|
||||
const ts = Date.now();
|
||||
let state = emptySessionState({ sessionId: "s1", workspaceId: "w1" });
|
||||
@@ -121,6 +174,32 @@ describe("canonical reducer integration", () => {
|
||||
expect(state.entries.filter((entry) => entry.role === "user")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("tracks an attention request and closes it when the plugin resolves it", () => {
|
||||
let state = emptySessionState({ sessionId: "s1", workspaceId: "w1" });
|
||||
state = append(state, {
|
||||
type: "pi2:attention_request",
|
||||
ts: 10,
|
||||
requestId: "att-1",
|
||||
method: "select",
|
||||
title: "Run this command?",
|
||||
options: [{ id: "allow-once", label: "Allow once" }],
|
||||
timeoutSec: 30,
|
||||
});
|
||||
expect(state.attention).toHaveLength(1);
|
||||
expect(state.attention[0]).toMatchObject({
|
||||
requestId: "att-1",
|
||||
method: "select",
|
||||
title: "Run this command?",
|
||||
options: [{ id: "allow-once", label: "Allow once" }],
|
||||
timeoutSec: 30,
|
||||
});
|
||||
expect(state.flags.attention).toBe(true);
|
||||
|
||||
state = append(state, { type: "pi2:attention_resolved", ts: 11, requestId: "att-1" });
|
||||
expect(state.attention).toHaveLength(0);
|
||||
expect(state.flags.attention).toBe(false);
|
||||
});
|
||||
|
||||
it("replays the pi2d basic-turn fixture through the shared reducer", () => {
|
||||
const fixture = join(process.cwd(), "..", "fixtures", "basic-turn", "events.jsonl");
|
||||
if (!existsSync(fixture)) {
|
||||
|
||||
@@ -47,6 +47,37 @@ describe("chat message stream", () => {
|
||||
expect(screen.getByText("agent aborted").closest(".msg__error")).not.toBeNull();
|
||||
});
|
||||
|
||||
it("exposes data-entry-id / data-role on every message", () => {
|
||||
renderStream();
|
||||
const user = screen.getByText("Fix the auth bug").closest("article");
|
||||
expect(user).toHaveAttribute("data-entry-id", "u1");
|
||||
expect(user).toHaveAttribute("data-role", "user");
|
||||
|
||||
const assistant = screen.getByText("Looking at the auth path now.").closest("article");
|
||||
expect(assistant).toHaveAttribute("data-entry-id", "a1");
|
||||
expect(assistant).toHaveAttribute("data-role", "assistant");
|
||||
});
|
||||
|
||||
it("exposes the load-older selector only while older pages exist", () => {
|
||||
const session = fullStreamSession();
|
||||
const props = {
|
||||
session,
|
||||
entries: session.entries,
|
||||
loadingOlder: false,
|
||||
error: null,
|
||||
onLoadOlder: vi.fn(),
|
||||
onRetry: vi.fn(),
|
||||
onOpenSubagent: vi.fn(),
|
||||
};
|
||||
const { rerender } = render(<MessageStream {...props} hasMore />);
|
||||
const button = screen.getByTestId("load-older");
|
||||
fireEvent.click(button);
|
||||
expect(props.onLoadOlder).toHaveBeenCalledTimes(1);
|
||||
|
||||
rerender(<MessageStream {...props} hasMore={false} />);
|
||||
expect(screen.queryByTestId("load-older")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("expands a tool card to show output and an edit diff", () => {
|
||||
renderStream();
|
||||
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { PiWsClient, type WebSocketLike, type WsFrame } from "@/lib/ws";
|
||||
|
||||
class FakeSocket implements WebSocketLike {
|
||||
readyState = 0;
|
||||
sent: WsFrame[] = [];
|
||||
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.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) });
|
||||
}
|
||||
|
||||
serverClose(code = 1006): void {
|
||||
this.readyState = 3;
|
||||
this.onclose?.({ code });
|
||||
}
|
||||
|
||||
frames(type: string): WsFrame[] {
|
||||
return this.sent.filter((frame) => frame.type === type);
|
||||
}
|
||||
}
|
||||
|
||||
function createClient() {
|
||||
const sockets: FakeSocket[] = [];
|
||||
const client = new PiWsClient({
|
||||
url: "ws://127.0.0.1:7676/api/v1/ws",
|
||||
token: "pkt_test",
|
||||
heartbeatMs: 0,
|
||||
socketFactory: () => {
|
||||
const socket = new FakeSocket();
|
||||
sockets.push(socket);
|
||||
return socket;
|
||||
},
|
||||
});
|
||||
return { client, sockets };
|
||||
}
|
||||
|
||||
/** Open + authenticate one socket, returning it. */
|
||||
function handshake(socket: FakeSocket, client: PiWsClient): void {
|
||||
socket.open();
|
||||
socket.receive({ v: 1, type: "hello_ack" });
|
||||
expect(client.getState()).toBe("open");
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe("WS resume", () => {
|
||||
it("resumes with a per-session `since` cursor instead of `sinceSeq`", () => {
|
||||
vi.useFakeTimers();
|
||||
const { client, sockets } = createClient();
|
||||
client.connect();
|
||||
handshake(sockets[0]!, client);
|
||||
|
||||
client.subscribe("s1");
|
||||
// No cursor yet: a plain subscribe.
|
||||
expect(sockets[0]!.frames("subscribe")).toEqual([
|
||||
{ v: 1, type: "subscribe", payload: { sessionIds: ["s1"] } },
|
||||
]);
|
||||
|
||||
sockets[0]!.receive({ type: "snapshot", sessionId: "s1", epoch: "e1", seq: 10, payload: {} });
|
||||
sockets[0]!.receive({ type: "event", sessionId: "s1", epoch: "e1", seq: 11, payload: {} });
|
||||
|
||||
sockets[0]!.serverClose();
|
||||
vi.advanceTimersByTime(200);
|
||||
const resumed = sockets[1]!;
|
||||
handshake(resumed, client);
|
||||
|
||||
expect(resumed.frames("subscribe")).toEqual([
|
||||
{
|
||||
v: 1,
|
||||
type: "subscribe",
|
||||
payload: { sessionIds: ["s1"], since: { sessionId: "s1", epoch: "e1", seq: 11 } },
|
||||
},
|
||||
]);
|
||||
// No legacy key on the wire.
|
||||
expect(resumed.frames("subscribe")[0]?.payload).not.toHaveProperty("sinceSeq");
|
||||
});
|
||||
|
||||
it("drops the cached cursor on `resync_required` so the next subscribe refetches", () => {
|
||||
vi.useFakeTimers();
|
||||
const { client, sockets } = createClient();
|
||||
client.connect();
|
||||
handshake(sockets[0]!, client);
|
||||
client.subscribe("s1");
|
||||
sockets[0]!.receive({ type: "snapshot", sessionId: "s1", epoch: "e1", seq: 10, payload: {} });
|
||||
expect(client.getLastSeq("s1")).toBe(10);
|
||||
expect(client.getEpoch("s1")).toBe("e1");
|
||||
|
||||
sockets[0]!.receive({ type: "resync_required", sessionId: "s1", epoch: "e1", seq: 10, payload: {} });
|
||||
expect(client.getLastSeq("s1")).toBeUndefined();
|
||||
expect(client.getEpoch("s1")).toBeUndefined();
|
||||
|
||||
sockets[0]!.serverClose();
|
||||
vi.advanceTimersByTime(200);
|
||||
handshake(sockets[1]!, client);
|
||||
expect(sockets[1]!.frames("subscribe")).toEqual([
|
||||
{ v: 1, type: "subscribe", payload: { sessionIds: ["s1"] } },
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps the exponential backoff while resuming several sessions", () => {
|
||||
vi.useFakeTimers();
|
||||
const { client, sockets } = createClient();
|
||||
client.connect();
|
||||
handshake(sockets[0]!, client);
|
||||
|
||||
client.subscribe(["s1", "s2"]);
|
||||
sockets[0]!.receive({ type: "snapshot", sessionId: "s1", epoch: "e1", seq: 4, payload: {} });
|
||||
sockets[0]!.serverClose();
|
||||
|
||||
// First retry waits the initial 200ms; the client keeps trying.
|
||||
vi.advanceTimersByTime(199);
|
||||
expect(sockets).toHaveLength(1);
|
||||
vi.advanceTimersByTime(1);
|
||||
expect(sockets).toHaveLength(2);
|
||||
|
||||
handshake(sockets[1]!, client);
|
||||
// One resumable frame per cursor, one batch for the rest.
|
||||
expect(sockets[1]!.frames("subscribe")).toEqual([
|
||||
{
|
||||
v: 1,
|
||||
type: "subscribe",
|
||||
payload: { sessionIds: ["s1"], since: { sessionId: "s1", epoch: "e1", seq: 4 } },
|
||||
},
|
||||
{ v: 1, type: "subscribe", payload: { sessionIds: ["s2"] } },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,15 @@
|
||||
import { fireEvent, render, screen, within } from "@testing-library/react";
|
||||
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import type { ComponentProps } from "react";
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { setLanguage } from "@/lib/i18n";
|
||||
import { SessionTree } from "@/features/chat/session-tree";
|
||||
import { useChatStore } from "@/features/chat/store";
|
||||
import { ChatPage } from "@/pages/chat";
|
||||
import { useSessionsStore } from "@/stores/sessions";
|
||||
import { sessionFixture, subagentFixture } from "./chat-fixtures";
|
||||
import { mockApi } from "./helpers/api-mock";
|
||||
import { renderPage } from "./helpers/render-page";
|
||||
|
||||
beforeAll(async () => {
|
||||
await setLanguage("en");
|
||||
@@ -80,3 +85,198 @@ describe("session tree", () => {
|
||||
expect(onToggleAll).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Deep links: an unknown session must never borrow another session. */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
const BOGUS = "ffffffffffffffffffffffff";
|
||||
const TS = 1_733_234_400_000;
|
||||
|
||||
/** The chat page opens a socket on mount; a silent socket keeps it inert. */
|
||||
function silentSocket(): void {
|
||||
class SilentSocket {
|
||||
readyState = 0;
|
||||
onopen: ((event: unknown) => void) | null = null;
|
||||
onmessage: ((event: { data: unknown }) => void) | null = null;
|
||||
onclose: ((event: { code?: number }) => void) | null = null;
|
||||
onerror: ((event: unknown) => void) | null = null;
|
||||
send(): void {}
|
||||
close(): void {
|
||||
this.readyState = 3;
|
||||
}
|
||||
}
|
||||
vi.stubGlobal("WebSocket", SilentSocket);
|
||||
}
|
||||
|
||||
function workspaceBody() {
|
||||
return [
|
||||
{
|
||||
workspaceId: "W1",
|
||||
cwd: "/work/w1",
|
||||
name: "W1",
|
||||
trusted: true,
|
||||
exists: true,
|
||||
sessionCount: 2,
|
||||
liveCount: 0,
|
||||
lastActiveAt: 0,
|
||||
instance: null,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function sessionsBody() {
|
||||
return {
|
||||
sessions: [
|
||||
{ sessionId: "s1", name: "Alpha", workspaceId: "W1", cwd: "/work/w1", status: "idle" },
|
||||
{ sessionId: "s2", name: "Beta", workspaceId: "W1", cwd: "/work/w1", status: "busy" },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function entriesBody(text: string) {
|
||||
return {
|
||||
entries: [
|
||||
{
|
||||
type: "message",
|
||||
id: "u1",
|
||||
timestamp: new Date(TS).toISOString(),
|
||||
message: { role: "user", content: text, timestamp: TS },
|
||||
},
|
||||
],
|
||||
cursor: { hasMore: false },
|
||||
};
|
||||
}
|
||||
|
||||
function chatRoutes() {
|
||||
return [
|
||||
{ path: "/chat/$sessionId", component: ChatPage },
|
||||
{ path: "/chat", component: ChatPage },
|
||||
{ path: "/workspaces", component: () => <div>Workspaces destination</div> },
|
||||
];
|
||||
}
|
||||
|
||||
function streamPane(): HTMLElement {
|
||||
const pane = document.querySelector(".stream-pane");
|
||||
if (!pane) throw new Error("the chat layout did not render a stream pane");
|
||||
return pane as HTMLElement;
|
||||
}
|
||||
|
||||
function requestedUrls(fetchMock: ReturnType<typeof mockApi>): string[] {
|
||||
return fetchMock.mock.calls.map(([input]) => String(input));
|
||||
}
|
||||
|
||||
describe("chat session deep link", () => {
|
||||
beforeEach(() => {
|
||||
useSessionsStore.getState().reset();
|
||||
useChatStore.setState({ history: {}, sending: null, preview: null });
|
||||
silentSocket();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("shows an error + retry for an unknown session instead of another session", async () => {
|
||||
const fetchMock = mockApi([
|
||||
{ path: "/api/v1/workspaces", handler: () => ({ body: workspaceBody() }) },
|
||||
{ path: "/api/v1/workspaces/W1/sessions", handler: () => ({ body: sessionsBody() }) },
|
||||
{ path: "/api/v1/models", handler: () => ({ body: [] }) },
|
||||
{ path: /^\/api\/v1\/sessions\/s1\/entries/, handler: () => ({ body: entriesBody("Alpha first message") }) },
|
||||
]);
|
||||
|
||||
await renderPage(chatRoutes(), `/chat/${BOGUS}?workspace=W1`);
|
||||
|
||||
const error = await screen.findByTestId("session-not-found");
|
||||
expect(within(error).getByText("Session not found")).toBeInTheDocument();
|
||||
expect(within(error).getByRole("button", { name: /retry/i })).toBeInTheDocument();
|
||||
// A way back to the workspace list, so the dead end is not a dead end.
|
||||
expect(within(error).getByRole("link", { name: /back to workspaces/i })).toHaveAttribute(
|
||||
"href",
|
||||
"/workspaces",
|
||||
);
|
||||
|
||||
// The main area never borrows the first session of the workspace.
|
||||
expect(within(streamPane()).queryByText("Alpha")).toBeNull();
|
||||
expect(within(streamPane()).queryByText("Alpha first message")).toBeNull();
|
||||
expect(streamPane().querySelector(".stream-name")?.textContent ?? "").not.toContain("Alpha");
|
||||
// ... and no composer for a session that does not exist.
|
||||
expect(within(streamPane()).queryByLabelText("Message input")).toBeNull();
|
||||
// No tree row claims to be the current session either.
|
||||
expect(document.querySelector('[data-session-id][aria-current="true"]')).toBeNull();
|
||||
// The unknown id is never used to fetch entries.
|
||||
expect(requestedUrls(fetchMock).some((url) => url.includes(BOGUS))).toBe(false);
|
||||
|
||||
// Retry refetches the session list.
|
||||
const listCalls = () =>
|
||||
requestedUrls(fetchMock).filter((url) => url.includes("/api/v1/workspaces/W1/sessions")).length;
|
||||
const before = listCalls();
|
||||
fireEvent.click(within(error).getByTestId("session-not-found-retry"));
|
||||
await waitFor(() => expect(listCalls()).toBeGreaterThan(before));
|
||||
});
|
||||
|
||||
it("selects the deep-linked session and renders its own history", async () => {
|
||||
const fetchMock = mockApi([
|
||||
{ path: "/api/v1/workspaces", handler: () => ({ body: workspaceBody() }) },
|
||||
{ path: "/api/v1/workspaces/W1/sessions", handler: () => ({ body: sessionsBody() }) },
|
||||
{ path: "/api/v1/models", handler: () => ({ body: [] }) },
|
||||
{ path: /^\/api\/v1\/sessions\/s2\/entries/, handler: () => ({ body: entriesBody("Beta first message") }) },
|
||||
]);
|
||||
|
||||
await renderPage(chatRoutes(), "/chat/s2?workspace=W1");
|
||||
|
||||
await waitFor(() => expect(document.querySelector('[data-session-id="s2"]')).not.toBeNull());
|
||||
expect(document.querySelector('[data-session-id="s2"]')).toHaveAttribute("aria-current", "true");
|
||||
expect(document.querySelector('[data-session-id="s1"]')).not.toHaveAttribute("aria-current", "true");
|
||||
|
||||
expect(await screen.findByText("Beta first message")).toBeInTheDocument();
|
||||
expect(screen.queryByTestId("session-not-found")).toBeNull();
|
||||
expect(streamPane().querySelector(".stream-name")).toHaveTextContent("Beta");
|
||||
expect(requestedUrls(fetchMock)).toContainEqual(
|
||||
expect.stringContaining("/api/v1/sessions/s2/entries"),
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps the first-session fallback for the /chat index", async () => {
|
||||
mockApi([
|
||||
{ path: "/api/v1/workspaces", handler: () => ({ body: workspaceBody() }) },
|
||||
{ path: "/api/v1/workspaces/W1/sessions", handler: () => ({ body: sessionsBody() }) },
|
||||
{ path: "/api/v1/models", handler: () => ({ body: [] }) },
|
||||
{ path: /^\/api\/v1\/sessions\/s1\/entries/, handler: () => ({ body: entriesBody("Alpha first message") }) },
|
||||
]);
|
||||
|
||||
await renderPage(chatRoutes(), "/chat?workspace=W1");
|
||||
|
||||
expect(await screen.findByText("Alpha first message")).toBeInTheDocument();
|
||||
expect(screen.queryByTestId("session-not-found")).toBeNull();
|
||||
expect(streamPane().querySelector(".stream-name")).toHaveTextContent("Alpha");
|
||||
});
|
||||
|
||||
it("does not flash the error state while the first session fetch is in flight", async () => {
|
||||
let release = () => {};
|
||||
const gate = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
mockApi([
|
||||
{ path: "/api/v1/workspaces", handler: () => ({ body: workspaceBody() }) },
|
||||
{
|
||||
path: "/api/v1/workspaces/W1/sessions",
|
||||
handler: async () => {
|
||||
await gate;
|
||||
return { body: sessionsBody() };
|
||||
},
|
||||
},
|
||||
{ path: "/api/v1/models", handler: () => ({ body: [] }) },
|
||||
{ path: /^\/api\/v1\/sessions\/s1\/entries/, handler: () => ({ body: entriesBody("Alpha first message") }) },
|
||||
]);
|
||||
|
||||
await renderPage(chatRoutes(), `/chat/${BOGUS}?workspace=W1`);
|
||||
|
||||
// Still loading: no error surface and no borrowed session.
|
||||
expect(screen.queryByTestId("session-not-found")).toBeNull();
|
||||
expect(streamPane().querySelector(".stream-name")?.textContent ?? "").not.toContain("Alpha");
|
||||
|
||||
release();
|
||||
expect(await screen.findByTestId("session-not-found")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,12 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardSub, CardTitle } from "@/components/ui/card";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
import { StatusDot } from "@/components/ui/status-dot";
|
||||
|
||||
describe("Button", () => {
|
||||
@@ -74,3 +77,50 @@ describe("Badge", () => {
|
||||
expect(container.firstElementChild).toHaveClass("badge", "badge--warn");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Modal", () => {
|
||||
function renderModal(onClick = vi.fn()) {
|
||||
render(
|
||||
<Modal
|
||||
open
|
||||
onOpenChange={() => undefined}
|
||||
title="Confirm connection"
|
||||
description="Pairing details"
|
||||
footer={
|
||||
<Button variant="primary" onClick={onClick}>
|
||||
Connect now
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<p>host:port</p>
|
||||
</Modal>,
|
||||
);
|
||||
return onClick;
|
||||
}
|
||||
|
||||
it("nests the panel inside the backdrop so the scrim cannot intercept clicks", () => {
|
||||
renderModal();
|
||||
const dialog = screen.getByRole("dialog");
|
||||
expect(dialog).toHaveClass("modal", "modal-content");
|
||||
// Sibling content kept painting under `.modal-backdrop` (z-index 60) and
|
||||
// Playwright reported "modal-backdrop intercepts pointer events".
|
||||
expect(dialog.parentElement).toHaveClass("modal-backdrop");
|
||||
});
|
||||
|
||||
it("keeps footer buttons clickable", () => {
|
||||
const onClick = renderModal();
|
||||
const footerButton = screen.getByRole("button", { name: "Connect now" });
|
||||
expect(onClick).not.toHaveBeenCalled();
|
||||
fireEvent.click(footerButton);
|
||||
expect(onClick).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("stacks the panel above the backdrop in app.css", () => {
|
||||
const css = readFileSync(resolve(process.cwd(), "src/styles/app.css"), "utf8");
|
||||
const backdrop = /\.modal-backdrop\s*{[^}]*}/.exec(css)?.[0] ?? "";
|
||||
const modal = /\.modal\s*{[^}]*}/.exec(css)?.[0] ?? "";
|
||||
expect(backdrop).toContain("z-index: 60");
|
||||
expect(modal).toContain("position: relative");
|
||||
expect(modal).toContain("z-index: 61");
|
||||
});
|
||||
});
|
||||
+253
-37
@@ -1,9 +1,10 @@
|
||||
import { fireEvent, screen, waitFor, within } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { commandCalls, mockApi } from "./helpers/api-mock";
|
||||
import { mockApi, type MockRoute } from "./helpers/api-mock";
|
||||
import { renderPage } from "./helpers/render-page";
|
||||
|
||||
import { isPairCode, normalizePairCode, parsePairLink, safePairNext } from "@/features/connect/pairing";
|
||||
import { setLanguage } from "@/lib/i18n";
|
||||
import { ConnectPage } from "@/pages/connect";
|
||||
|
||||
@@ -14,31 +15,72 @@ const infoBody = {
|
||||
platform: "linux",
|
||||
capabilities: ["read", "steer"],
|
||||
limits: {},
|
||||
name: "ThinkPad",
|
||||
hostname: "thinkpad-x1",
|
||||
os: "linux",
|
||||
version: "0.4.2",
|
||||
uptimeMs: 3 * 3_600_000,
|
||||
};
|
||||
|
||||
function routes() {
|
||||
return [
|
||||
{ path: "/connect", component: ConnectPage },
|
||||
{ path: "/workspaces", component: () => <div>Workspaces destination</div> },
|
||||
{ path: "/chat/$sessionId", component: () => <div>Chat destination</div> },
|
||||
{ path: "/status", component: () => <div>Status destination</div> },
|
||||
];
|
||||
}
|
||||
|
||||
function redeemRoute() {
|
||||
/** `POST <origin>/api/v1/pair` → `{token, device}` (the public redeem contract). */
|
||||
function pairRoute(reply: { status?: number; body?: unknown } = {}): MockRoute {
|
||||
return {
|
||||
method: "POST" as const,
|
||||
path: "/api/v1/cmd",
|
||||
method: "POST",
|
||||
path: "/api/v1/pair",
|
||||
handler: () => ({
|
||||
body: {
|
||||
accepted: true,
|
||||
status: reply.status ?? 200,
|
||||
body: reply.body ?? {
|
||||
token: "pkt_test",
|
||||
scopes: ["read", "steer"],
|
||||
server: { name: "ThinkPad", hostname: "thinkpad" },
|
||||
device: {
|
||||
id: "dev-7c1",
|
||||
name: "My browser",
|
||||
kind: "laptop",
|
||||
scopes: ["read", "steer"],
|
||||
lastSeenAt: 1_700_000_000_000,
|
||||
},
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
interface PairCall {
|
||||
origin: string;
|
||||
body: Record<string, unknown>;
|
||||
}
|
||||
|
||||
function pairCalls(fetchMock: ReturnType<typeof mockApi>): PairCall[] {
|
||||
return fetchMock.mock.calls
|
||||
.filter(([input, init]) => {
|
||||
const raw = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
||||
return new URL(raw, "http://localhost").pathname === "/api/v1/pair" && (init?.method ?? "GET") === "POST";
|
||||
})
|
||||
.map(([input, init]) => {
|
||||
const raw = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
||||
const url = new URL(raw, "http://localhost");
|
||||
return { origin: url.origin, body: JSON.parse(String(init?.body ?? "{}")) as Record<string, unknown> };
|
||||
});
|
||||
}
|
||||
|
||||
function fillManualForm(values: { host?: string; port?: string; code?: string; device?: string }) {
|
||||
if (values.host !== undefined) fireEvent.change(screen.getByTestId("connect-host"), { target: { value: values.host } });
|
||||
if (values.port !== undefined) fireEvent.change(screen.getByTestId("connect-port"), { target: { value: values.port } });
|
||||
if (values.code !== undefined) {
|
||||
fireEvent.change(screen.getByTestId("connect-pair-code"), { target: { value: values.code } });
|
||||
}
|
||||
if (values.device !== undefined) {
|
||||
fireEvent.change(screen.getByTestId("connect-device"), { target: { value: values.device } });
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
await setLanguage("en");
|
||||
});
|
||||
@@ -48,57 +90,155 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe("ConnectPage", () => {
|
||||
it("validates host, port and token inline without calling the daemon", async () => {
|
||||
const fetchMock = mockApi([redeemRoute()]);
|
||||
it("validates host, port and the 8-character pairing code inline without calling the daemon", async () => {
|
||||
const fetchMock = mockApi([pairRoute()]);
|
||||
await renderPage(routes(), "/connect", { paired: false });
|
||||
|
||||
const submit = screen.getByRole("button", { name: "Connect" });
|
||||
const submit = screen.getByTestId("connect-submit");
|
||||
fireEvent.click(submit);
|
||||
expect(await screen.findByText("Enter the server address")).toBeInTheDocument();
|
||||
|
||||
fireEvent.change(screen.getByLabelText("Host"), { target: { value: "192.168.2.10" } });
|
||||
fireEvent.change(screen.getByLabelText("Port"), { target: { value: "99999" } });
|
||||
fillManualForm({ host: "192.168.2.10", port: "99999" });
|
||||
fireEvent.click(submit);
|
||||
expect(await screen.findByText("Port must be 1–65535")).toBeInTheDocument();
|
||||
|
||||
fireEvent.change(screen.getByLabelText("Port"), { target: { value: "4321" } });
|
||||
fillManualForm({ port: "4321" });
|
||||
fireEvent.click(submit);
|
||||
expect(await screen.findByText("Enter the pairing token")).toBeInTheDocument();
|
||||
expect(commandCalls(fetchMock)).toHaveLength(0);
|
||||
expect(await screen.findByText("Enter the 8-character pairing code")).toBeInTheDocument();
|
||||
|
||||
fillManualForm({ code: "ABC" });
|
||||
fireEvent.click(submit);
|
||||
expect(await screen.findByText("Pairing code must be 8 letters or digits (A–Z, 0–9)")).toBeInTheDocument();
|
||||
|
||||
expect(pairCalls(fetchMock)).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("redeems a manual pairing, stores endpoint + token and redirects", async () => {
|
||||
const fetchMock = mockApi([redeemRoute()]);
|
||||
it("labels the third field as a pairing code and uppercases input", async () => {
|
||||
mockApi([pairRoute()]);
|
||||
await renderPage(routes(), "/connect", { paired: false });
|
||||
|
||||
expect(screen.getByLabelText("Pairing code")).toBe(screen.getByTestId("connect-pair-code"));
|
||||
fillManualForm({ code: "ab-cd12 34" });
|
||||
expect(screen.getByTestId("connect-pair-code")).toHaveValue("ABCD1234");
|
||||
});
|
||||
|
||||
it("redeems a manual pairing against /api/v1/pair, stores token + scopes and redirects", async () => {
|
||||
const fetchMock = mockApi([pairRoute()]);
|
||||
const { router } = await renderPage(routes(), "/connect", { paired: false });
|
||||
|
||||
fireEvent.change(screen.getByLabelText("Host"), { target: { value: "192.168.2.10" } });
|
||||
fireEvent.change(screen.getByLabelText("Port"), { target: { value: "4321" } });
|
||||
fireEvent.change(screen.getByPlaceholderText("Pairing token (pkt_…)"), {
|
||||
target: { value: "ABCD-1234" },
|
||||
});
|
||||
fireEvent.change(screen.getByPlaceholderText("e.g. My browser"), {
|
||||
target: { value: "My browser" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "Connect" }));
|
||||
fillManualForm({ host: "192.168.2.10", port: "4321", code: "abcd1234", device: "My browser" });
|
||||
fireEvent.click(screen.getByTestId("connect-submit"));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(localStorage.getItem("pi2-device-token")).toBe("Bearer pkt_test"),
|
||||
);
|
||||
await waitFor(() => expect(localStorage.getItem("pi2-device-token")).toBe("Bearer pkt_test"));
|
||||
expect(localStorage.getItem("pi2-endpoint")).toBe("http://192.168.2.10:4321");
|
||||
expect(localStorage.getItem("pi2-connection")).toBe("paired");
|
||||
expect(JSON.parse(localStorage.getItem("pi2-device-scopes") ?? "[]")).toEqual(["read", "steer"]);
|
||||
|
||||
const commands = commandCalls(fetchMock);
|
||||
expect(commands).toHaveLength(1);
|
||||
expect(commands[0]?.method).toBe("pair.redeem");
|
||||
expect(commands[0]?.params).toMatchObject({
|
||||
code: "ABCD-1234",
|
||||
deviceName: "My browser",
|
||||
});
|
||||
const calls = pairCalls(fetchMock);
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(calls[0]?.origin).toBe("http://192.168.2.10:4321");
|
||||
expect(calls[0]?.body).toEqual({ code: "ABCD1234", kind: "laptop", deviceName: "My browser" });
|
||||
|
||||
await waitFor(() => expect(router.state.location.pathname).toBe("/workspaces"));
|
||||
expect(await screen.findByText("Workspaces destination")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("returns to an allow-listed deep link after pairing", async () => {
|
||||
const fetchMock = mockApi([pairRoute()]);
|
||||
const { router } = await renderPage(routes(), "/connect?next=%2Fchat%2F01a15368%3Fworkspace%3Dws-1", {
|
||||
paired: false,
|
||||
});
|
||||
|
||||
fillManualForm({ host: "192.168.2.10", code: "ABCD1234", device: "My browser" });
|
||||
fireEvent.click(screen.getByTestId("connect-submit"));
|
||||
|
||||
await waitFor(() => expect(router.state.location.pathname).toBe("/chat/01a15368"));
|
||||
expect(router.state.location.search).toMatchObject({ workspace: "ws-1" });
|
||||
expect(pairCalls(fetchMock)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("shows a localized inline error for a wrong or expired code and stays unpaired", async () => {
|
||||
mockApi([
|
||||
pairRoute({
|
||||
status: 401,
|
||||
body: { code: "E_UNAUTHORIZED", message: "invalid or already used pairing code" },
|
||||
}),
|
||||
]);
|
||||
const { router } = await renderPage(routes(), "/connect", { paired: false });
|
||||
|
||||
fillManualForm({ host: "192.168.2.10", code: "ZZZZ9999", device: "My browser" });
|
||||
fireEvent.click(screen.getByTestId("connect-submit"));
|
||||
|
||||
expect(
|
||||
await screen.findByText("Pairing code is wrong or expired. Create a new code on the server."),
|
||||
).toBeInTheDocument();
|
||||
expect(localStorage.getItem("pi2-device-token")).toBeNull();
|
||||
expect(localStorage.getItem("pi2-connection")).toBeNull();
|
||||
expect(router.state.location.pathname).toBe("/connect");
|
||||
expect(screen.getByTestId("connect-submit")).toBeEnabled();
|
||||
});
|
||||
|
||||
it("warns then pairs from a pasted pi2 pair link through the confirmation dialog", async () => {
|
||||
const fetchMock = mockApi([pairRoute()]);
|
||||
const { router } = await renderPage(routes(), "/connect", { paired: false });
|
||||
|
||||
fireEvent.click(screen.getByTestId("connect-scan"));
|
||||
const link = await screen.findByLabelText("Pairing link");
|
||||
fireEvent.change(link, {
|
||||
target: { value: "pi2://pair?host=192.168.2.10&port=4321&code=ABCD1234" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "Identify" }));
|
||||
|
||||
// Confirmation dialog: host:port + masked code, and its buttons must be clickable.
|
||||
const dialog = await screen.findByRole("dialog");
|
||||
expect(within(dialog).getByText("192.168.2.10:4321")).toBeInTheDocument();
|
||||
expect(within(dialog).getByText("…234")).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByTestId("connect-confirm-connect"));
|
||||
await waitFor(() => expect(localStorage.getItem("pi2-connection")).toBe("paired"));
|
||||
expect(pairCalls(fetchMock)[0]?.body).toMatchObject({ code: "ABCD1234" });
|
||||
await waitFor(() => expect(router.state.location.pathname).toBe("/workspaces"));
|
||||
});
|
||||
|
||||
it("cancel on the confirmation dialog leaves the connection untouched", async () => {
|
||||
const fetchMock = mockApi([pairRoute()]);
|
||||
const { router } = await renderPage(routes(), "/connect", { paired: false });
|
||||
|
||||
fireEvent.click(screen.getByTestId("connect-scan"));
|
||||
const link = await screen.findByLabelText("Pairing link");
|
||||
fireEvent.change(link, { target: { value: "pi2://pair?host=192.168.2.10&code=ABCD1234" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Identify" }));
|
||||
await screen.findByRole("dialog");
|
||||
|
||||
fireEvent.click(screen.getByTestId("connect-confirm-cancel"));
|
||||
await waitFor(() => expect(screen.queryByTestId("connect-confirm-cancel")).not.toBeInTheDocument());
|
||||
expect(pairCalls(fetchMock)).toHaveLength(0);
|
||||
expect(localStorage.getItem("pi2-connection")).toBeNull();
|
||||
expect(router.state.location.pathname).toBe("/connect");
|
||||
});
|
||||
|
||||
it("shows the paired summary with server identity, uptime and device scopes", async () => {
|
||||
mockApi([{ path: "/api/v1/info", handler: () => ({ body: infoBody }) }]);
|
||||
await renderPage(routes(), "/connect", {
|
||||
paired: true,
|
||||
storage: {
|
||||
"pi2-device": "Test browser",
|
||||
"pi2-endpoint": "http://192.168.2.10:4321",
|
||||
"pi2-device-scopes": JSON.stringify(["read", "steer"]),
|
||||
},
|
||||
});
|
||||
|
||||
expect(await screen.findByText("Current connection")).toBeInTheDocument();
|
||||
expect(screen.getByText("Test browser")).toBeInTheDocument();
|
||||
expect(await screen.findByText("thinkpad-x1")).toBeInTheDocument();
|
||||
expect(screen.getByText("linux")).toBeInTheDocument();
|
||||
expect(screen.getByText("0.4.2")).toBeInTheDocument();
|
||||
expect(screen.getByText("3h 0m")).toBeInTheDocument();
|
||||
expect(screen.getByText("Read")).toBeInTheDocument();
|
||||
expect(screen.getByText("Steer")).toBeInTheDocument();
|
||||
expect(screen.queryByText("Apply")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows the paired summary and clears storage on confirmed disconnect", async () => {
|
||||
mockApi([{ path: "/api/v1/info", handler: () => ({ body: infoBody }) }]);
|
||||
await renderPage(routes(), "/connect", {
|
||||
@@ -122,3 +262,79 @@ describe("ConnectPage", () => {
|
||||
expect(screen.queryByText("Current connection")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe("parsePairLink", () => {
|
||||
it("parses pi2:// pair links", () => {
|
||||
expect(parsePairLink("pi2://pair?host=192.168.2.10&port=4321&code=ABCD1234")).toEqual({
|
||||
endpoint: "http://192.168.2.10:4321",
|
||||
code: "ABCD1234",
|
||||
name: "192.168.2.10",
|
||||
hostname: "192.168.2.10",
|
||||
port: 4321,
|
||||
});
|
||||
expect(parsePairLink("pi2://pair?host=pi2.local&port=8443&proto=https&code=abcd1234&name=Desk")).toMatchObject({
|
||||
endpoint: "https://pi2.local:8443",
|
||||
code: "ABCD1234",
|
||||
name: "Desk",
|
||||
});
|
||||
expect(parsePairLink("pi2://pair?host=192.168.2.10:9000&code=ABCD1234")).toMatchObject({
|
||||
endpoint: "http://192.168.2.10:9000",
|
||||
});
|
||||
});
|
||||
|
||||
it("parses http(s) /pair/<CODE> links", () => {
|
||||
expect(parsePairLink("https://192.168.2.10:4321/pair/ABCD1234")).toMatchObject({
|
||||
endpoint: "https://192.168.2.10:4321",
|
||||
code: "ABCD1234",
|
||||
hostname: "192.168.2.10",
|
||||
port: 4321,
|
||||
});
|
||||
expect(parsePairLink("/pair/abcd1234", "http://192.168.2.10:4321")).toMatchObject({
|
||||
endpoint: "http://192.168.2.10:4321",
|
||||
code: "ABCD1234",
|
||||
});
|
||||
});
|
||||
|
||||
it("parses #pair=, ?pair= and ?code= against the typed endpoint", () => {
|
||||
for (const raw of ["#pair=ABCD1234", "?pair=ABCD1234", "?code=ABCD1234"]) {
|
||||
expect(parsePairLink(raw, "http://192.168.2.10:4321"), raw).toMatchObject({
|
||||
endpoint: "http://192.168.2.10:4321",
|
||||
code: "ABCD1234",
|
||||
hostname: "192.168.2.10",
|
||||
});
|
||||
}
|
||||
expect(parsePairLink("https://192.168.2.11:4321/#pair=ABCD1234&name=Pi")).toMatchObject({
|
||||
endpoint: "https://192.168.2.11:4321",
|
||||
code: "ABCD1234",
|
||||
name: "Pi",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects payloads without a code or an address", () => {
|
||||
expect(parsePairLink("")).toBeNull();
|
||||
expect(parsePairLink("#pair=")).toBeNull();
|
||||
expect(parsePairLink("not a link")).toBeNull();
|
||||
expect(parsePairLink("pi2://pair?code=ABCD1234")).toBeNull();
|
||||
expect(parsePairLink("https://192.168.2.10:4321/pair/")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("pairing helpers", () => {
|
||||
it("normalizes pairing codes to 8 uppercase alphanumerics", () => {
|
||||
expect(normalizePairCode(" abcd-1234 ")).toBe("ABCD1234");
|
||||
expect(normalizePairCode("")).toBe("");
|
||||
expect(isPairCode("ABCD1234")).toBe(true);
|
||||
expect(isPairCode("abcd 1234")).toBe(true);
|
||||
expect(isPairCode("ABCD123")).toBe(false);
|
||||
expect(isPairCode("ABCD12345")).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps allow-listed deep links across the pairing round trip", () => {
|
||||
expect(safePairNext("/chat/01a15368?workspace=ws-1")).toBe("/chat/01a15368?workspace=ws-1");
|
||||
expect(safePairNext("/workspace/ws-1")).toBe("/workspace/ws-1");
|
||||
expect(safePairNext("/status?tab=devices")).toBe("/status?tab=devices");
|
||||
expect(safePairNext("/pair/ABCD1234")).toBe("/workspaces");
|
||||
expect(safePairNext("https://evil.example/x")).toBe("/workspaces");
|
||||
expect(safePairNext(null)).toBe("/workspaces");
|
||||
});
|
||||
});
|
||||
@@ -40,6 +40,31 @@ describe("i18n catalogs", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("defines every shipped UI string", () => {
|
||||
// Regression guard: these were referenced by src/pages/status.tsx and the
|
||||
// chat task renderers but missing from both catalogs.
|
||||
for (const key of [
|
||||
"status.infoError",
|
||||
"status.healthError",
|
||||
"status.resourcesError",
|
||||
"status.modelsError",
|
||||
"status.devicesError",
|
||||
"status.tasksError",
|
||||
"chat.steerMode",
|
||||
"chat.taskExitCode",
|
||||
]) {
|
||||
expect(enFlat[key], `en ${key}`).toBeTruthy();
|
||||
expect(zhFlat[key], `zh ${key}`).toBeTruthy();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps interpolation params aligned across catalogs", () => {
|
||||
const params = (value: string) => [...value.matchAll(/\{(\w+)\}/g)].map((match) => match[1] ?? "").sort();
|
||||
for (const [key, value] of Object.entries(enFlat)) {
|
||||
expect(params(zhFlat[key] ?? ""), key).toEqual(params(value));
|
||||
}
|
||||
});
|
||||
|
||||
it("covers every prototype namespace", () => {
|
||||
for (const prefix of [
|
||||
"common.",
|
||||
|
||||
@@ -10,12 +10,28 @@ describe("safeNext", () => {
|
||||
expect(safeNext("/workspace/ws-pi2?x=1")).toBe("/workspace/ws-pi2?x=1");
|
||||
});
|
||||
|
||||
it("keeps paired deep links (session + workspace query) across the pairing round trip", () => {
|
||||
expect(safeNext("/chat/01a15368?workspace=ws-1")).toBe("/chat/01a15368?workspace=ws-1");
|
||||
expect(safeNext("/chat/01a1?workspace=ws-1&tab=todo")).toBe("/chat/01a1?workspace=ws-1&tab=todo");
|
||||
expect(connectHref(safeNext("/chat/01a1?workspace=ws-1"))).toBe(
|
||||
"/connect?next=%2Fchat%2F01a1%3Fworkspace%3Dws-1",
|
||||
);
|
||||
// The `next` param survives a full redirect → pairing → redirect cycle.
|
||||
const href = connectHref("/chat/01a1?workspace=ws-1");
|
||||
const next = new URLSearchParams(href.split("?")[1]).get("next");
|
||||
expect(safeNext(next)).toBe("/chat/01a1?workspace=ws-1");
|
||||
});
|
||||
|
||||
it("falls back for unknown or unsafe targets", () => {
|
||||
expect(safeNext(undefined)).toBe("/workspaces");
|
||||
expect(safeNext("/servers")).toBe("/workspaces");
|
||||
expect(safeNext("/connect")).toBe("/workspaces");
|
||||
expect(safeNext("/pair/ABCD1234")).toBe("/workspaces");
|
||||
expect(safeNext("javascript:alert(1)")).toBe("/workspaces");
|
||||
expect(safeNext("https://evil.example/not-a-page")).toBe("/workspaces");
|
||||
// A protocol-relative link keeps only its path (the host is never used).
|
||||
expect(safeNext("//evil.example/chat/1")).toBe("/chat/1");
|
||||
expect(safeNext("//evil.example/not-a-page")).toBe("/workspaces");
|
||||
});
|
||||
|
||||
it("builds an encoded connect redirect", () => {
|
||||
|
||||
+229
-23
@@ -1,17 +1,25 @@
|
||||
import { fireEvent, screen, waitFor, within } from "@testing-library/react";
|
||||
import { act, fireEvent, screen, waitFor, within } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { commandCalls, mockApi } from "./helpers/api-mock";
|
||||
import { commandCalls, mockApi, type MockRoute } from "./helpers/api-mock";
|
||||
import { renderPage } from "./helpers/render-page";
|
||||
|
||||
import { setLanguage } from "@/lib/i18n";
|
||||
import { StatusPage } from "@/pages/status";
|
||||
import { useConnectionStore } from "@/stores/connection";
|
||||
|
||||
/** `/info` as the daemon answers it (src/daemon/http.ts §/api/v1/info). */
|
||||
const infoBody = {
|
||||
v: 1,
|
||||
daemonId: "daemon-1",
|
||||
machineId: "machine-1",
|
||||
platform: "linux",
|
||||
hostname: "pi2-box",
|
||||
os: "Linux 6.1.0",
|
||||
version: "0.2.0",
|
||||
uptimeMs: 2 * 3_600_000 + 5 * 60_000,
|
||||
pid: 4242,
|
||||
port: 4321,
|
||||
capabilities: ["read", "steer"],
|
||||
limits: { maxInstances: 5 },
|
||||
};
|
||||
@@ -26,7 +34,8 @@ const workspacesBody = [
|
||||
sessionCount: 2,
|
||||
liveCount: 1,
|
||||
lastActiveAt: Date.now(),
|
||||
instance: null,
|
||||
// A live instance is what makes `/sessions` answer without spawning one.
|
||||
instance: { workspaceId: "ws-1", status: "ready", pid: 4242, since: Date.now() },
|
||||
},
|
||||
];
|
||||
|
||||
@@ -65,6 +74,46 @@ const modelsBody = {
|
||||
],
|
||||
};
|
||||
|
||||
const pairBody = {
|
||||
accepted: true,
|
||||
code: "ABCD1234",
|
||||
url: "http://127.0.0.1:4321/pair/ABCD1234",
|
||||
expiresAt: Date.now() + 9 * 60_000,
|
||||
nonce: "nonce-1",
|
||||
};
|
||||
|
||||
const tasksBody = {
|
||||
sessions: [
|
||||
{
|
||||
sessionId: "sess-1",
|
||||
workspaceId: "ws-1",
|
||||
tasks: [
|
||||
{
|
||||
id: "task-1",
|
||||
command: "pnpm build",
|
||||
status: "running",
|
||||
startTime: Date.now() - 5_000,
|
||||
durationMs: 4_200,
|
||||
exitCode: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
/** `GET /api/v1/devices` answers a BARE ARRAY (`auth.listDevices()`). */
|
||||
const devicesBody = [
|
||||
{
|
||||
id: "dev-1",
|
||||
name: "Pixel",
|
||||
kind: "phone",
|
||||
scopes: ["read", "steer"],
|
||||
createdAt: Date.now() - 90_000,
|
||||
lastSeenAt: Date.now() - 60_000,
|
||||
revokedAt: null,
|
||||
},
|
||||
];
|
||||
|
||||
function routes() {
|
||||
return [
|
||||
{ path: "/status", component: StatusPage },
|
||||
@@ -73,28 +122,47 @@ function routes() {
|
||||
];
|
||||
}
|
||||
|
||||
function apiRoutes(devicesHandler = () => ({ body: { devices: devicesBody } })) {
|
||||
return [
|
||||
const SESSIONS_PATH = /^\/api\/v1\/workspaces\/[^/]+\/sessions$/;
|
||||
|
||||
function apiRoutes(overrides: MockRoute[] = []) {
|
||||
const base: MockRoute[] = [
|
||||
{ path: "/api/v1/info", handler: () => ({ body: infoBody }) },
|
||||
{ path: "/api/v1/health", handler: () => ({ body: healthBody }) },
|
||||
{ path: "/api/v1/resources", handler: () => ({ body: resourcesBody }) },
|
||||
{ path: "/api/v1/workspaces", handler: () => ({ body: workspacesBody }) },
|
||||
{ path: SESSIONS_PATH, handler: () => ({ body: tasksBody }) },
|
||||
{ path: "/api/v1/models", handler: () => ({ body: modelsBody }) },
|
||||
{ path: "/api/v1/devices", handler: devicesHandler },
|
||||
{ path: "/api/v1/devices", handler: () => ({ body: devicesBody }) },
|
||||
{ method: "DELETE" as const, path: "/api/v1/devices/dev-1", handler: () => ({ status: 204 }) },
|
||||
{ method: "POST" as const, path: "/api/v1/pair", handler: () => ({ body: pairBody }) },
|
||||
{ method: "POST" as const, path: "/api/v1/cmd", handler: () => ({ body: { accepted: true } }) },
|
||||
];
|
||||
const overridePaths = overrides.map((route) => route.path);
|
||||
return [...overrides, ...base.filter((route) => !overridePaths.includes(route.path))];
|
||||
}
|
||||
|
||||
const devicesBody = [
|
||||
{
|
||||
id: "dev-1",
|
||||
name: "Pixel",
|
||||
kind: "phone",
|
||||
scopes: ["read", "steer"],
|
||||
lastActiveAt: Date.now() - 60_000,
|
||||
revokedAt: null,
|
||||
},
|
||||
];
|
||||
type FetchMock = ReturnType<typeof mockApi>;
|
||||
|
||||
/** Recorded `method path` requests (the mock keeps every call). */
|
||||
function requests(fetchMock: FetchMock, method: string, path: string): { body: unknown }[] {
|
||||
return fetchMock.mock.calls
|
||||
.filter(([input, init]) => {
|
||||
const raw = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
||||
const url = new URL(raw, "http://localhost");
|
||||
return url.pathname === path && (init?.method ?? "GET").toUpperCase() === method;
|
||||
})
|
||||
.map(([, init]) => {
|
||||
const body = init?.body;
|
||||
return { body: typeof body === "string" ? (JSON.parse(body) as unknown) : undefined };
|
||||
});
|
||||
}
|
||||
|
||||
function card(title: string): HTMLElement {
|
||||
const heading = screen.getByText(title);
|
||||
const root = heading.closest(".status-card");
|
||||
if (!(root instanceof HTMLElement)) throw new Error(`card "${title}" not found`);
|
||||
return root;
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
await setLanguage("en");
|
||||
@@ -105,7 +173,7 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe("StatusPage", () => {
|
||||
it("renders server, health, resources, models and devices", async () => {
|
||||
it("renders server, health, resources, models, tasks and devices", async () => {
|
||||
mockApi(apiRoutes());
|
||||
await renderPage(routes(), "/status", { paired: true });
|
||||
|
||||
@@ -119,24 +187,162 @@ describe("StatusPage", () => {
|
||||
expect(await screen.findByText("claude-sonnet-4")).toBeInTheDocument();
|
||||
expect(screen.getByText("200k")).toBeInTheDocument();
|
||||
expect(screen.getByText("reasoning")).toBeInTheDocument();
|
||||
// Devices come from a bare array, tasks from every workspace's sessions.
|
||||
expect(await screen.findByText("Pixel")).toBeInTheDocument();
|
||||
expect(await screen.findByText("pnpm build")).toBeInTheDocument();
|
||||
expect(screen.getByText("Paired devices")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("revokes a device only after the confirmation dialog", async () => {
|
||||
it("renders the daemon identity fields from /info and the /resources counts", async () => {
|
||||
mockApi(apiRoutes());
|
||||
await renderPage(routes(), "/status", { paired: true });
|
||||
await screen.findByText("Server info");
|
||||
|
||||
await waitFor(() => expect(screen.getByText("daemon-1")).toBeInTheDocument());
|
||||
const info = card("Server info");
|
||||
// hostname and bind address both resolve to the daemon's hostname.
|
||||
expect(within(info).getAllByText("pi2-box").length).toBeGreaterThan(0);
|
||||
expect(within(info).getByText("Linux 6.1.0")).toBeInTheDocument();
|
||||
expect(within(info).getByText("linux")).toBeInTheDocument();
|
||||
expect(within(info).getByText("0.2.0")).toBeInTheDocument();
|
||||
expect(within(info).getByText("machine-1")).toBeInTheDocument();
|
||||
expect(within(info).getByText("2h 5m")).toBeInTheDocument();
|
||||
expect(within(info).getByText("4321")).toBeInTheDocument();
|
||||
// /resources: one instance, 512 MiB total RSS.
|
||||
expect(within(info).getByText("512 MiB")).toBeInTheDocument();
|
||||
expect(within(info).getByText("Instances")).toBeInTheDocument();
|
||||
// No placeholder for fields the daemon really sends.
|
||||
expect(within(info).queryByText("—")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("reports the WebSocket state from the shared connection store", async () => {
|
||||
mockApi(apiRoutes());
|
||||
await renderPage(routes(), "/status", { paired: true });
|
||||
|
||||
expect(await screen.findByTestId("ws-status")).toHaveTextContent("Disconnected");
|
||||
act(() => useConnectionStore.getState().setWsState("open"));
|
||||
await waitFor(() => expect(screen.getByTestId("ws-status")).toHaveTextContent("Connected"));
|
||||
});
|
||||
|
||||
it("mints a pairing code for the connection card", async () => {
|
||||
const fetchMock = mockApi(apiRoutes());
|
||||
await renderPage(routes(), "/status", { paired: true });
|
||||
|
||||
expect(await screen.findByTestId("pairing-code")).toHaveTextContent("ABCD1234");
|
||||
expect(screen.getByTestId("pairing-url")).toHaveTextContent(pairBody.url);
|
||||
expect(screen.getByText(/Pairing code expires in \d+ minutes/)).toBeInTheDocument();
|
||||
|
||||
const calls = requests(fetchMock, "POST", "/api/v1/pair");
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(calls[0]?.body).toEqual({ ttlSec: 600 });
|
||||
});
|
||||
|
||||
it("offers a retry when minting a pairing code fails", async () => {
|
||||
let attempts = 0;
|
||||
mockApi(
|
||||
apiRoutes([
|
||||
{
|
||||
method: "POST",
|
||||
path: "/api/v1/pair",
|
||||
handler: () => {
|
||||
attempts += 1;
|
||||
return attempts === 1
|
||||
? { status: 500, body: { error: { code: "E_INTERNAL", message: "boom" } } }
|
||||
: { body: pairBody };
|
||||
},
|
||||
},
|
||||
]),
|
||||
);
|
||||
await renderPage(routes(), "/status", { paired: true });
|
||||
|
||||
const connection = card("Connection");
|
||||
expect(await within(connection).findByText("Internal server error")).toBeInTheDocument();
|
||||
expect(within(connection).queryByTestId("pairing-code")).not.toBeInTheDocument();
|
||||
|
||||
fireEvent.click(within(connection).getByRole("button", { name: "Retry" }));
|
||||
expect(await within(connection).findByTestId("pairing-code")).toHaveTextContent("ABCD1234");
|
||||
expect(attempts).toBe(2);
|
||||
});
|
||||
|
||||
it("revokes a device with DELETE after the confirmation dialog", async () => {
|
||||
const fetchMock = mockApi(apiRoutes());
|
||||
await renderPage(routes(), "/status", { paired: true });
|
||||
await screen.findByText("Pixel");
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Revoke" }));
|
||||
// Duplicate "Revoke" names would break strict locators: each row names its device.
|
||||
fireEvent.click(screen.getByRole("button", { name: "Revoke Pixel" }));
|
||||
const dialog = await screen.findByRole("dialog");
|
||||
expect(within(dialog).getByText('Revoke access for "Pixel"? The phone\'s next request will fail.')).toBeInTheDocument();
|
||||
expect(
|
||||
within(dialog).getByText('Revoke access for "Pixel"? The phone\'s next request will fail.'),
|
||||
).toBeInTheDocument();
|
||||
fireEvent.click(within(dialog).getByRole("button", { name: "Revoke" }));
|
||||
|
||||
await waitFor(() => expect(screen.queryByText("Pixel")).not.toBeInTheDocument());
|
||||
|
||||
const commands = commandCalls(fetchMock);
|
||||
expect(commands).toHaveLength(1);
|
||||
expect(commands[0]).toEqual({ method: "device.revoke", params: { deviceId: "dev-1" } });
|
||||
expect(requests(fetchMock, "DELETE", "/api/v1/devices/dev-1")).toHaveLength(1);
|
||||
expect(commandCalls(fetchMock)).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("still lists devices when the daemon answers the legacy {devices} envelope", async () => {
|
||||
mockApi(apiRoutes([{ path: "/api/v1/devices", handler: () => ({ body: { devices: devicesBody } }) }]));
|
||||
await renderPage(routes(), "/status", { paired: true });
|
||||
|
||||
expect(await screen.findByText("Pixel")).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Revoke Pixel" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows an error with retry when the device list fails", async () => {
|
||||
let attempts = 0;
|
||||
mockApi(
|
||||
apiRoutes([
|
||||
{
|
||||
path: "/api/v1/devices",
|
||||
handler: () => {
|
||||
attempts += 1;
|
||||
return attempts === 1
|
||||
? { status: 500, body: { error: { code: "E_INTERNAL", message: "boom" } } }
|
||||
: { body: devicesBody };
|
||||
},
|
||||
},
|
||||
]),
|
||||
);
|
||||
await renderPage(routes(), "/status", { paired: true });
|
||||
|
||||
const devices = card("Paired devices");
|
||||
expect(await within(devices).findByText("Internal server error")).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(within(devices).getByRole("button", { name: "Retry" }));
|
||||
expect(await within(devices).findByText("Pixel")).toBeInTheDocument();
|
||||
expect(attempts).toBe(2);
|
||||
});
|
||||
|
||||
it("keeps the tasks empty state when no workspace reports a task", async () => {
|
||||
mockApi(
|
||||
apiRoutes([
|
||||
{ path: SESSIONS_PATH, handler: () => ({ body: { sessions: [{ sessionId: "sess-1", tasks: [] }] } }) },
|
||||
]),
|
||||
);
|
||||
await renderPage(routes(), "/status", { paired: true });
|
||||
|
||||
const tasks = card("Background tasks");
|
||||
expect(await within(tasks).findByText("No background tasks")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("does not ask for sessions of workspaces without a live instance", async () => {
|
||||
// `/sessions` relays through instances.ensure(), which would spawn a Neovim
|
||||
// for every idle workspace — the status page must never trigger that.
|
||||
const fetchMock = mockApi(
|
||||
apiRoutes([
|
||||
{
|
||||
path: "/api/v1/workspaces",
|
||||
handler: () => ({ body: workspacesBody.map((workspace) => ({ ...workspace, instance: null })) }),
|
||||
},
|
||||
]),
|
||||
);
|
||||
await renderPage(routes(), "/status", { paired: true });
|
||||
|
||||
const tasks = card("Background tasks");
|
||||
expect(await within(tasks).findByText("No background tasks")).toBeInTheDocument();
|
||||
expect(requests(fetchMock, "GET", "/api/v1/workspaces/ws-1/sessions")).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -63,6 +63,35 @@ describe("WorkspacesPage", () => {
|
||||
|
||||
const names = [...container.querySelectorAll(".list-row__name")].map((node) => node.textContent);
|
||||
expect(names).toEqual(["Alpha", "Bravo", "Charlie"]);
|
||||
|
||||
// Stable hooks for the e2e/Playwright suite (row + enter link).
|
||||
const rows = screen.getAllByTestId("workspace-row");
|
||||
expect(rows.map((row) => row.getAttribute("data-workspace-id"))).toEqual(["ws-a", "ws-b", "ws-c"]);
|
||||
const enters = screen.getAllByTestId("workspace-enter");
|
||||
expect(enters.map((link) => link.getAttribute("href"))).toEqual([
|
||||
"/chat?workspace=ws-a",
|
||||
"/chat?workspace=ws-b",
|
||||
"/chat?workspace=ws-c",
|
||||
]);
|
||||
});
|
||||
|
||||
it("opens the new-workspace dialog from the empty state", async () => {
|
||||
const fetchMock = mockApi([
|
||||
{ path: "/api/v1/info", handler: () => ({ body: infoBody }) },
|
||||
{ path: "/api/v1/workspaces", handler: () => ({ body: [] }) },
|
||||
]);
|
||||
|
||||
await renderPage(routes(), "/workspaces", { paired: true });
|
||||
await screen.findByText("No workspaces yet");
|
||||
|
||||
fireEvent.click(screen.getAllByRole("button", { name: "Open new workspace" })[0]!);
|
||||
const dialog = await screen.findByRole("dialog");
|
||||
expect(within(dialog).getByLabelText("Path")).toBeInTheDocument();
|
||||
|
||||
// An empty path is rejected inline and issues no command.
|
||||
fireEvent.click(within(dialog).getByRole("button", { name: "Open" }));
|
||||
expect(await within(dialog).findByText("Enter a working directory path")).toBeInTheDocument();
|
||||
expect(commandCalls(fetchMock)).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("renders the empty state without a server picker", async () => {
|
||||
|
||||
+34
-3
@@ -1,6 +1,6 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { PiWsClient, type WebSocketLike, type WsFrame } from "@/lib/ws";
|
||||
import { PiWsClient, normalizeDeviceToken, type WebSocketLike, type WsFrame } from "@/lib/ws";
|
||||
|
||||
class FakeSocket implements WebSocketLike {
|
||||
readyState = 0;
|
||||
@@ -91,7 +91,34 @@ describe("PiWsClient", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("reconnects with exponential backoff and resumes with sinceSeq", () => {
|
||||
it("strips the `Bearer ` prefix the token store adds before the auth frame", () => {
|
||||
vi.useFakeTimers();
|
||||
// `setDeviceToken()` persists `Bearer <token>`; the daemon hashes the
|
||||
// frame verbatim, so the prefix must not reach the wire.
|
||||
const { client, sockets } = createClient("Bearer abc");
|
||||
client.connect();
|
||||
sockets[0]!.open();
|
||||
expect(sockets[0]!.frames("auth")).toEqual([{ v: 1, type: "auth", token: "abc" }]);
|
||||
|
||||
// The same normalization applies to every reconnect.
|
||||
sockets[0]!.receive({ type: "hello_ack" });
|
||||
sockets[0]!.serverClose(1006);
|
||||
vi.advanceTimersByTime(200);
|
||||
expect(sockets).toHaveLength(2);
|
||||
sockets[1]!.open();
|
||||
expect(sockets[1]!.frames("auth")).toEqual([{ v: 1, type: "auth", token: "abc" }]);
|
||||
});
|
||||
|
||||
it("normalizes case, whitespace and a prefix-only token", () => {
|
||||
expect(normalizeDeviceToken("bearer abc \n")).toBe("abc");
|
||||
expect(normalizeDeviceToken(" Bearer\tabc")).toBe("abc");
|
||||
expect(normalizeDeviceToken("abc")).toBe("abc");
|
||||
expect(normalizeDeviceToken("Bearer ")).toBeUndefined();
|
||||
expect(normalizeDeviceToken("")).toBeUndefined();
|
||||
expect(normalizeDeviceToken(null)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("reconnects with exponential backoff and resumes with the `since` cursor", () => {
|
||||
vi.useFakeTimers();
|
||||
const { client, sockets, states, snapshots } = createClient();
|
||||
client.connect();
|
||||
@@ -115,7 +142,11 @@ describe("PiWsClient", () => {
|
||||
sockets[1]!.receive({ type: "hello_ack" });
|
||||
expect(client.getState()).toBe("open");
|
||||
expect(sockets[1]!.frames("subscribe")).toEqual([
|
||||
{ v: 1, type: "subscribe", payload: { sessionIds: ["s1"], sinceSeq: { s1: 10 } } },
|
||||
{
|
||||
v: 1,
|
||||
type: "subscribe",
|
||||
payload: { sessionIds: ["s1"], since: { sessionId: "s1", epoch: "e1", seq: 10 } },
|
||||
},
|
||||
]);
|
||||
|
||||
// A successful hello_ack resets the backoff, so the next retry is 200ms again.
|
||||
|
||||
Reference in new issue
Block a user