Merge remote-tracking branch 'origin/main' into feature/corporate-ca
Build App / compute-version (pull_request) Successful in 4s
Build App / build-macos (pull_request) Successful in 2m28s
Build App / build-windows (pull_request) Successful in 5m20s
Build Container / build-container (pull_request) Successful in 9m58s
Build App / build-linux (pull_request) Successful in 5m12s
Build App / create-tag (pull_request) Skipped
Build App / sync-to-github (pull_request) Skipped
Build App / compute-version (pull_request) Successful in 4s
Build App / build-macos (pull_request) Successful in 2m28s
Build App / build-windows (pull_request) Successful in 5m20s
Build Container / build-container (pull_request) Successful in 9m58s
Build App / build-linux (pull_request) Successful in 5m12s
Build App / create-tag (pull_request) Skipped
Build App / sync-to-github (pull_request) Skipped
# Conflicts: # app/src/lib/tauri-commands.ts
This commit is contained in:
@@ -1,23 +1,41 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import BrowserTab from "./BrowserTab";
|
||||
import type { BrowserViewStatus, Project } from "../../../lib/types";
|
||||
import type {
|
||||
BrowserSetupOutcome,
|
||||
BrowserViewStatus,
|
||||
PlaywrightDetection,
|
||||
Project,
|
||||
} from "../../../lib/types";
|
||||
|
||||
const getBrowserViewStatus = vi.fn<() => Promise<BrowserViewStatus>>();
|
||||
const setBrowserViewEnabled = vi.fn<() => Promise<BrowserViewStatus>>();
|
||||
const checkBrowserViewSupport = vi.fn<() => Promise<PlaywrightDetection>>();
|
||||
const installBrowserViewSupport = vi.fn<() => Promise<BrowserSetupOutcome>>();
|
||||
const installBrowserViewBrowser = vi.fn<(id: string, b: string) => Promise<BrowserSetupOutcome>>();
|
||||
const pushToast = vi.fn();
|
||||
const setContainerProgress = vi.fn();
|
||||
|
||||
vi.mock("../../../lib/tauri-commands", () => ({
|
||||
getBrowserViewStatus: () => getBrowserViewStatus(),
|
||||
setBrowserViewEnabled: () => setBrowserViewEnabled(),
|
||||
checkBrowserViewSupport: () => checkBrowserViewSupport(),
|
||||
installBrowserViewSupport: () => installBrowserViewSupport(),
|
||||
installBrowserViewBrowser: (id: string, b: string) => installBrowserViewBrowser(id, b),
|
||||
}));
|
||||
|
||||
vi.mock("@tauri-apps/api/event", () => ({
|
||||
listen: vi.fn(async () => () => {}),
|
||||
}));
|
||||
|
||||
const storeState = {
|
||||
pushToast,
|
||||
setContainerProgress,
|
||||
containerProgress: {} as Record<string, string>,
|
||||
};
|
||||
|
||||
vi.mock("../../../store/appState", () => ({
|
||||
useAppState: (selector: (s: unknown) => unknown) => selector({ pushToast }),
|
||||
useAppState: (selector: (s: unknown) => unknown) => selector(storeState),
|
||||
}));
|
||||
|
||||
const OFF: BrowserViewStatus = {
|
||||
@@ -31,6 +49,33 @@ const OFF: BrowserViewStatus = {
|
||||
message: null,
|
||||
};
|
||||
|
||||
const NOTHING: PlaywrightDetection = {
|
||||
node_version: "22.11.0",
|
||||
playwright_version: null,
|
||||
playwright_path: null,
|
||||
playwright_cli: null,
|
||||
has_bind: false,
|
||||
cli_version: null,
|
||||
cli_entry: null,
|
||||
browsers: [],
|
||||
chrome_channel: null,
|
||||
searched: [
|
||||
"/workspace",
|
||||
"/usr/lib/node_modules",
|
||||
"/home/claude/.npm/_npx/9f3a/node_modules",
|
||||
],
|
||||
};
|
||||
|
||||
const READY: PlaywrightDetection = {
|
||||
...NOTHING,
|
||||
playwright_version: "1.62.1",
|
||||
playwright_path: "/workspace/node_modules/playwright-core/package.json",
|
||||
playwright_cli: "/workspace/node_modules/playwright-core/cli.js",
|
||||
has_bind: true,
|
||||
cli_version: "0.1.18",
|
||||
cli_entry: "/workspace/node_modules/@playwright/cli/playwright-cli.js",
|
||||
};
|
||||
|
||||
const project: Project = {
|
||||
id: "p1",
|
||||
name: "api-server",
|
||||
@@ -63,7 +108,9 @@ const project: Project = {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
storeState.containerProgress = {};
|
||||
getBrowserViewStatus.mockResolvedValue(OFF);
|
||||
checkBrowserViewSupport.mockResolvedValue(READY);
|
||||
});
|
||||
|
||||
describe("BrowserTab", () => {
|
||||
@@ -72,17 +119,24 @@ describe("BrowserTab", () => {
|
||||
expect(await screen.findByText(/container isn’t running/i)).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: /start browser view/i })).toBeNull();
|
||||
expect(getBrowserViewStatus).not.toHaveBeenCalled();
|
||||
expect(checkBrowserViewSupport).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("starts off, and never starts a view without being asked", async () => {
|
||||
it("starts off, and never starts a view or installs anything without being asked", async () => {
|
||||
checkBrowserViewSupport.mockResolvedValue({ ...READY, browsers: ["chromium-1200"] });
|
||||
render(<BrowserTab project={project} active />);
|
||||
await waitFor(() => expect(getBrowserViewStatus).toHaveBeenCalled());
|
||||
expect(screen.getByText("Off")).toBeInTheDocument();
|
||||
expect(screen.queryByTitle(/browser view for/i)).toBeNull();
|
||||
expect(setBrowserViewEnabled).not.toHaveBeenCalled();
|
||||
// Probing is read-only and expected; installing is a mutation and is not.
|
||||
await waitFor(() => expect(checkBrowserViewSupport).toHaveBeenCalled());
|
||||
expect(installBrowserViewSupport).not.toHaveBeenCalled();
|
||||
expect(installBrowserViewBrowser).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows the live pane, pointed at loopback with a token, once started", async () => {
|
||||
checkBrowserViewSupport.mockResolvedValue({ ...READY, browsers: ["chromium-1200"] });
|
||||
setBrowserViewEnabled.mockResolvedValue({
|
||||
...OFF,
|
||||
enabled: true,
|
||||
@@ -109,27 +163,121 @@ describe("BrowserTab", () => {
|
||||
expect(screen.getByRole("button", { name: "Stop" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("offers setup before the user hits a wall, naming what is missing", async () => {
|
||||
checkBrowserViewSupport.mockResolvedValue(NOTHING);
|
||||
|
||||
render(<BrowserTab project={project} active />);
|
||||
|
||||
// No Start attempt was needed to learn this.
|
||||
expect(await screen.findByRole("button", { name: /set up playwright/i })).toBeInTheDocument();
|
||||
expect(screen.getByText(/Missing: playwright, @playwright\/cli/)).toBeInTheDocument();
|
||||
// The npx cache is shown among the searched roots — that is where an
|
||||
// MCP-installed Playwright actually lives.
|
||||
expect(screen.getByText(/_npx\/9f3a\/node_modules/)).toBeInTheDocument();
|
||||
// A browser can't be installed before Playwright is.
|
||||
expect(screen.getByRole("button", { name: /install chromium/i })).toBeDisabled();
|
||||
});
|
||||
|
||||
it("installs Playwright on request and updates itself from the fresh probe", async () => {
|
||||
checkBrowserViewSupport.mockResolvedValue(NOTHING);
|
||||
installBrowserViewSupport.mockResolvedValue({
|
||||
detection: READY,
|
||||
log: "added 5 packages in 3s",
|
||||
browser_launched: null,
|
||||
warning: "Playwright is installed, but this container has no browser to drive yet.",
|
||||
});
|
||||
|
||||
render(<BrowserTab project={project} active />);
|
||||
const button = await screen.findByRole("button", { name: /set up playwright/i });
|
||||
await act(async () => {
|
||||
fireEvent.click(button);
|
||||
});
|
||||
|
||||
await waitFor(() => expect(installBrowserViewSupport).toHaveBeenCalled());
|
||||
// The pane re-rendered from the returned probe — no reopening the tab.
|
||||
expect(await screen.findByText("1.62.1")).toBeInTheDocument();
|
||||
// Stated in the warning box, and again in the pane's own summary line.
|
||||
expect(screen.getAllByText(/no browser to drive yet/).length).toBeGreaterThan(0);
|
||||
// And the browser buttons are now live.
|
||||
expect(screen.getByRole("button", { name: /install chromium/i })).toBeEnabled();
|
||||
expect(screen.getByRole("button", { name: /install chrome channel/i })).toBeEnabled();
|
||||
// The progress line is always cleared, whatever happened.
|
||||
expect(setContainerProgress).toHaveBeenCalledWith("p1", null);
|
||||
});
|
||||
|
||||
it("says which browser is for which caller, and states the size first", async () => {
|
||||
checkBrowserViewSupport.mockResolvedValue(READY);
|
||||
render(<BrowserTab project={project} active />);
|
||||
|
||||
expect(await screen.findByText(/several hundred mb/i)).toBeInTheDocument();
|
||||
// The copy is broken across a <code> element, so match the container.
|
||||
expect(
|
||||
screen.getByText((_, el) =>
|
||||
(el?.textContent ?? "").includes("@playwright/mcp") &&
|
||||
(el?.textContent ?? "").includes("asks for") &&
|
||||
el?.tagName.toLowerCase() === "li",
|
||||
),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByText(/roughly 150 mb/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("installs the chrome channel when that is the one asked for", async () => {
|
||||
checkBrowserViewSupport.mockResolvedValue(READY);
|
||||
installBrowserViewBrowser.mockResolvedValue({
|
||||
detection: { ...READY, chrome_channel: "/usr/bin/google-chrome-stable" },
|
||||
log: "Installing google-chrome-stable",
|
||||
browser_launched: true,
|
||||
warning: null,
|
||||
});
|
||||
|
||||
render(<BrowserTab project={project} active />);
|
||||
const button = await screen.findByRole("button", { name: /install chrome channel/i });
|
||||
await act(async () => {
|
||||
fireEvent.click(button);
|
||||
});
|
||||
|
||||
await waitFor(() =>
|
||||
expect(installBrowserViewBrowser).toHaveBeenCalledWith("p1", "chrome"),
|
||||
);
|
||||
// Shown as the step's "done" line and again in the diagnostics table.
|
||||
await waitFor(() =>
|
||||
expect(screen.getAllByText(/google-chrome-stable/).length).toBeGreaterThan(0),
|
||||
);
|
||||
});
|
||||
|
||||
it("reports an install failure with the real command output", async () => {
|
||||
checkBrowserViewSupport.mockResolvedValue(NOTHING);
|
||||
installBrowserViewSupport.mockRejectedValue(
|
||||
"npm couldn't install Playwright in this container (exit 1).\n\nnpm said:\nEACCES: permission denied",
|
||||
);
|
||||
|
||||
render(<BrowserTab project={project} active />);
|
||||
const button = await screen.findByRole("button", { name: /set up playwright/i });
|
||||
await act(async () => {
|
||||
fireEvent.click(button);
|
||||
});
|
||||
|
||||
expect(await screen.findByText(/EACCES: permission denied/)).toBeInTheDocument();
|
||||
expect(pushToast).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ kind: "error" }),
|
||||
);
|
||||
expect(setContainerProgress).toHaveBeenCalledWith("p1", null);
|
||||
});
|
||||
|
||||
it("explains precisely what is missing instead of spinning", async () => {
|
||||
checkBrowserViewSupport.mockRejectedValue("container busy");
|
||||
getBrowserViewStatus.mockResolvedValue({
|
||||
...OFF,
|
||||
enabled: true,
|
||||
state: "unavailable",
|
||||
message:
|
||||
"Playwright isn't installed in this container. Install it with `npm i -D playwright`.",
|
||||
detection: {
|
||||
node_version: "22.11.0",
|
||||
playwright_version: null,
|
||||
playwright_path: null,
|
||||
has_bind: false,
|
||||
cli_version: null,
|
||||
cli_entry: null,
|
||||
searched: ["/workspace", "/usr/lib/node_modules"],
|
||||
},
|
||||
"Playwright isn't installed in this container. Two packages are needed: `playwright` and `@playwright/cli`.",
|
||||
detection: NOTHING,
|
||||
});
|
||||
|
||||
render(<BrowserTab project={project} active />);
|
||||
|
||||
expect(await screen.findByText(/npm i -D playwright/)).toBeInTheDocument();
|
||||
expect(await screen.findByText(/Two packages are needed/)).toBeInTheDocument();
|
||||
expect(screen.getByText("Unavailable")).toBeInTheDocument();
|
||||
// The probe's findings are shown, so the user can see why.
|
||||
expect(screen.getByText("22.11.0")).toBeInTheDocument();
|
||||
@@ -139,6 +287,7 @@ describe("BrowserTab", () => {
|
||||
});
|
||||
|
||||
it("surfaces a start failure rather than leaving the pane blank", async () => {
|
||||
checkBrowserViewSupport.mockResolvedValue({ ...READY, browsers: ["chromium-1200"] });
|
||||
setBrowserViewEnabled.mockRejectedValue("container went away");
|
||||
|
||||
render(<BrowserTab project={project} active />);
|
||||
@@ -155,6 +304,7 @@ describe("BrowserTab", () => {
|
||||
});
|
||||
|
||||
it("stops the view when asked", async () => {
|
||||
checkBrowserViewSupport.mockResolvedValue({ ...READY, browsers: ["chromium-1200"] });
|
||||
getBrowserViewStatus.mockResolvedValue({
|
||||
...OFF,
|
||||
enabled: true,
|
||||
|
||||
@@ -1,15 +1,22 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import type {
|
||||
BrowserInstallTarget,
|
||||
BrowserSetupOutcome,
|
||||
BrowserViewChangedEvent,
|
||||
BrowserViewStatus,
|
||||
PlaywrightDetection,
|
||||
Project,
|
||||
} from "../../../lib/types";
|
||||
import {
|
||||
checkBrowserViewSupport,
|
||||
getBrowserViewStatus,
|
||||
installBrowserViewBrowser,
|
||||
installBrowserViewSupport,
|
||||
setBrowserViewEnabled,
|
||||
} from "../../../lib/tauri-commands";
|
||||
import { useAppState } from "../../../store/appState";
|
||||
import AccordionSection from "../../ui/AccordionSection";
|
||||
import Button from "../../ui/Button";
|
||||
import StatusIndicator from "../../ui/StatusIndicator";
|
||||
|
||||
@@ -29,6 +36,9 @@ const OFF: BrowserViewStatus = {
|
||||
message: null,
|
||||
};
|
||||
|
||||
/** Which install is in flight. `null` means none — nothing installs itself. */
|
||||
type SetupJob = null | "packages" | BrowserInstallTarget;
|
||||
|
||||
/**
|
||||
* Watch — and take over — the browser Claude is driving with Playwright inside
|
||||
* the container.
|
||||
@@ -38,6 +48,12 @@ const OFF: BrowserViewStatus = {
|
||||
* loopback. Nothing starts until the user asks: this is remote control of a
|
||||
* browser in a privileged sandbox, so it is off by default and opted into per
|
||||
* project, exactly like the auth bridge.
|
||||
*
|
||||
* The same rule, harder, applies to setup. Opening this tab *probes* the
|
||||
* container (one `node -e`, read-only) so the pane can say what is missing
|
||||
* before the user asks for a view — but it never installs anything. Installing
|
||||
* packages and downloading a browser are container mutations measured in
|
||||
* hundreds of megabytes; both are separate, labelled, user-pressed buttons.
|
||||
*/
|
||||
export default function BrowserTab({ project, active }: Props) {
|
||||
const [status, setStatus] = useState<BrowserViewStatus>(OFF);
|
||||
@@ -45,7 +61,14 @@ export default function BrowserTab({ project, active }: Props) {
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
/** Bumped to force the iframe to reload without changing its src. */
|
||||
const [reloadKey, setReloadKey] = useState(0);
|
||||
/** Last read-only probe of the container, for the setup panel. */
|
||||
const [detection, setDetection] = useState<PlaywrightDetection | null>(null);
|
||||
const [job, setJob] = useState<SetupJob>(null);
|
||||
const [outcome, setOutcome] = useState<BrowserSetupOutcome | null>(null);
|
||||
const [setupError, setSetupError] = useState<string | null>(null);
|
||||
const pushToast = useAppState((s) => s.pushToast);
|
||||
const setContainerProgress = useAppState((s) => s.setContainerProgress);
|
||||
const progress = useAppState((s) => s.containerProgress[project.id]);
|
||||
const running = project.status === "running";
|
||||
|
||||
// The backend is the source of truth: it emits whenever a view starts or is
|
||||
@@ -77,6 +100,11 @@ export default function BrowserTab({ project, active }: Props) {
|
||||
getBrowserViewStatus(projectId)
|
||||
.then((s) => mounted.current && setStatus(s))
|
||||
.catch(() => {});
|
||||
// Read-only. This is what lets the pane offer setup before the user hits a
|
||||
// wall, and it is why a "not installed" answer is never stale.
|
||||
checkBrowserViewSupport(projectId)
|
||||
.then((d) => mounted.current && setDetection(d))
|
||||
.catch(() => {});
|
||||
}, [active, projectId, running]);
|
||||
|
||||
const toggle = useCallback(
|
||||
@@ -101,8 +129,52 @@ export default function BrowserTab({ project, active }: Props) {
|
||||
[projectId, pushToast],
|
||||
);
|
||||
|
||||
// A stopped container can't be hosting a browser, so say that plainly rather
|
||||
// than offering a control that would only fail.
|
||||
/** Run one install. Every path clears the progress line it started. */
|
||||
const install = useCallback(
|
||||
async (which: Exclude<SetupJob, null>) => {
|
||||
setJob(which);
|
||||
setSetupError(null);
|
||||
setOutcome(null);
|
||||
try {
|
||||
const result =
|
||||
which === "packages"
|
||||
? await installBrowserViewSupport(projectId)
|
||||
: await installBrowserViewBrowser(projectId, which);
|
||||
if (!mounted.current) return;
|
||||
// The command re-probes, so the pane updates itself — no reopening the
|
||||
// tab, no second button to press.
|
||||
setDetection(result.detection);
|
||||
setOutcome(result);
|
||||
if (result.warning) {
|
||||
// Not an error — the step did what it said — but the caveat is the
|
||||
// part that decides whether the browser will actually work.
|
||||
pushToast({
|
||||
kind: "info",
|
||||
message: "Setup finished, with something to know",
|
||||
detail: result.warning,
|
||||
});
|
||||
} else {
|
||||
pushToast({
|
||||
kind: "success",
|
||||
message:
|
||||
which === "packages" ? "Playwright installed" : `${which} installed and verified`,
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
const detail = String(e);
|
||||
if (mounted.current) setSetupError(detail);
|
||||
pushToast({ kind: "error", message: "Setup failed", detail });
|
||||
} finally {
|
||||
setContainerProgress(projectId, null);
|
||||
if (mounted.current) setJob(null);
|
||||
}
|
||||
},
|
||||
[projectId, pushToast, setContainerProgress],
|
||||
);
|
||||
|
||||
// A stopped container can't be hosting a browser — and can't be installed
|
||||
// into either, so say that plainly rather than offering controls that would
|
||||
// only fail.
|
||||
if (!running) {
|
||||
return (
|
||||
<Explainer title="The container isn’t running.">
|
||||
@@ -113,6 +185,16 @@ export default function BrowserTab({ project, active }: Props) {
|
||||
}
|
||||
|
||||
const live = status.state === "running" && status.url;
|
||||
// Prefer the probe: it is the fresher of the two, and it is the one that
|
||||
// reflects an install that just finished.
|
||||
const probed = detection ?? status.detection;
|
||||
const ready = isUsable(probed);
|
||||
// Mirrors Rust `PlaywrightDetection::needs_browser`: the Chrome channel is an
|
||||
// apt package, so it never shows up in `browsers`, and a container that has
|
||||
// it is not missing a browser.
|
||||
const needsBrowser =
|
||||
probed !== null && probed.browsers.length === 0 && probed.chrome_channel === null;
|
||||
const needsSetup = probed !== null && (!ready || needsBrowser);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full min-h-0">
|
||||
@@ -151,7 +233,7 @@ export default function BrowserTab({ project, active }: Props) {
|
||||
<Button
|
||||
size="md"
|
||||
variant={live ? "secondary" : "primary"}
|
||||
disabled={busy}
|
||||
disabled={busy || job !== null}
|
||||
onClick={() => toggle(!status.enabled || status.state !== "running")}
|
||||
>
|
||||
{busy ? "Working…" : live ? "Stop" : "Start browser view"}
|
||||
@@ -169,8 +251,23 @@ export default function BrowserTab({ project, active }: Props) {
|
||||
/>
|
||||
) : (
|
||||
<div className="flex-1 min-h-0 overflow-y-auto">
|
||||
{status.state === "unavailable" ? (
|
||||
<Unavailable status={status} />
|
||||
{/* Setup stays on screen while an install is running and after it
|
||||
finishes, so its output and caveats don't vanish at the moment
|
||||
they become readable. */}
|
||||
{needsSetup ||
|
||||
status.state === "unavailable" ||
|
||||
job !== null ||
|
||||
outcome !== null ||
|
||||
setupError !== null ? (
|
||||
<Setup
|
||||
detection={probed}
|
||||
message={status.state === "unavailable" ? status.message : null}
|
||||
job={job}
|
||||
progress={job ? progress : undefined}
|
||||
outcome={outcome}
|
||||
error={setupError}
|
||||
onInstall={install}
|
||||
/>
|
||||
) : error ? (
|
||||
<Explainer title="The browser view didn’t start." tone="error">
|
||||
<span className="font-mono text-xs break-words">{error}</span>
|
||||
@@ -190,25 +287,214 @@ export default function BrowserTab({ project, active }: Props) {
|
||||
);
|
||||
}
|
||||
|
||||
/** The container can't serve a view — say exactly what is missing. */
|
||||
function Unavailable({ status }: { status: BrowserViewStatus }) {
|
||||
const d = status.detection;
|
||||
/** Mirrors Rust `PlaywrightDetection::is_usable`. */
|
||||
function isUsable(d: PlaywrightDetection | null): boolean {
|
||||
return d !== null && d.playwright_version !== null && d.has_bind && d.cli_entry !== null;
|
||||
}
|
||||
|
||||
/** What the container is short of, as a list rather than as prose. */
|
||||
function missingParts(d: PlaywrightDetection | null): string[] {
|
||||
if (!d) return [];
|
||||
const out: string[] = [];
|
||||
if (!d.node_version) out.push("Node.js");
|
||||
if (!d.playwright_version) out.push("playwright");
|
||||
else if (!d.has_bind) out.push("a newer playwright — this build has no browser.bind()");
|
||||
if (!d.cli_entry) out.push("@playwright/cli");
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup, as one action per line, each saying what it costs before it is
|
||||
* pressed.
|
||||
*
|
||||
* The old pane printed npm commands here and left the rest to the user. The
|
||||
* result, verified with a real one: an `@playwright/mcp` install that could
|
||||
* never satisfy this pane, a global install that hit EACCES, a Chromium that
|
||||
* downloaded and then would not start because the image shipped none of its
|
||||
* shared libraries, and a long tail of commands after that. Current base images
|
||||
* bake those libraries in, so that last one is fixed at the source — but a
|
||||
* project keeps its original base image until it is migrated, so the install
|
||||
* action still handles a container that lacks them.
|
||||
*/
|
||||
function Setup({
|
||||
detection,
|
||||
message,
|
||||
job,
|
||||
progress,
|
||||
outcome,
|
||||
error,
|
||||
onInstall,
|
||||
}: {
|
||||
detection: PlaywrightDetection | null;
|
||||
message: string | null;
|
||||
job: SetupJob;
|
||||
progress?: string;
|
||||
outcome: BrowserSetupOutcome | null;
|
||||
error: string | null;
|
||||
onInstall: (which: Exclude<SetupJob, null>) => void;
|
||||
}) {
|
||||
const busy = job !== null;
|
||||
const havePackages = isUsable(detection);
|
||||
const missing = missingParts(detection);
|
||||
const browsers = detection?.browsers ?? [];
|
||||
const chrome = detection?.chrome_channel ?? null;
|
||||
const noBrowser = browsers.length === 0 && chrome === null;
|
||||
|
||||
return (
|
||||
<div className="p-4 max-w-[46rem] space-y-3">
|
||||
<h2 className="text-[13px] font-semibold text-[var(--text-primary)]">
|
||||
This container can’t serve a browser view yet
|
||||
</h2>
|
||||
<p className="text-[13px] text-[var(--text-secondary)] leading-relaxed">
|
||||
{status.message}
|
||||
</p>
|
||||
{d && (
|
||||
<dl className="text-xs grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 pt-2 border-t border-[var(--border-color)]">
|
||||
<Detail label="Node.js" value={d.node_version} />
|
||||
<Detail label="Playwright" value={d.playwright_version} />
|
||||
<Detail label="browser.bind()" value={d.has_bind ? "available" : "not in this build"} />
|
||||
<Detail label="@playwright/cli" value={d.cli_version} />
|
||||
{d.searched.length > 0 && (
|
||||
<Detail label="Searched" value={d.searched.join(", ")} />
|
||||
<div className="p-4 max-w-[46rem] space-y-4">
|
||||
<div>
|
||||
<h2 className="text-[13px] font-semibold text-[var(--text-primary)]">
|
||||
{!havePackages
|
||||
? "This container can’t serve a browser view yet"
|
||||
: noBrowser
|
||||
? "Playwright is ready — but there’s no browser to drive yet"
|
||||
: "This container is set up"}
|
||||
</h2>
|
||||
<p className="mt-1 text-[13px] text-[var(--text-secondary)] leading-relaxed">
|
||||
{message ??
|
||||
(missing.length > 0
|
||||
? `Missing: ${missing.join(", ")}.`
|
||||
: noBrowser
|
||||
? "Playwright and the viewer are installed. Install a browser below so there is something to watch."
|
||||
: "Start the view from the button above once Claude has a browser open.")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Step
|
||||
title="1. Playwright and the viewer UI"
|
||||
detail={
|
||||
<>
|
||||
Installs <Code>playwright</Code> and <Code>@playwright/cli</Code> into{" "}
|
||||
<Code>/workspace/node_modules</Code> inside the container. That directory is
|
||||
container storage — your project folders are mounted one level down, so
|
||||
nothing of yours is touched — and no <Code>sudo</Code> is involved. Small
|
||||
download; browsers come next.
|
||||
</>
|
||||
}
|
||||
done={havePackages}
|
||||
doneLabel={`Installed — playwright ${detection?.playwright_version ?? ""}, @playwright/cli ${detection?.cli_version ?? ""}`}
|
||||
action={
|
||||
<Button
|
||||
size="md"
|
||||
variant={havePackages ? "secondary" : "primary"}
|
||||
disabled={busy}
|
||||
onClick={() => onInstall("packages")}
|
||||
>
|
||||
{job === "packages" ? "Installing…" : havePackages ? "Reinstall" : "Set up Playwright"}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
|
||||
<Step
|
||||
title="2. A browser to drive"
|
||||
detail={
|
||||
<>
|
||||
Both check the system libraries a browser links against first. Current base
|
||||
images ship them, so that step is normally skipped; a container built from an
|
||||
older image gets them installed with apt, which is the difference between a
|
||||
browser that downloads successfully and one that also starts. Both end by
|
||||
actually launching the browser to prove it works. Browsers land in{" "}
|
||||
<Code>~/.cache/ms-playwright</Code>, which is on the home volume, so they
|
||||
survive container recreation and are only lost on a project Reset.
|
||||
</>
|
||||
}
|
||||
done={browsers.length > 0 || chrome !== null}
|
||||
doneLabel={[
|
||||
browsers.length > 0 ? browsers.join(", ") : null,
|
||||
chrome ? `Chrome channel (${chrome})` : null,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · ")}
|
||||
action={
|
||||
<div className="flex flex-col gap-2 items-end">
|
||||
<Button
|
||||
size="md"
|
||||
variant={browsers.length > 0 || !havePackages ? "secondary" : "primary"}
|
||||
disabled={busy || !havePackages}
|
||||
onClick={() => onInstall("chromium")}
|
||||
>
|
||||
{job === "chromium" ? "Installing…" : "Install Chromium"}
|
||||
</Button>
|
||||
<Button
|
||||
size="md"
|
||||
disabled={busy || !havePackages}
|
||||
onClick={() => onInstall("chrome")}
|
||||
>
|
||||
{job === "chrome" ? "Installing…" : "Install Chrome channel"}
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<ul className="mt-2 space-y-1 text-xs text-[var(--text-secondary)] leading-relaxed">
|
||||
<li>
|
||||
<strong className="text-[var(--text-primary)]">Chromium</strong> — Playwright’s
|
||||
own build, used by <Code>chromium.launch()</Code> with no channel. Several
|
||||
hundred MB.
|
||||
</li>
|
||||
<li>
|
||||
<strong className="text-[var(--text-primary)]">Chrome channel</strong> — Google
|
||||
Chrome from apt, which is what <Code>@playwright/mcp</Code> asks for. Install
|
||||
this one if Claude drives the browser through the MCP plugin. Roughly 150 MB.
|
||||
</li>
|
||||
</ul>
|
||||
</Step>
|
||||
|
||||
{busy && (
|
||||
<p
|
||||
className="text-xs font-mono text-[var(--text-secondary)] break-all"
|
||||
aria-live="polite"
|
||||
>
|
||||
{progress ?? "Working…"}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="text-xs text-[var(--error)]">
|
||||
<p className="font-semibold">That didn’t work.</p>
|
||||
<pre className="mt-1 whitespace-pre-wrap font-mono break-words text-[var(--text-secondary)]">
|
||||
{error}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{outcome?.warning && (
|
||||
<div className="text-xs text-[var(--text-primary)] border border-[var(--border-color)] rounded-[var(--radius-control)] p-3">
|
||||
<p className="font-semibold">Worth knowing</p>
|
||||
<p className="mt-1 whitespace-pre-wrap text-[var(--text-secondary)] leading-relaxed">
|
||||
{outcome.warning}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{outcome?.log && (
|
||||
<AccordionSection
|
||||
id="browser-view-install-log"
|
||||
title="Install output"
|
||||
defaultOpen={false}
|
||||
>
|
||||
<pre className="p-3 text-xs font-mono whitespace-pre-wrap break-words text-[var(--text-secondary)] max-h-64 overflow-y-auto">
|
||||
{outcome.log}
|
||||
</pre>
|
||||
</AccordionSection>
|
||||
)}
|
||||
|
||||
{detection && (
|
||||
<dl className="text-xs grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 pt-3 border-t border-[var(--border-color)]">
|
||||
<Detail label="Node.js" value={detection.node_version} />
|
||||
<Detail label="Playwright" value={detection.playwright_version} />
|
||||
<Detail label="Resolved from" value={detection.playwright_path} />
|
||||
<Detail
|
||||
label="browser.bind()"
|
||||
value={detection.has_bind ? "available" : "not in this build"}
|
||||
/>
|
||||
<Detail label="@playwright/cli" value={detection.cli_version} />
|
||||
<Detail
|
||||
label="Browsers"
|
||||
value={browsers.length > 0 ? browsers.join(", ") : null}
|
||||
/>
|
||||
<Detail label="Chrome channel" value={chrome} />
|
||||
{detection.searched.length > 0 && (
|
||||
<Detail label="Searched" value={detection.searched.join(", ")} />
|
||||
)}
|
||||
</dl>
|
||||
)}
|
||||
@@ -216,6 +502,44 @@ function Unavailable({ status }: { status: BrowserViewStatus }) {
|
||||
);
|
||||
}
|
||||
|
||||
/** One numbered setup step: what it does, whether it is done, and its button. */
|
||||
function Step({
|
||||
title,
|
||||
detail,
|
||||
done,
|
||||
doneLabel,
|
||||
action,
|
||||
children,
|
||||
}: {
|
||||
title: string;
|
||||
detail: React.ReactNode;
|
||||
done: boolean;
|
||||
doneLabel?: string;
|
||||
action: React.ReactNode;
|
||||
children?: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="border border-[var(--border-color)] rounded-[var(--radius-control)] p-3">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<h3 className="text-[13px] font-semibold text-[var(--text-primary)]">{title}</h3>
|
||||
<StatusIndicator tone={done ? "ok" : "off"} label={done ? "Installed" : "Not installed"} />
|
||||
</div>
|
||||
<p className="mt-1 text-xs text-[var(--text-secondary)] leading-relaxed">{detail}</p>
|
||||
{done && doneLabel && (
|
||||
<p className="mt-1 text-xs font-mono text-[var(--text-secondary)] break-all">
|
||||
{doneLabel}
|
||||
</p>
|
||||
)}
|
||||
{children}
|
||||
</div>
|
||||
<div className="flex-shrink-0">{action}</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Detail({ label, value }: { label: string; value: string | null }) {
|
||||
return (
|
||||
<>
|
||||
|
||||
@@ -31,6 +31,22 @@ vi.mock("@tauri-apps/api/event", () => ({
|
||||
}),
|
||||
}));
|
||||
|
||||
/** Every event the hook subscribes to, so the unmount test counts the right
|
||||
* number of teardowns instead of a magic number that drifts. */
|
||||
const EVENT_NAMES = [
|
||||
"claude-token-progress",
|
||||
"claude-token-output",
|
||||
"claude-token-link",
|
||||
"claude-token-code-rejected",
|
||||
];
|
||||
|
||||
/** The sign-in URL at its real length (346 characters, measured against
|
||||
* Claude Code 2.1.226) and the 80-column slice of it that is all the visible
|
||||
* transcript ever contains. */
|
||||
const FULL_URL =
|
||||
"https://claude.com/cai/oauth/authorize?code=true&client_id=9d1c250a-e61b-44d9-88ed-5944d1962f5e&response_type=code&redirect_uri=https%3A%2F%2Fplatform.claude.com%2Foauth%2Fcode%2Fcallback&scope=user%3Ainference&code_challenge=RUX5MlWvwld1dmpvF_aPIJQWMBmffuJt4dOdL13zWAg&code_challenge_method=S256&state=su-x9PgZzvkBd3-um6G1llLNDgxptyO6HERvvCSrTbg";
|
||||
const TRUNCATED_URL = FULL_URL.slice(0, 80);
|
||||
|
||||
function emitOutput(chunk: string, projectId = "p1") {
|
||||
act(() => {
|
||||
handlers.get("claude-token-output")?.({
|
||||
@@ -39,6 +55,26 @@ function emitOutput(chunk: string, projectId = "p1") {
|
||||
});
|
||||
}
|
||||
|
||||
function emitLink(url: string, projectId = "p1") {
|
||||
act(() => {
|
||||
handlers.get("claude-token-link")?.({
|
||||
payload: { project_id: projectId, url },
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function emitCodeRejected(message: string, attemptsRemaining: number) {
|
||||
act(() => {
|
||||
handlers.get("claude-token-code-rejected")?.({
|
||||
payload: {
|
||||
project_id: "p1",
|
||||
message,
|
||||
attempts_remaining: attemptsRemaining,
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function renderModal(
|
||||
overrides: { onClose?: () => void; onAuthenticated?: () => void } = {},
|
||||
) {
|
||||
@@ -200,6 +236,93 @@ describe("ClaudeAuthModal", () => {
|
||||
const { unmount } = renderModal();
|
||||
await flowStarted();
|
||||
unmount();
|
||||
await waitFor(() => expect(unlisten).toHaveBeenCalledTimes(2));
|
||||
await waitFor(() =>
|
||||
expect(unlisten).toHaveBeenCalledTimes(EVENT_NAMES.length),
|
||||
);
|
||||
});
|
||||
|
||||
// ── The hyperlink target, not the wrapped display text ────────────────
|
||||
//
|
||||
// `claude setup-token` slices the *visible* text of its OSC 8 hyperlink to
|
||||
// the terminal width, so the transcript holds five 80-character pieces of a
|
||||
// 346-character URL. The backend lifts the whole thing out of the hyperlink
|
||||
// parameter and sends it on `claude-token-link`.
|
||||
|
||||
it("prefers the hyperlink target over the wrapped copy in the transcript", async () => {
|
||||
renderModal();
|
||||
await flowStarted();
|
||||
|
||||
// What the transcript holds: the first slice only.
|
||||
emitOutput(`Browser didn't open? Use the url below to sign in\n${TRUNCATED_URL}\n`);
|
||||
// What the hyperlink parameter holds: all of it.
|
||||
emitLink(FULL_URL);
|
||||
|
||||
const link = await screen.findByRole("link", { name: FULL_URL });
|
||||
fireEvent.click(link);
|
||||
await waitFor(() => expect(openUrl).toHaveBeenCalledWith(FULL_URL));
|
||||
expect(openUrl).not.toHaveBeenCalledWith(TRUNCATED_URL);
|
||||
});
|
||||
|
||||
it("refuses a hyperlink target that is not an Anthropic sign-in address", async () => {
|
||||
renderModal();
|
||||
await flowStarted();
|
||||
|
||||
emitLink("https://evil.tld/cai/oauth/authorize?code=true");
|
||||
|
||||
expect(screen.queryByRole("link")).not.toBeInTheDocument();
|
||||
expect(openUrl).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("ignores a hyperlink belonging to a different project", async () => {
|
||||
renderModal();
|
||||
await flowStarted();
|
||||
|
||||
emitLink(FULL_URL, "p2");
|
||||
expect(screen.queryByRole("link")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
// ── A refused code is recoverable, not a hang ─────────────────────────
|
||||
|
||||
it("reports a rejected code and lets another one be submitted", async () => {
|
||||
renderModal();
|
||||
await flowStarted();
|
||||
|
||||
const input = screen.getByLabelText("Authentication code");
|
||||
fireEvent.change(input, { target: { value: "truncated" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Submit code" }));
|
||||
await waitFor(() =>
|
||||
expect(submitClaudeTokenCode).toHaveBeenCalledWith("truncated"),
|
||||
);
|
||||
// Before the rejection arrives the UI claims the sign-in is completing.
|
||||
expect(screen.getByText("Finishing sign-in")).toBeInTheDocument();
|
||||
|
||||
emitCodeRejected(
|
||||
"That code was rejected — `claude setup-token` reports the full code was not copied. Copy it again from the Anthropic page and submit it; 2 attempts left.",
|
||||
2,
|
||||
);
|
||||
|
||||
// Reported, not waited out — and the flow is still live.
|
||||
await screen.findByText(/That code was rejected/);
|
||||
expect(screen.getByText("Code rejected — try again")).toBeInTheDocument();
|
||||
expect(screen.queryByText("Finishing sign-in")).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId("claude-auth-error")).not.toBeInTheDocument();
|
||||
|
||||
// A second code goes through without restarting the whole flow.
|
||||
fireEvent.change(input, { target: { value: "the-whole-code" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Submit code" }));
|
||||
await waitFor(() =>
|
||||
expect(submitClaudeTokenCode).toHaveBeenLastCalledWith("the-whole-code"),
|
||||
);
|
||||
expect(acquireClaudeToken).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("ends with a reported failure when the retries run out", async () => {
|
||||
acquireClaudeToken.mockRejectedValue(
|
||||
"`claude setup-token` rejected the code 3 times, so the sign-in was abandoned. No token was stored.",
|
||||
);
|
||||
renderModal();
|
||||
|
||||
const banner = await screen.findByTestId("claude-auth-error");
|
||||
expect(banner).toHaveTextContent(/rejected the code 3 times/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -27,6 +27,9 @@ interface Props {
|
||||
const PHASE_STATUS: Record<string, { tone: StatusTone; label: string }> = {
|
||||
waiting: { tone: "busy", label: "Waiting for sign-in" },
|
||||
finishing: { tone: "busy", label: "Finishing sign-in" },
|
||||
// The CLI refused a code and is back at its prompt. Distinct from "failed":
|
||||
// the flow is still live and another code will be accepted.
|
||||
rejected: { tone: "error", label: "Code rejected — try again" },
|
||||
succeeded: { tone: "ok", label: "Token stored" },
|
||||
failed: { tone: "error", label: "Authentication failed" },
|
||||
};
|
||||
@@ -88,7 +91,9 @@ export default function ClaudeAuthModal({
|
||||
? PHASE_STATUS.failed
|
||||
: flow.codeSubmitted
|
||||
? PHASE_STATUS.finishing
|
||||
: PHASE_STATUS.waiting;
|
||||
: flow.codeRejections > 0
|
||||
? PHASE_STATUS.rejected
|
||||
: PHASE_STATUS.waiting;
|
||||
|
||||
// Split for display only. `flow.signInUrl` has already passed the host
|
||||
// allowlist; this decides which half of it an ellipsis is allowed to eat.
|
||||
|
||||
Reference in New Issue
Block a user