@@ -476,6 +487,92 @@ function Checklist({ compact }: { compact: boolean }) {
)}
+
{machines.names.length > 0 ? (
diff --git a/plugins/team-setup/figma-contract.ts b/plugins/team-setup/figma-contract.ts
new file mode 100644
index 00000000..73d19afa
--- /dev/null
+++ b/plugins/team-setup/figma-contract.ts
@@ -0,0 +1,48 @@
+// The contract between team-setup's server entry and its host entry for the
+// Figma step. The host entry runs on the developer's machine, where Claude
+// Code and its MCP config live; the server only asks it what to show and
+// relays what the developer pastes. Nothing here carries a token.
+import { z } from "zod";
+
+export const FIGMA_SERVER_NAME = "figma";
+export const FIGMA_SERVER_URL = "https://mcp.figma.com/mcp";
+// Claude Code's MCP OAuth callback is always http://localhost:/callback,
+// and the only knob it exposes is `oauth.callbackPort`. Pinning one port lets
+// the step validate the URL the browser lands on and replay it against the
+// loopback listener Claude Code opened. The same port is safe on every machine:
+// the listener is loopback-only.
+export const FIGMA_CALLBACK_PORT = 53280;
+
+export const figmaHostContract = {
+ // What the step needs to draw itself: whether `claude` is here, whether the
+ // figma server is configured at user scope, whether it is signed in, and
+ // whether a sign-in is waiting for its callback.
+ state: {
+ input: z.null(),
+ output: z.object({
+ claude: z.boolean(),
+ configured: z.boolean(),
+ authenticated: z.boolean(),
+ pending: z.boolean(),
+ // The authorization URL while a sign-in waits, so a reloaded page can show it again.
+ url: z.string().nullable(),
+ message: z.string().nullable(),
+ }),
+ },
+ // Add the server at user scope and start `claude mcp login`, returning the
+ // authorization URL and the callback port Claude chose. Idempotent: a second
+ // call while one is pending returns the same URL.
+ start: {
+ input: z.null(),
+ output: z.object({ url: z.string(), port: z.number().int().positive() }),
+ },
+ // Validate the callback URL the developer pasted and replay it against the
+ // loopback listener. Returns the login process's own error when it fails.
+ complete: {
+ input: z.object({ url: z.string().trim().min(1) }).strict(),
+ output: z.object({ ok: z.boolean(), message: z.string().nullable() }),
+ },
+ cancel: { input: z.null(), output: z.object({ ok: z.boolean() }) },
+} as const;
+
+export type FigmaHostState = z.infer<(typeof figmaHostContract)["state"]["output"]>;
diff --git a/plugins/team-setup/figma.test.ts b/plugins/team-setup/figma.test.ts
new file mode 100644
index 00000000..f56cfe5d
--- /dev/null
+++ b/plugins/team-setup/figma.test.ts
@@ -0,0 +1,282 @@
+import { describe, expect, it, vi } from "vitest";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { experimental_createHostEntryHarness } from "@get-bb/plugin-sdk/testing/host";
+import {
+ createFigmaHostEntry,
+ parseAuthorizationUrl,
+ parseMcpGet,
+ resolveClaude,
+ validateCallbackUrl,
+ type FigmaProcess,
+ type FigmaResult,
+ type FigmaRunner,
+} from "./figma.js";
+
+const STATE = "RV47MxJKqLavoHiTPom0DFEjLhquGV9fRHQnvWiCLVU";
+const AUTH_URL = `https://www.figma.com/oauth/mcp?response_type=code&client_id=Y4y9cmA3GQ3XPOqfpEAGcp&code_challenge=abc&code_challenge_method=S256&redirect_uri=http%3A%2F%2Flocalhost%3A53280%2Fcallback&state=${STATE}&scope=mcp%3Aconnect&resource=https%3A%2F%2Fmcp.figma.com%2Fmcp`;
+
+describe("parseAuthorizationUrl", () => {
+ it("reads the URL, callback port and state claude prints", () => {
+ expect(parseAuthorizationUrl(["Visit this URL to authorize:", ` ${AUTH_URL}`])).toEqual({ url: AUTH_URL, port: 53280, state: STATE });
+ });
+
+ it("sees through the OSC 8 hyperlink wrapper", () => {
+ expect(parseAuthorizationUrl([`\u001b]8;;${AUTH_URL}\u0007${AUTH_URL}\u001b]8;;\u0007`])).toEqual({ url: AUTH_URL, port: 53280, state: STATE });
+ });
+
+ it("ignores URLs that are not this sign-in", () => {
+ expect(parseAuthorizationUrl(["see https://cli.figma.com/help"])).toBeNull();
+ expect(parseAuthorizationUrl([])).toBeNull();
+ });
+});
+
+describe("validateCallbackUrl", () => {
+ const good = `http://localhost:53280/callback?code=one-time&state=${STATE}`;
+
+ it("accepts the dead localhost callback the browser lands on", () => {
+ expect(validateCallbackUrl(good, 53280, STATE)).toEqual({ ok: true, search: `?code=one-time&state=${STATE}` });
+ expect(validateCallbackUrl(good.replace("localhost", "127.0.0.1"), 53280, STATE).ok).toBe(true);
+ });
+
+ it("rejects a URL that is not a URL", () => {
+ expect(validateCallbackUrl("not a url", 53280, STATE)).toMatchObject({ ok: false });
+ });
+
+ it("rejects the wrong port", () => {
+ expect(validateCallbackUrl(good.replace("53280", "53281"), 53280, STATE)).toMatchObject({ ok: false, message: expect.stringContaining("port") });
+ });
+
+ it("rejects a host that is not localhost", () => {
+ expect(validateCallbackUrl(good.replace("localhost", "example.com"), 53280, STATE)).toMatchObject({ ok: false, message: expect.stringContaining("localhost") });
+ });
+
+ it("rejects a missing code and a mismatched state", () => {
+ expect(validateCallbackUrl(`http://localhost:53280/callback?state=${STATE}`, 53280, STATE)).toMatchObject({ ok: false, message: expect.stringContaining("code") });
+ expect(validateCallbackUrl(good.replace(STATE, "other"), 53280, STATE)).toMatchObject({ ok: false, message: expect.stringContaining("different sign-in") });
+ });
+});
+
+describe("parseMcpGet", () => {
+ it("reads a signed-in server", () => {
+ expect(parseMcpGet("figma:\n Scope: User config\n Status: ✓ Connected\n")).toEqual({ configured: true, authenticated: true });
+ });
+
+ it("reads a server that needs authentication, and one that is not configured", () => {
+ expect(parseMcpGet("figma:\n Status: ! Needs authentication\n")).toEqual({ configured: true, authenticated: false });
+ expect(parseMcpGet('No MCP server named "figma". Configured servers: none')).toEqual({ configured: false, authenticated: false });
+ });
+});
+
+interface FakeHandle {
+ emit(chunk: string): void;
+ resolve(result: Partial): void;
+ killed: boolean;
+}
+
+interface Fake {
+ runner: FigmaRunner;
+ runs: Array<{ args: string[]; timeoutMs: number }>;
+ started: FakeHandle[];
+}
+
+function fakeRunner(get: Partial = {}, add: Partial = {}, remove: Partial = {}): Fake {
+ const runs: Fake["runs"] = [];
+ const started: FakeHandle[] = [];
+ const runner: FigmaRunner = {
+ run: vi.fn(async (args: string[], timeoutMs: number) => {
+ runs.push({ args, timeoutMs });
+ if (args[0] === "mcp" && args[1] === "get") return { exitCode: 0, stdout: "", stderr: "", missing: false, ...get };
+ if (args[0] === "mcp" && args[1] === "add") return { exitCode: 0, stdout: "MCP server figma added", stderr: "", missing: false, ...add };
+ if (args[0] === "mcp" && args[1] === "remove") return { exitCode: 0, stdout: "", stderr: "", missing: false, ...remove };
+ return { exitCode: 0, stdout: "", stderr: "", missing: false };
+ }),
+ startLogin: vi.fn((): FigmaProcess => {
+ const listeners: Array<(chunk: string) => void> = [];
+ let resolveExit!: (result: FigmaResult) => void;
+ const exited = new Promise((resolve) => {
+ resolveExit = resolve;
+ });
+ const handle: FakeHandle = {
+ emit: (chunk) => listeners.forEach((listener) => listener(chunk)),
+ resolve: (result) => resolveExit({ exitCode: 0, stdout: "", stderr: "", missing: false, ...result }),
+ killed: false,
+ };
+ started.push(handle);
+ return {
+ onOutput: (listener) => listeners.push(listener),
+ exited,
+ kill: () => {
+ handle.killed = true;
+ handle.resolve({ exitCode: 1, stderr: "killed" });
+ },
+ };
+ }),
+ };
+ return { runner, runs, started };
+}
+
+function createHarness(fake: Fake, fetchImpl: typeof fetch) {
+ return experimental_createHostEntryHarness(
+ createFigmaHostEntry({ runner: fake.runner, fetch: fetchImpl, startTimeoutMs: 200, completeTimeoutMs: 200, getTimeoutMs: 200, addTimeoutMs: 200 }),
+ );
+}
+
+/** Start a sign-in and feed it the authorization URL the CLI prints. */
+async function startSignIn(fake: Fake, host: ReturnType) {
+ const started = host.experimental_call("start", null);
+ await vi.waitFor(() => expect(fake.started).toHaveLength(1));
+ fake.started[0].emit(`Visit this URL to authorize:\n ${AUTH_URL}\n`);
+ return started;
+}
+
+describe("the Figma host entry", () => {
+ it("reports claude missing", async () => {
+ const fake = fakeRunner({ missing: true, exitCode: 127 });
+ const host = createHarness(fake, vi.fn());
+ expect(await host.experimental_call("state", null)).toEqual({ claude: false, configured: false, authenticated: false, pending: false, url: null, message: "claude is not installed on this machine." });
+ await host.experimental_dispose();
+ });
+
+ it("reads the signed-in state from claude mcp get", async () => {
+ const fake = fakeRunner({ stdout: "figma:\n Scope: User config\n Status: ✓ Connected\n" });
+ const host = createHarness(fake, vi.fn());
+ expect(await host.experimental_call("state", null)).toMatchObject({ claude: true, configured: true, authenticated: true, pending: false });
+ expect(fake.runs[0].args).toEqual(["mcp", "get", "figma"]);
+ await host.experimental_dispose();
+ });
+
+ it("treats 'No MCP server named' on stderr as not configured, without a warning", async () => {
+ const fake = fakeRunner({ exitCode: 1, stderr: 'No MCP server named "figma". Run `claude mcp add` to add one.' });
+ const host = createHarness(fake, vi.fn());
+ expect(await host.experimental_call("state", null)).toMatchObject({ configured: false, authenticated: false, message: null });
+ await host.experimental_dispose();
+ });
+
+ it("starts the sign-in, holds the worker, and is idempotent", async () => {
+ const fake = fakeRunner();
+ const host = createHarness(fake, vi.fn());
+ expect(await startSignIn(fake, host)).toEqual({ url: AUTH_URL, port: 53280 });
+ expect(fake.runs.find((run) => run.args[1] === "add")?.args).toEqual(["mcp", "add", "--transport", "http", "--scope", "user", "--callback-port", "53280", "figma", "https://mcp.figma.com/mcp"]);
+ expect(host.experimental_getRetainedWorkerLeaseCount()).toBe(1);
+ expect(await host.experimental_call("start", null)).toEqual({ url: AUTH_URL, port: 53280 });
+ expect(fake.started).toHaveLength(1);
+ expect(await host.experimental_call("state", null)).toMatchObject({ pending: true, url: AUTH_URL });
+ await host.experimental_dispose();
+ });
+
+ it("reuses an existing Figma server instead of re-adding it", async () => {
+ const fake = fakeRunner({ stdout: "figma:\n Scope: User config\n Status: ! Needs authentication\n URL: https://mcp.figma.com/mcp\n" });
+ const host = createHarness(fake, vi.fn());
+ await startSignIn(fake, host);
+ expect(fake.runs.some((run) => run.args[1] === "add")).toBe(false);
+ expect(fake.runs.some((run) => run.args[1] === "remove")).toBe(false);
+ await host.experimental_dispose();
+ });
+
+ it("replaces a figma server configured at another URL", async () => {
+ const fake = fakeRunner({ stdout: "figma:\n Scope: User config\n Status: ! Needs authentication\n URL: https://example.com/mcp\n" });
+ const host = createHarness(fake, vi.fn());
+ await startSignIn(fake, host);
+ expect(fake.runs.find((run) => run.args[1] === "remove")?.args).toEqual(["mcp", "remove", "figma", "-s", "user"]);
+ expect(fake.runs.some((run) => run.args[1] === "add")).toBe(true);
+ await host.experimental_dispose();
+ });
+
+ it("surfaces a remove that fails for a reason other than not found", async () => {
+ const fake = fakeRunner(
+ { stdout: "figma:\n Scope: User config\n Status: ! Needs authentication\n URL: https://example.com/mcp\n" },
+ {},
+ { exitCode: 1, stderr: "cannot remove figma from project scope" },
+ );
+ const host = createHarness(fake, vi.fn());
+ await expect(host.experimental_call("start", null)).rejects.toThrow(/cannot remove/u);
+ await host.experimental_dispose();
+ });
+
+ it("tolerates an add that reports the server already exists", async () => {
+ const fake = fakeRunner({}, { exitCode: 1, stderr: "MCP server figma already exists in user config" });
+ const host = createHarness(fake, vi.fn());
+ expect(await startSignIn(fake, host)).toEqual({ url: AUTH_URL, port: 53280 });
+ await host.experimental_dispose();
+ });
+
+ it("rejects a start whose login exits before printing a URL", async () => {
+ const fake = fakeRunner();
+ const host = createHarness(fake, vi.fn());
+ const started = host.experimental_call("start", null);
+ await vi.waitFor(() => expect(fake.started).toHaveLength(1));
+ fake.started[0].resolve({ exitCode: 1, stderr: "no TTY" });
+ await expect(started).rejects.toThrow(/no TTY/u);
+ await host.experimental_dispose();
+ });
+
+ it("validates the pasted URL, replays it, and waits for the login to finish", async () => {
+ const fake = fakeRunner();
+ const fetchImpl = vi.fn(async () => {
+ fake.started[0].resolve({ exitCode: 0, stdout: "Authenticated with figma" });
+ return new Response("ok");
+ });
+ const host = createHarness(fake, fetchImpl as unknown as typeof fetch);
+ await startSignIn(fake, host);
+ expect(await host.experimental_call("complete", { url: `http://localhost:53280/callback?code=one-time&state=${STATE}` })).toEqual({ ok: true, message: null });
+ expect(fetchImpl).toHaveBeenCalledWith(`http://127.0.0.1:53280/callback?code=one-time&state=${STATE}`);
+ expect(host.experimental_getRetainedWorkerLeaseCount()).toBe(0);
+ await host.experimental_dispose();
+ });
+
+ it("rejects a wrong-port URL without replaying anything", async () => {
+ const fake = fakeRunner();
+ const fetchImpl = vi.fn();
+ const host = createHarness(fake, fetchImpl as unknown as typeof fetch);
+ await startSignIn(fake, host);
+ expect(await host.experimental_call("complete", { url: `http://localhost:53281/callback?code=one-time&state=${STATE}` })).toMatchObject({ ok: false, message: expect.stringContaining("port") });
+ expect(fetchImpl).not.toHaveBeenCalled();
+ expect(host.experimental_getRetainedWorkerLeaseCount()).toBe(1);
+ await host.experimental_dispose();
+ });
+
+ it("reports the login's own failure", async () => {
+ const fake = fakeRunner();
+ const fetchImpl = vi.fn(async () => {
+ fake.started[0].resolve({ exitCode: 1, stderr: "Issuer mismatch in authorization response" });
+ return new Response("ok");
+ });
+ const host = createHarness(fake, fetchImpl as unknown as typeof fetch);
+ await startSignIn(fake, host);
+ expect(await host.experimental_call("complete", { url: `http://localhost:53280/callback?code=one-time&state=${STATE}` })).toMatchObject({ ok: false, message: expect.stringContaining("Issuer mismatch") });
+ await host.experimental_dispose();
+ });
+
+ it("completes with no sign-in in progress", async () => {
+ const fake = fakeRunner();
+ const host = createHarness(fake, vi.fn());
+ expect(await host.experimental_call("complete", { url: `http://localhost:53280/callback?code=x&state=${STATE}` })).toMatchObject({ ok: false, message: expect.stringContaining("No Figma sign-in") });
+ await host.experimental_dispose();
+ });
+
+ it("cancels a waiting sign-in and releases the worker", async () => {
+ const fake = fakeRunner();
+ const host = createHarness(fake, vi.fn());
+ await startSignIn(fake, host);
+ expect(await host.experimental_call("cancel", null)).toEqual({ ok: true });
+ expect(fake.started[0].killed).toBe(true);
+ expect(host.experimental_getRetainedWorkerLeaseCount()).toBe(0);
+ await host.experimental_dispose();
+ });
+});
+
+describe("resolveClaude", () => {
+ it("finds claude on PATH and returns null when it is nowhere", async () => {
+ const dir = await mkdtemp(join(tmpdir(), "figma-claude-"));
+ const file = join(dir, "claude");
+ try {
+ await writeFile(file, "#!/bin/sh\n", { mode: 0o755 });
+ expect(resolveClaude({ PATH: dir }, "/home/nobody")).toBe(file);
+ expect(resolveClaude({ PATH: "/nonexistent-bin" }, "/home/nobody")).toBeNull();
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/plugins/team-setup/figma.ts b/plugins/team-setup/figma.ts
new file mode 100644
index 00000000..d8b608d5
--- /dev/null
+++ b/plugins/team-setup/figma.ts
@@ -0,0 +1,417 @@
+// The Figma step's machine side: everything that touches `claude`, its
+// `~/.claude.json`, and its OAuth listener. It runs in the host worker on the
+// developer's machine, never on the bb server.
+//
+// Figma's remote MCP server takes browser OAuth only. Claude Code opens a
+// loopback listener on a pinned port and prints an authorization URL; the
+// browser lands on a dead `http://localhost:/callback?code=...` page,
+// and the developer pastes that URL back here. This entry replays it against
+// the listener. Only the one-time code passes through the plugin; the PKCE
+// verifier stays inside Claude Code, and the token lands in Claude Code's own
+// credential store.
+//
+// `claude mcp login` refuses to run unless stdin is a terminal (it offers the
+// paste-the-redirect-URL prompt), so the login is started under `script`,
+// which gives it a pseudo-terminal. Its stdin pipe is held open for the
+// login's lifetime so the prompt is not closed early.
+import { execFile, spawn, type ChildProcess } from "node:child_process";
+import { accessSync, constants } from "node:fs";
+import { homedir } from "node:os";
+import { delimiter, join } from "node:path";
+import { experimental_defineHostEntry, experimental_sanitizeInheritedChildProcessEnv } from "@get-bb/plugin-sdk/host";
+import { FIGMA_CALLBACK_PORT, FIGMA_SERVER_NAME, FIGMA_SERVER_URL, figmaHostContract } from "./figma-contract.js";
+
+export interface FigmaResult {
+ exitCode: number;
+ stdout: string;
+ stderr: string;
+ /** `claude` was not found; the command never ran. */
+ missing: boolean;
+}
+
+export interface FigmaProcess {
+ /** Every chunk the process writes to stdout or stderr, as it arrives. */
+ onOutput(listener: (chunk: string) => void): void;
+ exited: Promise;
+ kill(): void;
+}
+
+export interface FigmaRunner {
+ /** Run `claude` and collect its output. */
+ run(args: string[], timeoutMs: number): Promise;
+ /** Start `claude mcp login` under a pseudo-terminal, its stdin left open. */
+ startLogin(): FigmaProcess;
+}
+
+export interface FigmaHostDeps {
+ runner: FigmaRunner;
+ fetch: typeof fetch;
+ /** How long a pending sign-in may wait for the callback before it is killed. */
+ ttlMs?: number;
+ startTimeoutMs?: number;
+ completeTimeoutMs?: number;
+ getTimeoutMs?: number;
+ addTimeoutMs?: number;
+}
+
+export interface FigmaAuthorization {
+ url: string;
+ port: number;
+ state: string;
+}
+
+export type CallbackCheck = { ok: true; search: string } | { ok: false; message: string };
+
+// The authorization URL is printed wrapped in an OSC 8 hyperlink and again
+// plain; either copy parses. Control characters end a match so the escape
+// sequence around it is not swallowed.
+const URL_PATTERN = /https?:\/\/[^\s\u0000-\u001f"'<>]+/u;
+
+/** The authorization URL, callback port and state from `claude mcp login`'s output, if present. */
+export function parseAuthorizationUrl(lines: readonly string[]): FigmaAuthorization | null {
+ for (const line of lines) {
+ const match = URL_PATTERN.exec(line);
+ if (match === null) continue;
+ let url: URL;
+ try {
+ url = new URL(match[0]);
+ } catch {
+ continue;
+ }
+ const redirect = url.searchParams.get("redirect_uri");
+ const state = url.searchParams.get("state");
+ if (redirect === null || state === null || state === "") continue;
+ let callback: URL;
+ try {
+ callback = new URL(redirect);
+ } catch {
+ continue;
+ }
+ if (callback.pathname !== "/callback") continue;
+ const port = callback.port === "" ? (callback.protocol === "https:" ? 443 : 80) : Number(callback.port);
+ if (!Number.isInteger(port) || port <= 0) continue;
+ return { url: match[0], port, state };
+ }
+ return null;
+}
+
+const CALLBACK_HOSTS = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
+
+/** Validate the dead callback URL the developer pasted against the sign-in that is waiting. */
+export function validateCallbackUrl(pasted: string, port: number, state: string): CallbackCheck {
+ let url: URL;
+ try {
+ url = new URL(pasted.trim());
+ } catch {
+ return { ok: false, message: "That is not a URL. Paste the whole address from the browser's address bar." };
+ }
+ if (url.protocol !== "http:") return { ok: false, message: "The callback URL must start with http://." };
+ if (!CALLBACK_HOSTS.has(url.hostname.toLowerCase())) {
+ return { ok: false, message: "The callback URL must point at localhost, where Claude Code is listening." };
+ }
+ const actualPort = url.port === "" ? "80" : url.port;
+ if (actualPort !== String(port)) {
+ return { ok: false, message: `The callback URL's port is ${actualPort}, but this sign-in is listening on ${port}.` };
+ }
+ if (url.pathname !== "/callback") return { ok: false, message: "The callback URL must be the /callback address." };
+ const code = url.searchParams.get("code");
+ if (code === null || code === "") return { ok: false, message: "The callback URL has no code in it." };
+ const returnedState = url.searchParams.get("state");
+ if (returnedState !== state) {
+ return { ok: false, message: "That callback URL belongs to a different sign-in. Start again." };
+ }
+ return { ok: true, search: url.search };
+}
+
+/** Whether `claude mcp get figma` reports the server configured and signed in. */
+export function parseMcpGet(stdout: string): { configured: boolean; authenticated: boolean } {
+ if (/No MCP server named/iu.test(stdout)) return { configured: false, authenticated: false };
+ const status = /^[ \t]*Status:\s*(.+)$/mu.exec(stdout)?.[1]?.trim() ?? "";
+ if (status === "") return { configured: false, authenticated: false };
+ // A server with no stored credentials reports "Needs authentication"
+ // without connecting. Anything else — connected, or a connection error —
+ // means Claude Code holds a credential for it.
+ const authenticated = !/Needs authentication/iu.test(status) && !/Not configured/iu.test(status);
+ return { configured: true, authenticated };
+}
+
+function tail(text: string, lines = 3): string {
+ return text
+ .trim()
+ .split("\n")
+ .filter((line) => line.trim() !== "")
+ .slice(-lines)
+ .join(" ")
+ .trim();
+}
+
+function errorMessage(error: unknown): string {
+ return error instanceof Error ? error.message : String(error);
+}
+
+/** Find the `claude` the provider would run, on PATH first and then where it installs. */
+export function resolveClaude(env: NodeJS.ProcessEnv = process.env, home = homedir()): string | null {
+ const names = process.platform === "win32" ? ["claude.exe", "claude.cmd", "claude"] : ["claude"];
+ for (const dir of (env.PATH ?? "").split(delimiter)) {
+ if (dir === "") continue;
+ for (const name of names) {
+ const candidate = join(dir, name);
+ try {
+ accessSync(candidate, constants.X_OK);
+ return candidate;
+ } catch {
+ // keep looking
+ }
+ }
+ }
+ for (const candidate of [join(home, ".local", "bin", "claude"), join(home, ".claude", "local", "claude"), "/opt/homebrew/bin/claude", "/usr/local/bin/claude"]) {
+ try {
+ accessSync(candidate, constants.X_OK);
+ return candidate;
+ } catch {
+ // keep looking
+ }
+ }
+ return null;
+}
+
+function shellQuote(value: string): string {
+ return `'${value.replaceAll("'", `'\\''`)}'`;
+}
+
+function claudeEnvironment(): NodeJS.ProcessEnv {
+ const env = experimental_sanitizeInheritedChildProcessEnv({ env: process.env });
+ env.TERM = "xterm-256color";
+ env.NO_COLOR = "1";
+ return env;
+}
+
+function collect(child: ChildProcess): FigmaProcess {
+ const listeners: Array<(chunk: string) => void> = [];
+ let stdout = "";
+ let stderr = "";
+ child.stdout?.setEncoding("utf8");
+ child.stdout?.on("data", (chunk: string) => {
+ stdout += chunk;
+ for (const listener of listeners) listener(chunk);
+ });
+ child.stderr?.setEncoding("utf8");
+ child.stderr?.on("data", (chunk: string) => {
+ stderr += chunk;
+ for (const listener of listeners) listener(chunk);
+ });
+ const exited = new Promise((resolve) => {
+ child.on("error", (error) => {
+ stderr += error.message;
+ resolve({ exitCode: 1, stdout, stderr, missing: false });
+ });
+ child.on("close", (code) => resolve({ exitCode: code ?? 1, stdout, stderr, missing: false }));
+ });
+ return { onOutput: (listener) => listeners.push(listener), exited, kill: () => child.kill("SIGTERM") };
+}
+
+export function createFigmaRunner(): FigmaRunner {
+ return {
+ run(args, timeoutMs) {
+ const command = resolveClaude();
+ if (command === null) return Promise.resolve({ exitCode: 127, stdout: "", stderr: "claude: not found", missing: true });
+ return new Promise((resolve) => {
+ execFile(
+ command,
+ args,
+ { timeout: timeoutMs, maxBuffer: 4 * 1024 * 1024, env: claudeEnvironment(), windowsHide: true },
+ (error, stdout, stderr) => {
+ const failure = error as (Omit & { code?: string | number; killed?: boolean }) | null;
+ if (failure?.code === "ENOENT") return resolve({ exitCode: 127, stdout: "", stderr: "claude: not found", missing: true });
+ const exitCode = failure === null ? 0 : typeof failure.code === "number" ? failure.code : 1;
+ resolve({
+ exitCode,
+ stdout: String(stdout),
+ stderr: failure !== null && failure.killed ? `claude did not finish in ${timeoutMs / 1000}s` : String(stderr),
+ missing: false,
+ });
+ },
+ );
+ });
+ },
+ startLogin() {
+ const command = resolveClaude();
+ if (command === null) throw new Error("claude is not installed on this machine.");
+ // util-linux `script -qec /dev/null`; the BSD/macOS form passes
+ // the command as arguments after the typescript file.
+ const args =
+ process.platform === "darwin"
+ ? ["-q", "/dev/null", command, "mcp", "login", "--no-browser", FIGMA_SERVER_NAME]
+ : ["-qec", `${shellQuote(command)} mcp login --no-browser ${FIGMA_SERVER_NAME}`, "/dev/null"];
+ const child = spawn("script", args, { env: claudeEnvironment(), stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
+ // The stdin pipe is deliberately never ended: ending it closes the PTY,
+ // which makes Claude Code abort the sign-in.
+ return collect(child);
+ },
+ };
+}
+
+function waitForAuthorization(process: FigmaProcess, timeoutMs: number): Promise {
+ return new Promise((resolve, reject) => {
+ let buffer = "";
+ let settled = false;
+ const timer = setTimeout(() => {
+ if (settled) return;
+ settled = true;
+ process.kill();
+ reject(new Error("claude printed no authorization URL; is Claude Code up to date?"));
+ }, timeoutMs);
+ const finish = (action: () => void) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ action();
+ };
+ process.onOutput((chunk) => {
+ if (settled) return;
+ buffer += chunk;
+ const parsed = parseAuthorizationUrl(buffer.split(/\r?\n/u));
+ if (parsed !== null) finish(() => resolve(parsed));
+ });
+ void process.exited.then((result) => {
+ finish(() => reject(new Error(tail(result.stderr || result.stdout) || `claude mcp login exited with ${result.exitCode}`)));
+ });
+ });
+}
+
+function waitForExit(promise: Promise, timeoutMs: number): Promise {
+ return new Promise((resolve) => {
+ const timer = setTimeout(() => resolve(null), timeoutMs);
+ void promise.then(
+ (result) => {
+ clearTimeout(timer);
+ resolve(result);
+ },
+ () => {
+ clearTimeout(timer);
+ resolve(null);
+ },
+ );
+ });
+}
+
+interface Pending {
+ process: FigmaProcess;
+ url: string;
+ port: number;
+ state: string;
+ lease: { dispose(): void };
+ timer: ReturnType;
+}
+
+export function createFigmaHostEntry(deps: FigmaHostDeps) {
+ const ttlMs = deps.ttlMs ?? 15 * 60 * 1000;
+ const startTimeoutMs = deps.startTimeoutMs ?? 20_000;
+ const completeTimeoutMs = deps.completeTimeoutMs ?? 30_000;
+ const getTimeoutMs = deps.getTimeoutMs ?? 10_000;
+ const addTimeoutMs = deps.addTimeoutMs ?? 20_000;
+ let pending: Pending | null = null;
+
+ function clearPending(kill: boolean): void {
+ if (pending === null) return;
+ const entry = pending;
+ pending = null;
+ clearTimeout(entry.timer);
+ if (kill) entry.process.kill();
+ entry.lease.dispose();
+ }
+
+ // `claude mcp add` refuses a server that already exists (exit 1, "already
+ // exists in user config"), so a retry after a cancel or a failed sign-in must
+ // not re-add blindly. Read the existing config back: an entry already at our
+ // URL is left alone, anything else named figma is replaced so the sign-in is
+ // against Figma's server. Removing a differently-configured entry only drops
+ // credentials for the wrong server, and the step is only offered while it is
+ // not signed in.
+ async function ensureConfigured(): Promise {
+ const existing = await deps.runner.run(["mcp", "get", FIGMA_SERVER_NAME], getTimeoutMs);
+ if (existing.missing) throw new Error("claude is not installed on this machine.");
+ const output = `${existing.stdout}\n${existing.stderr}`;
+ if (existing.exitCode === 0 && existing.stdout.includes(FIGMA_SERVER_URL)) return;
+ if (!/No MCP server named/iu.test(output)) {
+ const removed = await deps.runner.run(["mcp", "remove", FIGMA_SERVER_NAME, "-s", "user"], addTimeoutMs);
+ // A remove that fails for a reason other than "not found" (say a
+ // differently-scoped entry it cannot touch) would leave an old server in
+ // place; surface it rather than letting the add's "already exists" hide it.
+ if (removed.exitCode !== 0 && !/No MCP server named|not found/iu.test(`${removed.stdout}${removed.stderr}`)) {
+ throw new Error(tail(removed.stderr) || `claude mcp remove exited with ${removed.exitCode}`);
+ }
+ }
+ const added = await deps.runner.run(
+ ["mcp", "add", "--transport", "http", "--scope", "user", "--callback-port", String(FIGMA_CALLBACK_PORT), FIGMA_SERVER_NAME, FIGMA_SERVER_URL],
+ addTimeoutMs,
+ );
+ if (added.missing) throw new Error("claude is not installed on this machine.");
+ if (added.exitCode !== 0 && !/already exists/iu.test(added.stderr)) throw new Error(tail(added.stderr) || `claude mcp add exited with ${added.exitCode}`);
+ }
+
+ return experimental_defineHostEntry({
+ contract: figmaHostContract,
+ handlers: {
+ async state() {
+ if (pending !== null) {
+ return { claude: true, configured: true, authenticated: false, pending: true, url: pending.url, message: null };
+ }
+ const result = await deps.runner.run(["mcp", "get", FIGMA_SERVER_NAME], getTimeoutMs);
+ if (result.missing) return { claude: false, configured: false, authenticated: false, pending: false, url: null, message: "claude is not installed on this machine." };
+ // `mcp get` puts "No MCP server named …" on stderr when no servers are
+ // configured at all, and on stdout when others are; parse both.
+ const parsed = parseMcpGet(`${result.stdout}\n${result.stderr}`);
+ return { claude: true, ...parsed, pending: false, url: null, message: parsed.configured && result.exitCode !== 0 ? tail(result.stderr) || null : null };
+ },
+
+ async start(_input, context) {
+ if (pending !== null) return { url: pending.url, port: pending.port };
+ await ensureConfigured();
+ const process = deps.runner.startLogin();
+ const authorization = await waitForAuthorization(process, startTimeoutMs);
+ const entry: Pending = {
+ process,
+ url: authorization.url,
+ port: authorization.port,
+ state: authorization.state,
+ lease: context.experimental_retainWorker(),
+ timer: setTimeout(() => {
+ if (pending === entry) clearPending(true);
+ }, ttlMs),
+ };
+ pending = entry;
+ void process.exited.then(() => {
+ if (pending === entry) clearPending(false);
+ });
+ return { url: authorization.url, port: authorization.port };
+ },
+
+ async complete({ url }) {
+ if (pending === null) return { ok: false, message: "No Figma sign-in is in progress. Start it again." };
+ const entry = pending;
+ const checked = validateCallbackUrl(url, entry.port, entry.state);
+ if (!checked.ok) return { ok: false, message: checked.message };
+ try {
+ const response = await deps.fetch(`http://127.0.0.1:${entry.port}/callback${checked.search}`);
+ await response.text();
+ } catch (error) {
+ return { ok: false, message: `Could not reach the sign-in listener on this machine: ${errorMessage(error)}` };
+ }
+ const result = await waitForExit(entry.process.exited, completeTimeoutMs);
+ if (pending === entry) clearPending(result === null);
+ if (result === null) return { ok: false, message: "The sign-in did not finish in time. Start it again." };
+ if (result.exitCode === 0) return { ok: true, message: null };
+ return { ok: false, message: tail(result.stderr || result.stdout) || `claude mcp login exited with ${result.exitCode}` };
+ },
+
+ async cancel() {
+ clearPending(true);
+ return { ok: true };
+ },
+ },
+ dispose() {
+ clearPending(true);
+ },
+ });
+}
diff --git a/plugins/team-setup/host.ts b/plugins/team-setup/host.ts
new file mode 100644
index 00000000..5152e80f
--- /dev/null
+++ b/plugins/team-setup/host.ts
@@ -0,0 +1,5 @@
+// The host entry for team-setup: the Figma step runs where Claude Code and its
+// MCP config live, on the developer's machine. See figma.ts for the flow.
+import { createFigmaHostEntry, createFigmaRunner } from "./figma.js";
+
+export default createFigmaHostEntry({ runner: createFigmaRunner(), fetch });
diff --git a/plugins/team-setup/package.json b/plugins/team-setup/package.json
index ec8c6d81..52292ad2 100644
--- a/plugins/team-setup/package.json
+++ b/plugins/team-setup/package.json
@@ -4,8 +4,8 @@
"type": "module",
"description": "First-run checklist for a bb-gate server: Claude or Codex, GitHub, devbox, first machine",
"engines": {
- "bb": ">=0.45",
- "bbPluginSdk": ">=0.6.15"
+ "bb": ">=0.46",
+ "bbPluginSdk": ">=0.6.37"
},
"bb": {
"name": "Team setup",
@@ -14,6 +14,7 @@
"icon": "ListTodo"
},
"server": "./server.ts",
+ "host": "./host.ts",
"app": "./app.tsx"
},
"keywords": [
diff --git a/plugins/team-setup/server.test.ts b/plugins/team-setup/server.test.ts
index 4e38d83a..71557760 100644
--- a/plugins/team-setup/server.test.ts
+++ b/plugins/team-setup/server.test.ts
@@ -44,16 +44,32 @@ interface World {
pool?: unknown;
devbox?: unknown;
linear?: unknown;
- hosts?: Array<{ name: string }>;
+ hosts?: Array<{ id?: string; name: string; status?: string }>;
+ figmaHost?: { claude: boolean; configured: boolean; authenticated: boolean; pending: boolean; url: string | null; message: string | null };
+ figmaComplete?: { ok: boolean; message: string | null };
runs?: Record;
settings?: Record;
env?: Record;
setVariable?: (input: { name: string; value: string; note: string | null }) => Promise;
}
+const FIGMA_OPTIONAL = { claude: true, configured: false, authenticated: false, pending: false, url: null, message: null };
+
async function setup(world: World = {}) {
const gh = fakeGh(world.runs);
- const { bb, harness } = createFakePluginHost({ pluginId: "team-setup", settings: world.settings ?? {} });
+ const hostCalls: Array<{ method: string; input: unknown; hostId: string }> = [];
+ const { bb, harness } = createFakePluginHost({
+ pluginId: "team-setup",
+ settings: world.settings ?? {},
+ experimental_callHostRpc: (call) => {
+ hostCalls.push({ method: call.method, input: call.input, hostId: call.hostId });
+ if (call.method === "state") return world.figmaHost ?? FIGMA_OPTIONAL;
+ if (call.method === "start") return { url: "https://www.figma.com/oauth/mcp?response_type=code", port: 53280 };
+ if (call.method === "complete") return world.figmaComplete ?? { ok: true, message: null };
+ if (call.method === "cancel") return { ok: true };
+ throw new Error(`no answer for host ${call.method}`);
+ },
+ });
harness.sdk.stub("plugins.list", async () => ({
plugins: (world.plugins ?? [{ id: ACCOUNT_POOL_ID, enabled: true }, { id: DEVBOX_ID, enabled: true }, { id: LINEAR_ID, enabled: true }]).map((p) => ({ ...p, name: p.id })),
}));
@@ -61,7 +77,7 @@ async function setup(world: World = {}) {
builtInGit: world.builtInGit ?? { status: "not logged in", statusMessage: "gh is not logged in on the server" },
variables: [],
}));
- harness.sdk.stub("hosts.list", async () => world.hosts ?? []);
+ harness.sdk.stub("hosts.list", async () => (world.hosts ?? []).map((host, index) => ({ id: host.id ?? `host-${index}`, name: host.name, status: host.status ?? "connected" })));
const setVariables: Array<{ name: string; value: string; note: string | null }> = [];
harness.sdk.stub("system.setMachineEnvironmentVariable", async (input: { name: string; value: string; note: string | null }) => {
setVariables.push(input);
@@ -96,7 +112,7 @@ async function setup(world: World = {}) {
let now = 1_000_000;
await createTeamSetupPlugin({ gh: gh.runner, now: () => now, env: world.env ?? {} })(bb);
const status = async () => (await harness.callRpc("status", null)) as Awaited>;
- return { bb, harness, gh, rpcCalls, status, setVariables, advance: (ms: number) => (now += ms) };
+ return { bb, harness, gh, rpcCalls, hostCalls, status, setVariables, advance: (ms: number) => (now += ms) };
}
// Only for the inferred return type above.
declare function statusType(): Promise<{
@@ -104,8 +120,9 @@ declare function statusType(): Promise<{
github: { status: string; login: string | null; orgMember: boolean | null; pending: { code: string; url: string } | null; lastError: string | null };
devbox: { available: boolean; connected: boolean; project: string | null; message: string | null };
linear: { available: boolean; connected: boolean; configured: boolean; user: string | null; organization: string | null; message: string | null };
+ figma: { available: boolean; message: string | null; machine: string | null; claude: boolean; configured: boolean; authenticated: boolean; pending: boolean; url: string | null };
machines: { names: string[] };
- steps: { ai: string; github: string; devbox: string; linear: string; machine: string };
+ steps: { ai: string; github: string; devbox: string; linear: string; figma: string; machine: string };
complete: boolean;
}>;
@@ -118,7 +135,7 @@ describe("status", () => {
it("starts with everything to do", async () => {
const { status } = await setup();
const s = await status();
- expect(s.steps).toEqual({ ai: "todo", github: "todo", devbox: "todo", linear: "optional", machine: "todo" });
+ expect(s.steps).toEqual({ ai: "todo", github: "todo", devbox: "todo", linear: "optional", figma: "unavailable", machine: "todo" });
expect(s.complete).toBe(false);
expect(s.github.login).toBeNull();
});
@@ -133,7 +150,7 @@ describe("status", () => {
runs: signedIn,
});
const s = await status();
- expect(s.steps).toEqual({ ai: "done", github: "done", devbox: "done", linear: "done", machine: "done" });
+ expect(s.steps).toEqual({ ai: "done", github: "done", devbox: "done", linear: "done", figma: "optional", machine: "done" });
expect(s.complete).toBe(true);
expect(s.linear).toMatchObject({ connected: true, user: "jane", organization: "Acme" });
expect(s.github.login).toBe("octocat");
@@ -160,7 +177,7 @@ describe("status", () => {
const s = await status();
expect(s.devbox.available).toBe(false);
expect(s.devbox.message).toContain("turned off");
- expect(s.steps).toEqual({ ai: "done", github: "done", devbox: "unavailable", linear: "unavailable", machine: "done" });
+ expect(s.steps).toEqual({ ai: "done", github: "done", devbox: "unavailable", linear: "unavailable", figma: "optional", machine: "done" });
expect(s.complete).toBe(true);
});
@@ -319,6 +336,83 @@ describe("Account Pool and devbox flows", () => {
});
});
+describe("Figma step", () => {
+ it("is unavailable until a machine is connected", async () => {
+ const { status } = await setup();
+ const s = await status();
+ expect(s.steps.figma).toBe("unavailable");
+ expect(s.figma).toMatchObject({ available: false, machine: null });
+ expect(s.figma.message).toContain("No machine");
+ });
+
+ it("is unavailable when claude is not on the machine", async () => {
+ const { status } = await setup({ hosts: [{ name: "box" }], figmaHost: { claude: false, configured: false, authenticated: false, pending: false, url: null, message: "claude is not installed on this machine." } });
+ const s = await status();
+ expect(s.steps.figma).toBe("unavailable");
+ expect(s.figma).toMatchObject({ available: false, machine: "box", claude: false });
+ expect(s.figma.message).toContain("claude is not installed");
+ });
+
+ it("is optional before Figma is configured, so a server that never uses it stays complete", async () => {
+ const { status } = await setup({
+ builtInGit: { status: "logged in", statusMessage: "ok" },
+ pool: { routing: { claude: true, codex: false }, accounts: [{ id: "a", provider: "claude", label: "me", enabled: true, status: "ready" }] },
+ devbox: { connected: true, project: "dylan" },
+ linear: { connected: true, configured: true, user: { id: "u1", name: "jane", email: null }, organization: { name: "Acme", urlKey: "acme" } },
+ hosts: [{ name: "box" }],
+ runs: signedIn,
+ });
+ const s = await status();
+ expect(s.steps.figma).toBe("optional");
+ expect(s.figma).toMatchObject({ available: true, machine: "box", claude: true, configured: false, authenticated: false });
+ expect(s.complete).toBe(true);
+ });
+
+ it("is a to-do once configured but not signed in", async () => {
+ const { status } = await setup({ hosts: [{ name: "box" }], figmaHost: { claude: true, configured: true, authenticated: false, pending: false, url: null, message: null } });
+ expect((await status()).steps.figma).toBe("todo");
+ });
+
+ it("is a to-do while a sign-in waits for its callback", async () => {
+ const { status } = await setup({ hosts: [{ name: "box" }], figmaHost: { claude: true, configured: true, authenticated: false, pending: true, url: "https://www.figma.com/oauth/mcp?x", message: null } });
+ const s = await status();
+ expect(s.steps.figma).toBe("todo");
+ expect(s.figma.url).toBe("https://www.figma.com/oauth/mcp?x");
+ });
+
+ it("is done once Claude Code is signed in", async () => {
+ const { status } = await setup({ hosts: [{ name: "box" }], figmaHost: { claude: true, configured: true, authenticated: true, pending: false, url: null, message: null } });
+ expect((await status()).steps.figma).toBe("done");
+ });
+
+ it("caches the machine state so a poll does not repeat the host check", async () => {
+ const { status, hostCalls } = await setup({ hosts: [{ name: "box" }] });
+ await status();
+ await status();
+ expect(hostCalls.filter((call) => call.method === "state")).toHaveLength(1);
+ });
+
+ it("starts a sign-in on the connected machine and proxies completion", async () => {
+ const { harness, hostCalls, status } = await setup({ hosts: [{ id: "h1", name: "box" }] });
+ expect(await harness.callRpc("figmaSignIn", null)).toEqual({ url: "https://www.figma.com/oauth/mcp?response_type=code", port: 53280 });
+ expect(hostCalls[0]).toEqual({ method: "start", input: null, hostId: "h1" });
+ expect((await status()).figma.pending).toBe(true);
+ expect(await harness.callRpc("figmaComplete", { url: "http://localhost:53280/callback?code=c&state=s" })).toEqual({ ok: true, message: null });
+ expect(hostCalls.find((call) => call.method === "complete")).toMatchObject({ hostId: "h1", input: { url: "http://localhost:53280/callback?code=c&state=s" } });
+ expect(await harness.callRpc("figmaCancel", null)).toEqual({ ok: true });
+ });
+
+ it("passes a rejected callback back to the page", async () => {
+ const { harness } = await setup({ hosts: [{ name: "box" }], figmaComplete: { ok: false, message: "The callback URL has no code in it." } });
+ expect(await harness.callRpc("figmaComplete", { url: "http://localhost:53280/callback" })).toEqual({ ok: false, message: "The callback URL has no code in it." });
+ });
+
+ it("fails the sign-in when no machine is connected", async () => {
+ const { harness } = await setup();
+ await expect(harness.callRpc("figmaSignIn", null)).rejects.toThrow(/No machine/u);
+ });
+});
+
describe("machine environment seeding", () => {
it("copies FIREWORKS_API_KEY from the server environment to every machine", async () => {
const { setVariables } = await setup({ env: { FIREWORKS_API_KEY: "fw-secret" } });
diff --git a/plugins/team-setup/server.ts b/plugins/team-setup/server.ts
index ede55ee6..3ee460fd 100644
--- a/plugins/team-setup/server.ts
+++ b/plugins/team-setup/server.ts
@@ -27,6 +27,7 @@ import {
type GhProcess,
type GhRunner,
} from "./gh.js";
+import { figmaHostContract, type FigmaHostState } from "./figma-contract.js";
export const ACCOUNT_POOL_ID = "account-pool";
export const DEVBOX_ID = "devbox-provider";
@@ -50,6 +51,15 @@ const PROMPT_TIMEOUT_MS = 20_000;
const GH_TIMEOUT_MS = 15_000;
const IDENTITY_TTL_MS = 60_000;
+// The Figma step reads its state from Claude Code on the machine, and that
+// check may connect to Figma to answer. Bound the call and cache the answer so
+// a ten-second status poll does not repeat it.
+const FIGMA_STATE_TTL_MS = 60_000;
+const FIGMA_STATE_TIMEOUT_MS = 15_000;
+const FIGMA_START_TIMEOUT_MS = 90_000;
+const FIGMA_COMPLETE_TIMEOUT_MS = 60_000;
+const FIGMA_CANCEL_TIMEOUT_MS = 10_000;
+
// "optional" is a step the developer may do but does not have to; like
// "unavailable" it never blocks completion.
const stepStateSchema = z.enum(["done", "todo", "optional", "unavailable"]);
@@ -66,6 +76,16 @@ const accountRowSchema = z.object({
const githubStatusSchema = z.enum(["logged in", "not logged in", "overridden", "disabled", "unknown"]);
const pendingLoginSchema = z.object({ code: z.string(), url: z.string(), expiresAt: z.number() });
+const figmaStatusSchema = z.object({
+ available: z.boolean(),
+ message: z.string().nullable(),
+ machine: z.string().nullable(),
+ claude: z.boolean(),
+ configured: z.boolean(),
+ authenticated: z.boolean(),
+ pending: z.boolean(),
+ url: z.string().nullable(),
+});
export const rpcContract = defineRpcContract({
status: {
@@ -101,7 +121,8 @@ export const rpcContract = defineRpcContract({
organization: z.string().nullable(),
}),
machines: z.object({ names: z.array(z.string()) }),
- steps: z.object({ ai: stepStateSchema, github: stepStateSchema, devbox: stepStateSchema, linear: stepStateSchema, machine: stepStateSchema }),
+ figma: figmaStatusSchema,
+ steps: z.object({ ai: stepStateSchema, github: stepStateSchema, devbox: stepStateSchema, linear: stepStateSchema, figma: stepStateSchema, machine: stepStateSchema }),
complete: z.boolean(),
}),
},
@@ -111,6 +132,15 @@ export const rpcContract = defineRpcContract({
githubSignIn: { input: z.null(), output: pendingLoginSchema },
githubCancel: { input: z.null(), output: z.object({ ok: z.boolean() }) },
githubSignOut: { input: z.null(), output: z.object({ ok: z.boolean() }) },
+ // Figma: Claude Code's OAuth on the machine. The step shows the
+ // authorization URL, the developer pastes the dead localhost callback back,
+ // and the plugin replays it against Claude Code's own loopback listener.
+ figmaSignIn: { input: z.null(), output: z.object({ url: z.string(), port: z.number().int() }) },
+ figmaComplete: {
+ input: z.object({ url: z.string().trim().min(1) }).strict(),
+ output: z.object({ ok: z.boolean(), message: z.string().nullable() }),
+ },
+ figmaCancel: { input: z.null(), output: z.object({ ok: z.boolean() }) },
// Claude: Account Pool's browser sign-in. Open the URL, paste the code
// from its final page back here.
claudeSignIn: { input: z.null(), output: z.object({ sessionId: z.string(), url: z.string() }) },
@@ -379,6 +409,40 @@ export function createTeamSetupPlugin(deps: TeamSetupDeps): (bb: BbPluginApi) =>
});
}
+ // ---- Figma ------------------------------------------------------------
+
+ // The step acts on the machine that runs Claude Code, through this
+ // plugin's own host entry. The state is cached because reading it may
+ // connect to Figma; it is dropped when a sign-in starts or finishes.
+ const figmaHost = bb.hosts.experimental_client({ contract: figmaHostContract });
+ let figmaCache: { hostId: string; at: number; state: FigmaHostState } | null = null;
+ let figmaPending: { hostId: string; url: string; port: number } | null = null;
+
+ async function primaryMachine(): Promise<{ id: string; name: string } | null> {
+ const hosts = await bb.sdk.hosts.list();
+ const connected = hosts.find((host) => host.status === "connected");
+ return connected === undefined ? null : { id: connected.id, name: connected.name };
+ }
+
+ async function machineFigmaState(machine: { id: string; name: string }): Promise {
+ if (figmaCache !== null && figmaCache.hostId === machine.id && deps.now() - figmaCache.at < FIGMA_STATE_TTL_MS) return figmaCache.state;
+ try {
+ const state = await figmaHost.call("state", null, { hostId: machine.id, timeoutMs: FIGMA_STATE_TIMEOUT_MS });
+ if (!state.pending) figmaCache = { hostId: machine.id, at: deps.now(), state };
+ return state;
+ } catch (error) {
+ if (figmaCache !== null && figmaCache.hostId === machine.id) return figmaCache.state;
+ return {
+ claude: true,
+ configured: false,
+ authenticated: false,
+ pending: false,
+ url: null,
+ message: `Could not read the Figma setup on ${machine.name}: ${errorMessage(error)}`,
+ };
+ }
+ }
+
// ---- the checklist ----------------------------------------------------
bb.rpc.register(rpcContract, {
@@ -389,13 +453,14 @@ export function createTeamSetupPlugin(deps: TeamSetupDeps): (bb: BbPluginApi) =>
pluginState(LINEAR_ID),
githubStatus(),
bb.sdk.hosts.list().then(
- (list) => list.map((h) => h.name),
+ (list) => list,
(error: unknown) => {
bb.log.warn(`could not list machines: ${errorMessage(error)}`);
- return [] as string[];
+ return [] as Array<{ id: string; name: string; status: string }>;
},
),
]);
+ const machineNames = hosts.map((h) => h.name);
const ai = { ...poolState, routing: { claude: false, codex: false }, accounts: [] as z.infer[] };
if (poolState.available) {
@@ -436,6 +501,34 @@ export function createTeamSetupPlugin(deps: TeamSetupDeps): (bb: BbPluginApi) =>
}
const aiReady = ai.accounts.some((a) => a.enabled && ai.routing[a.provider]);
+ // The Figma step runs on the machine that runs Claude Code, so it can
+ // only be offered while one is connected and only be acted on while
+ // `claude` is installed there. It is optional until it is configured.
+ const machine = hosts.find((h) => h.status === "connected") ?? null;
+ const figma = {
+ available: machine !== null,
+ message: machine === null ? "No machine is connected." : (null as string | null),
+ machine: machine?.name ?? null,
+ claude: false,
+ configured: false,
+ authenticated: false,
+ pending: figmaPending !== null,
+ url: figmaPending?.url ?? (null as string | null),
+ };
+ if (machine !== null) {
+ const state = await machineFigmaState(machine);
+ figma.claude = state.claude;
+ figma.configured = state.configured;
+ figma.authenticated = state.authenticated;
+ figma.pending = state.pending || figmaPending !== null;
+ figma.url = state.url ?? figmaPending?.url ?? null;
+ if (!state.claude) {
+ figma.available = false;
+ figma.message = state.message ?? `claude is not installed on ${machine.name}.`;
+ } else if (state.message !== null) {
+ figma.message = state.message;
+ }
+ }
const steps = {
ai: !ai.available ? "unavailable" : aiReady ? "done" : "todo",
github:
@@ -449,6 +542,9 @@ export function createTeamSetupPlugin(deps: TeamSetupDeps): (bb: BbPluginApi) =>
// cannot connect, and that is not the developer's to-do. Even when
// it can, Linear is optional: not connecting it is not incomplete.
linear: !linear.available || !linear.configured ? "unavailable" : linear.connected ? "done" : "optional",
+ // Figma is optional while it is not configured; once it is, or while
+ // a sign-in waits for its callback, finishing it is a to-do.
+ figma: !figma.available ? "unavailable" : figma.authenticated ? "done" : figma.configured || figma.pending ? "todo" : "optional",
machine: hosts.length > 0 ? "done" : "todo",
} as const;
return {
@@ -456,7 +552,8 @@ export function createTeamSetupPlugin(deps: TeamSetupDeps): (bb: BbPluginApi) =>
github,
devbox,
linear,
- machines: { names: hosts },
+ machines: { names: machineNames },
+ figma,
steps,
complete: Object.values(steps).every((s) => s !== "todo"),
};
@@ -480,6 +577,40 @@ export function createTeamSetupPlugin(deps: TeamSetupDeps): (bb: BbPluginApi) =>
return { ok: true };
},
+ async figmaSignIn() {
+ const machine = await primaryMachine();
+ if (machine === null) throw new Error("No machine is connected. Create one first.");
+ const started = await figmaHost.call("start", null, { hostId: machine.id, timeoutMs: FIGMA_START_TIMEOUT_MS });
+ figmaPending = { hostId: machine.id, url: started.url, port: started.port };
+ figmaCache = null;
+ bb.realtime.publish(CHANGED, { figma: "started" });
+ return { url: started.url, port: started.port };
+ },
+ async figmaComplete({ url }) {
+ const hostId = figmaPending?.hostId ?? (await primaryMachine())?.id;
+ if (hostId === undefined) throw new Error("No machine is connected.");
+ const result = await figmaHost.call("complete", { url }, { hostId, timeoutMs: FIGMA_COMPLETE_TIMEOUT_MS });
+ if (result.ok) {
+ figmaPending = null;
+ figmaCache = null;
+ bb.realtime.publish(CHANGED, { figma: "signed in" });
+ }
+ return result;
+ },
+ async figmaCancel() {
+ const hostId = figmaPending?.hostId ?? (await primaryMachine())?.id;
+ if (hostId !== undefined) {
+ try {
+ await figmaHost.call("cancel", null, { hostId, timeoutMs: FIGMA_CANCEL_TIMEOUT_MS });
+ } catch (error) {
+ bb.log.warn(`could not cancel the Figma sign-in: ${errorMessage(error)}`);
+ }
+ }
+ figmaPending = null;
+ figmaCache = null;
+ return { ok: true };
+ },
+
async claudeSignIn() {
const started = await call(ACCOUNT_POOL_ID, "login.start", null, poolLoginStartSchema);
return { sessionId: started.sessionId, url: started.authorizeUrl };