Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

feat: dashboard tabs preview (#266)

luigiagentc7b444d74e46
diff --git a/cmd/pinchtab/cmd_server.go b/cmd/pinchtab/cmd_server.go
index 1689c2f5..2ee00b57 100644
--- a/cmd/pinchtab/cmd_server.go
+++ b/cmd/pinchtab/cmd_server.go
@@ -8,7 +8,7 @@ import (
var serverCmd = &cobra.Command{
Use: "server",
- Short: "Start full server",
+ Short: "Start server",
Run: func(cmd *cobra.Command, args []string) {
maybeRunWizard()
cfg := config.Load()
diff --git a/dashboard/src/components/molecules/InstanceCard.tsx b/dashboard/src/components/instances/InstanceCard.tsx
similarity index 100%
rename from dashboard/src/components/molecules/InstanceCard.tsx
rename to dashboard/src/components/instances/InstanceCard.tsx
diff --git a/dashboard/src/components/molecules/InstanceListItem.test.tsx b/dashboard/src/components/instances/InstanceListItem.test.tsx
similarity index 100%
rename from dashboard/src/components/molecules/InstanceListItem.test.tsx
rename to dashboard/src/components/instances/InstanceListItem.test.tsx
diff --git a/dashboard/src/components/molecules/InstanceListItem.tsx b/dashboard/src/components/instances/InstanceListItem.tsx
similarity index 100%
rename from dashboard/src/components/molecules/InstanceListItem.tsx
rename to dashboard/src/components/instances/InstanceListItem.tsx
diff --git a/dashboard/src/components/molecules/CreateProfileModal.test.tsx b/dashboard/src/components/molecules/CreateProfileModal.test.tsx
new file mode 100644
index 00000000..3ecbda80
--- /dev/null
+++ b/dashboard/src/components/molecules/CreateProfileModal.test.tsx
@@ -0,0 +1,91 @@
+import { render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import CreateProfileModal from "./CreateProfileModal";
+
+vi.mock("../../services/api", () => ({
+ createProfile: vi.fn(),
+}));
+
+describe("CreateProfileModal", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("submits the local form and returns the created profile key", async () => {
+ const { createProfile } = await import("../../services/api");
+ const onClose = vi.fn();
+ const onCreated = vi.fn();
+
+ vi.mocked(createProfile).mockResolvedValue({
+ status: "ok",
+ id: "prof_work",
+ name: "work",
+ });
+
+ render(
+ <CreateProfileModal
+ open={true}
+ onClose={onClose}
+ onCreated={onCreated}
+ />,
+ );
+
+ await userEvent.type(
+ screen.getByPlaceholderText("e.g. personal, work, scraping"),
+ "work",
+ );
+ await userEvent.type(
+ screen.getByPlaceholderText(
+ "e.g. I need to access Gmail for the team account",
+ ),
+ "Team account access",
+ );
+
+ await userEvent.click(screen.getByRole("button", { name: "Create" }));
+
+ await waitFor(() => {
+ expect(createProfile).toHaveBeenCalledWith({
+ name: "work",
+ useWhen: "Team account access",
+ });
+ });
+ expect(onClose).toHaveBeenCalledTimes(1);
+ expect(onCreated).toHaveBeenCalledWith("prof_work");
+ });
+
+ it("resets its local fields when closed and reopened", async () => {
+ const { rerender } = render(
+ <CreateProfileModal
+ open={true}
+ onClose={() => {}}
+ onCreated={() => {}}
+ />,
+ );
+
+ const nameInput = screen.getByPlaceholderText(
+ "e.g. personal, work, scraping",
+ );
+ await userEvent.type(nameInput, "scratch");
+
+ rerender(
+ <CreateProfileModal
+ open={false}
+ onClose={() => {}}
+ onCreated={() => {}}
+ />,
+ );
+
+ rerender(
+ <CreateProfileModal
+ open={true}
+ onClose={() => {}}
+ onCreated={() => {}}
+ />,
+ );
+
+ expect(
+ screen.getByPlaceholderText("e.g. personal, work, scraping"),
+ ).toHaveValue("");
+ });
+});
diff --git a/dashboard/src/components/molecules/CreateProfileModal.tsx b/dashboard/src/components/molecules/CreateProfileModal.tsx
new file mode 100644
index 00000000..055b610d
--- /dev/null
+++ b/dashboard/src/components/molecules/CreateProfileModal.tsx
@@ -0,0 +1,98 @@
+import { useEffect, useState } from "react";
+import { Button, Input, Modal } from "../atoms";
+import * as api from "../../services/api";
+
+interface Props {
+ open: boolean;
+ onClose: () => void;
+ onCreated: (preferredProfileKey: string) => void | Promise<void>;
+}
+
+export default function CreateProfileModal({
+ open,
+ onClose,
+ onCreated,
+}: Props) {
+ const [createName, setCreateName] = useState("");
+ const [createUseWhen, setCreateUseWhen] = useState("");
+ const [createSource, setCreateSource] = useState("");
+ const [createLoading, setCreateLoading] = useState(false);
+
+ useEffect(() => {
+ if (open) {
+ return;
+ }
+
+ setCreateName("");
+ setCreateUseWhen("");
+ setCreateSource("");
+ setCreateLoading(false);
+ }, [open]);
+
+ const handleCreate = async () => {
+ if (!createName.trim() || createLoading) return;
+
+ setCreateLoading(true);
+ try {
+ const created = await api.createProfile({
+ name: createName.trim(),
+ useWhen: createUseWhen.trim() || undefined,
+ });
+ onClose();
+ await onCreated(created.id || created.name);
+ } catch (e) {
+ console.error("Failed to create profile", e);
+ } finally {
+ setCreateLoading(false);
+ }
+ };
+
+ return (
+ <Modal
+ open={open}
+ onClose={onClose}
+ title="πŸ“ New Profile"
+ wide
+ actions={
+ <>
+ <Button
+ variant="secondary"
+ disabled={createLoading}
+ onClick={onClose}
+ >
+ Cancel
+ </Button>
+ <Button
+ variant="primary"
+ onClick={handleCreate}
+ disabled={!createName.trim()}
+ loading={createLoading}
+ >
+ Create
+ </Button>
+ </>
+ }
+ >
+ <div className="flex flex-col gap-4">
+ <Input
+ label="Name"
+ placeholder="e.g. personal, work, scraping"
+ value={createName}
+ onChange={(e) => setCreateName(e.target.value)}
+ />
+ <Input
+ label="Use this profile when (helps agents pick the right profile)"
+ placeholder="e.g. I need to access Gmail for the team account"
+ value={createUseWhen}
+ onChange={(e) => setCreateUseWhen(e.target.value)}
+ />
+ <Input
+ label="Import from (optional β€” Chrome user data path)"
+ placeholder="e.g. /Users/you/Library/Application Support/Google/Chrome"
+ value={createSource}
+ onChange={(e) => setCreateSource(e.target.value)}
+ />
+ </div>
+ </Modal>
+ );
+}
diff --git a/dashboard/src/components/molecules/EmptyView.tsx b/dashboard/src/components/molecules/EmptyView.tsx
new file mode 100644
index 00000000..c2e2f539
--- /dev/null
+++ b/dashboard/src/components/molecules/EmptyView.tsx
@@ -0,0 +1,16 @@
+interface Props {
+ message: string;
+ icon?: string;
+ className?: string;
+}
+
+export default function EmptyView({ message, icon, className = "" }: Props) {
+ return (
+ <div
+ className={`flex h-full flex-col items-center justify-center p-6 text-center text-sm text-text-muted ${className}`}
+ >
+ {icon && <div className="mb-3 text-3xl opacity-50">{icon}</div>}
+ <p className="max-w-xs">{message}</p>
+ </div>
+ );
+}
diff --git a/dashboard/src/components/molecules/ProfileDetailsModal.tsx b/dashboard/src/components/molecules/ProfileDetailsModal.tsx
deleted file mode 100644
index e64ca1bb..00000000
--- a/dashboard/src/components/molecules/ProfileDetailsModal.tsx
+++ /dev/null
@@ -1,318 +0,0 @@
-import { useState, useEffect, useCallback } from "react";
-import { Modal, Button, Input } from "../atoms";
-import ScreencastTile from "./ScreencastTile";
-import TabItem from "./TabItem";
-import type { Profile, Instance, InstanceTab } from "../../generated/types";
-import * as api from "../../services/api";
-
-interface Props {
- profile: Profile | null;
- instance?: Instance;
- onClose: () => void;
- onSave?: (name: string, useWhen: string) => void;
- onDelete?: () => void;
-}
-
-type TabId = "profile" | "live" | "logs";
-
-function InfoRow({ label, value }: { label: string; value: string }) {
- return (
- <div className="flex justify-between py-1 text-sm">
- <span className="text-text-muted">{label}</span>
- <span className="text-text-primary">{value}</span>
- </div>
- );
-}
-
-export default function ProfileDetailsModal({
- profile,
- instance,
- onClose,
- onSave,
- onDelete,
-}: Props) {
- const [activeTab, setActiveTab] = useState<TabId>("profile");
- const [name, setName] = useState("");
- const [useWhen, setUseWhen] = useState("");
- const [tabs, setTabs] = useState<InstanceTab[]>([]);
- const [logs, setLogs] = useState("");
- const [copyFeedback, setCopyFeedback] = useState("");
-
- const isRunning = instance?.status === "running";
-
- // Initialize form values when profile changes
- useEffect(() => {
- if (profile) {
- setName(profile.name);
- setUseWhen(profile.useWhen || "");
- }
- }, [profile]);
-
- // Load live data when switching to live/logs tab
- const loadLiveData = useCallback(async () => {
- if (!instance?.id) return;
-
- try {
- const allTabs = await api.fetchAllTabs().catch(() => []);
- // Filter tabs for this instance
- const instanceTabs = Array.isArray(allTabs)
- ? allTabs.filter((t) => t.instanceId === instance.id)
- : [];
- setTabs(instanceTabs);
- const instanceLogs = await api
- .fetchInstanceLogs(instance.id)
- .catch(() => "");
- setLogs(instanceLogs);
- } catch (e) {
- console.error("Failed to load live data", e);
- }
- }, [instance]);
-
- useEffect(() => {
- if (activeTab === "live" || activeTab === "logs") {
- loadLiveData();
- }
- }, [activeTab, loadLiveData]);
-
- const handleCopyId = async () => {
- if (!profile?.id) return;
- try {
- await navigator.clipboard.writeText(profile.id);
- setCopyFeedback("Copied!");
- setTimeout(() => setCopyFeedback(""), 2000);
- } catch {
- setCopyFeedback("Failed");
- setTimeout(() => setCopyFeedback(""), 2000);
- }
- };
-
- const handleSave = () => {
- onSave?.(name, useWhen);
- };
-
- if (!profile) return null;
-
- const tabClasses = (id: TabId) =>
- `flex-1 py-2 text-sm font-medium border-b-2 transition-colors ${
- activeTab === id
- ? "border-primary text-text-primary"
- : "border-transparent text-text-muted hover:text-text-secondary"
- }`;
-
- return (
- <Modal
- open={!!profile}
- onClose={onClose}
- title={profile.name}
- wide
- actions={
- <div className="flex w-full items-center justify-between">
- <Button variant="danger" onClick={onDelete}>
- Delete
- </Button>
- <div className="flex gap-2">
- <Button variant="primary" onClick={handleSave}>
- Save
- </Button>
- <Button variant="secondary" onClick={onClose}>
- Close
- </Button>
- </div>
- </div>
- }
- >
- {/* Tabs */}
- <div className="-mx-4 -mt-2 mb-4 flex border-b border-border-subtle px-4">
- <button
- className={tabClasses("profile")}
- onClick={() => setActiveTab("profile")}
- >
- Profile
- </button>
- <button
- className={tabClasses("live")}
- onClick={() => setActiveTab("live")}
- >
- Live
- </button>
- <button
- className={tabClasses("logs")}
- onClick={() => setActiveTab("logs")}
- >
- Logs
- </button>
- </div>
-
- {/* Tab Content */}
- <div className="min-h-[400px]">
- {activeTab === "profile" && (
- <div className="flex flex-col gap-4">
- {/* Profile ID */}
- <div>
- <label className="mb-1 block text-xs text-text-muted">
- Profile ID
- </label>
- <div className="flex gap-2">
- <input
- readOnly
- value={profile.id || "β€”"}
- className="flex-1 rounded border border-border-subtle bg-bg-elevated px-3 py-2 font-mono text-xs text-text-secondary"
- />
- <Button size="sm" variant="secondary" onClick={handleCopyId}>
- {copyFeedback || "Copy"}
- </Button>
- </div>
- </div>
-
- {/* Name */}
- <Input
- label="Name"
- value={name}
- onChange={(e) => setName(e.target.value)}
- />
-
- {/* Use When */}
- <div>
- <label className="mb-1 block text-xs text-text-muted">
- Use this profile when
- </label>
- <textarea
- value={useWhen}
- onChange={(e) => setUseWhen(e.target.value)}
- className="min-h-[80px] w-full resize-y rounded border border-border-subtle bg-bg-elevated px-3 py-2 text-sm text-text-primary"
- />
- </div>
-
- {/* Status */}
- <div className="rounded border border-border-subtle bg-bg-elevated p-3">
- <h4 className="mb-2 text-xs font-semibold uppercase tracking-wide text-text-muted">
- Status
- </h4>
- <div className="space-y-1">
- <InfoRow label="State" value={instance?.status || "stopped"} />
- <InfoRow label="Port" value={instance?.port || "β€”"} />
- <InfoRow
- label="Size"
- value={
- profile.sizeMB ? `${profile.sizeMB.toFixed(0)} MB` : "β€”"
- }
- />
- <InfoRow label="Source" value={profile.source || "β€”"} />
- {profile.chromeProfileName && (
- <InfoRow label="Chrome" value={profile.chromeProfileName} />
- )}
- {(profile.accountEmail || profile.accountName) && (
- <InfoRow
- label="Account"
- value={profile.accountEmail || profile.accountName || ""}
- />
- )}
- </div>
- </div>
-
- {/* Path */}
- {profile.path && (
- <div className="rounded border border-border-subtle bg-bg-elevated p-3">
- <h4 className="mb-1 text-xs font-semibold uppercase tracking-wide text-text-muted">
- Path
- </h4>
- <code
- className={`text-xs ${profile.pathExists ? "text-text-secondary" : "text-destructive"}`}
- >
- {profile.path}
- {!profile.pathExists && " (not found)"}
- </code>
- </div>
- )}
- </div>
- )}
-
- {activeTab === "live" && (
- <div>
- {isRunning && instance ? (
- <div>
- <div className="mb-3 flex items-center justify-between">
- <span className="text-sm text-text-muted">
- {tabs.length} tab(s)
- </span>
- <Button size="sm" variant="secondary" onClick={loadLiveData}>
- Refresh
- </Button>
- </div>
- {tabs.length === 0 ? (
- <div className="flex h-[300px] items-center justify-center text-sm text-text-muted">
- No tabs open
- </div>
- ) : (
- <div className="grid gap-3 sm:grid-cols-2">
- {tabs.map((tab) => (
- <ScreencastTile
- key={tab.id}
- instanceId={instance.id}
- tabId={tab.id}
- label={tab.title?.slice(0, 20) || tab.id.slice(0, 8)}
- url={tab.url}
- />
- ))}
- </div>
- )}
- </div>
- ) : (
- <div className="flex h-[300px] items-center justify-center text-sm text-text-muted">
- Instance not running. Start the profile to see live view.
- </div>
- )}
- </div>
- )}
-
- {activeTab === "logs" && (
- <div className="space-y-4">
- {/* Tabs */}
- <div>
- <h4 className="mb-2 text-xs font-semibold uppercase tracking-wide text-text-muted">
- Tabs ({tabs.length})
- </h4>
- {tabs.length === 0 ? (
- <p className="text-sm text-text-muted">
- {isRunning ? "No tabs open." : "Instance not running."}
- </p>
- ) : (
- <div className="space-y-1">
- {tabs.map((tab) => (
- <TabItem key={tab.id} tab={tab} compact />
- ))}
- </div>
- )}
- </div>
-
- {/* Agents */}
- <div>
- <h4 className="mb-2 text-xs font-semibold uppercase tracking-wide text-text-muted">
- Agents
- </h4>
- <p className="text-sm text-text-muted">
- Agent registry is not exposed by the current backend.
- </p>
- </div>
-
- {/* Logs placeholder */}
- <div>
- <h4 className="mb-2 text-xs font-semibold uppercase tracking-wide text-text-muted">
- Logs
- </h4>
- {logs ? (
- <pre className="max-h-[200px] overflow-auto rounded bg-bg-elevated p-3 font-mono text-xs text-text-secondary">
- {logs}
- </pre>
- ) : (
- <p className="text-sm text-text-muted">
- No instance logs available.
- </p>
- )}
- </div>
- </div>
- )}
- </div>
- </Modal>
- );
-}
diff --git a/dashboard/src/components/molecules/ProfileDetailsPanel.tsx b/dashboard/src/components/molecules/ProfileDetailsPanel.tsx
deleted file mode 100644
index 0132b948..00000000
--- a/dashboard/src/components/molecules/ProfileDetailsPanel.tsx
+++ /dev/null
@@ -1,417 +0,0 @@
-import { useState, useEffect, useCallback } from "react";
-import { Button, Input, Badge } from "../atoms";
-import ScreencastTile from "./ScreencastTile";
-import TabItem from "./TabItem";
-import type { Profile, Instance, InstanceTab } from "../../generated/types";
-import * as api from "../../services/api";
-
-interface Props {
- profile: Profile | null;
- instance?: Instance;
- onLaunch: () => void;
- onStop?: () => void;
- onSave?: (name: string, useWhen: string) => void;
- onDelete?: () => void;
-}
-
-type TabId = "profile" | "live" | "tabs" | "agents" | "logs";
-
-function MetaBlock({
- label,
- children,
-}: {
- label: string;
- children: React.ReactNode;
-}) {
- return (
- <div className="rounded-xl border border-border-subtle bg-black/10 p-4">
- <div className="dashboard-section-title mb-2 text-[0.68rem]">{label}</div>
- {children}
- </div>
- );
-}
-
-export default function ProfileDetailsPanel({
- profile,
- instance,
- onLaunch,
- onStop,
- onSave,
- onDelete,
-}: Props) {
- const [activeTab, setActiveTab] = useState<TabId>("profile");
- const [name, setName] = useState("");
- const [useWhen, setUseWhen] = useState("");
- const [tabs, setTabs] = useState<InstanceTab[]>([]);
- const [logs, setLogs] = useState("");
- const [copyFeedback, setCopyFeedback] = useState("");
-
- const isRunning = instance?.status === "running";
-
- useEffect(() => {
- if (profile) {
- setName(profile.name);
- setUseWhen(profile.useWhen || "");
- setCopyFeedback("");
- } else {
- setName("");
- setUseWhen("");
- setTabs([]);
- setLogs("");
- }
- }, [profile]);
-
- const loadLiveData = useCallback(async () => {
- if (!instance?.id) {
- setTabs([]);
- setLogs("");
- return;
- }
-
- try {
- const [instanceTabs, instanceLogs] = await Promise.all([
- api.fetchInstanceTabs(instance.id).catch(() => []),
- api.fetchInstanceLogs(instance.id).catch(() => ""),
- ]);
- setTabs(instanceTabs);
- setLogs(instanceLogs);
- } catch (e) {
- console.error("Failed to load live data", e);
- }
- }, [instance]);
-
- useEffect(() => {
- if (activeTab === "live" || activeTab === "tabs" || activeTab === "logs") {
- loadLiveData();
- }
- }, [activeTab, loadLiveData]);
-
- useEffect(() => {
- if (activeTab !== "logs" || !instance?.id) {
- return;
- }
-
- return api.subscribeToInstanceLogs(instance.id, {
- onLogs: (nextLogs) => setLogs(nextLogs),
- });
- }, [activeTab, instance?.id]);
-
- const handleCopyId = async () => {
- if (!profile?.id) return;
- try {
- await navigator.clipboard.writeText(profile.id);
- setCopyFeedback("Copied");
- setTimeout(() => setCopyFeedback(""), 2000);
- } catch {
- setCopyFeedback("Failed");
- setTimeout(() => setCopyFeedback(""), 2000);
- }
- };
-
- const handleSave = () => {
- onSave?.(name, useWhen);
- };
-
- const tabClasses = (id: TabId) =>
- `rounded-sm px-3 py-2 text-sm font-medium transition-colors ${
- activeTab === id
- ? "bg-bg-hover text-text-primary"
- : "text-text-muted hover:bg-bg-hover hover:text-text-secondary"
- }`;
-
- if (!profile) {
- return (
- <div className="dashboard-panel flex h-full min-h-[28rem] items-center justify-center p-6 text-center text-sm text-text-muted">
- Select a profile to inspect its instance, live tabs, and logs.
- </div>
- );
- }
-
- const statusVariant =
- instance?.status === "running"
- ? "success"
- : instance?.status === "error"
- ? "danger"
- : "default";
- const statusLabel =
- instance?.status === "running"
- ? `Running on :${instance.port}`
- : instance?.status === "error"
- ? "Error"
- : "Stopped";
- const accountText = profile.accountEmail || profile.accountName || "";
- const sizeText = profile.sizeMB ? `${profile.sizeMB.toFixed(0)} MB` : "β€”";
- const browserType = instance?.attached
- ? "Attached via CDP"
- : instance?.headless
- ? "Headless"
- : "Headed";
- const headerMeta = [
- profile.chromeProfileName ? `Chrome ${profile.chromeProfileName}` : null,
- instance?.attached ? "CDP attached" : null,
- ].filter(Boolean);
- const hasChanges =
- name.trim() !== profile.name || useWhen !== (profile.useWhen || "");
-
- return (
- <div className="dashboard-panel flex h-full min-h-[28rem] flex-col overflow-hidden">
- <div className="border-b border-border-subtle px-4 py-3 lg:px-5">
- <div className="flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between">
- <div className="min-w-0">
- <div className="flex flex-wrap items-center gap-3">
- <h2 className="truncate text-lg font-semibold text-text-primary">
- {profile.name}
- </h2>
- <Badge variant={statusVariant}>{statusLabel}</Badge>
- {headerMeta.length > 0 && (
- <div className="text-sm text-text-muted">
- {headerMeta.join(" Β· ")}
- </div>
- )}
- </div>
- {profile.useWhen?.trim() && (
- <p className="mt-1 text-sm text-text-muted">{profile.useWhen}</p>
- )}
- </div>
- <div className="flex shrink-0 flex-wrap gap-2">
- {profile.id && (
- <Button size="sm" variant="secondary" onClick={handleCopyId}>
- {copyFeedback || "Copy ID"}
- </Button>
- )}
- <Button size="sm" variant="secondary" onClick={onDelete}>
- Delete
- </Button>
- <Button
- size="sm"
- variant="primary"
- onClick={handleSave}
- disabled={!name.trim() || !hasChanges}
- >
- Save
- </Button>
- {isRunning ? (
- <Button size="sm" variant="danger" onClick={onStop}>
- Stop
- </Button>
- ) : (
- <Button size="sm" variant="primary" onClick={onLaunch}>
- Start
- </Button>
- )}
- </div>
- </div>
- </div>
-
- <div className="border-b border-border-subtle px-4 py-3 lg:px-5">
- <div className="flex flex-wrap gap-2">
- <button
- type="button"
- className={tabClasses("profile")}
- onClick={() => setActiveTab("profile")}
- >
- Profile
- </button>
- <button
- type="button"
- className={tabClasses("live")}
- onClick={() => setActiveTab("live")}
- >
- Live
- </button>
- <button
- type="button"
- className={tabClasses("tabs")}
- onClick={() => setActiveTab("tabs")}
- >
- Tabs ({tabs.length})
- </button>
- <button
- type="button"
- className={tabClasses("logs")}
- onClick={() => setActiveTab("logs")}
- >
- Logs
- </button>
- </div>
- </div>
-
- <div className="min-h-0 flex-1 overflow-hidden px-4 py-4 lg:px-5">
- {activeTab === "profile" && (
- <div className="h-full overflow-auto">
- <div className="grid gap-4 xl:grid-cols-2">
- <div className="space-y-4">
- <Input
- label="Name"
- value={name}
- onChange={(e) => setName(e.target.value)}
- />
-
- <div>
- <label className="dashboard-section-title mb-1 block text-[0.68rem]">
- Use this profile when
- </label>
- <textarea
- value={useWhen}
- onChange={(e) => setUseWhen(e.target.value)}
- className="min-h-[180px] w-full resize-y rounded border border-border-subtle bg-bg-elevated px-3 py-2 text-sm text-text-primary"
- />
- </div>
- </div>
-
- <MetaBlock label="Profile panel">
- <div className="space-y-3 text-sm text-text-secondary">
- <div className="flex items-center justify-between gap-3">
- <span className="dashboard-section-title text-[0.68rem]">
- Status
- </span>
- <span className="text-right">
- {instance?.status || "stopped"}
- </span>
- </div>
- {instance?.port && (
- <div className="flex items-center justify-between gap-3">
- <span className="dashboard-section-title text-[0.68rem]">
- Port
- </span>
- <span className="text-right">{instance.port}</span>
- </div>
- )}
- <div className="flex items-center justify-between gap-3">
- <span className="dashboard-section-title text-[0.68rem]">
- Browser
- </span>
- <span className="text-right">{browserType}</span>
- </div>
- <div className="flex items-center justify-between gap-3">
- <span className="dashboard-section-title text-[0.68rem]">
- Size
- </span>
- <span className="text-right">{sizeText}</span>
- </div>
- {accountText && (
- <div className="flex items-center justify-between gap-3">
- <span className="dashboard-section-title text-[0.68rem]">
- Account
- </span>
- <span className="text-right">{accountText}</span>
- </div>
- )}
- {profile.chromeProfileName && (
- <div className="flex items-center justify-between gap-3">
- <span className="dashboard-section-title text-[0.68rem]">
- Identity
- </span>
- <span className="text-right">
- {profile.chromeProfileName}
- </span>
- </div>
- )}
- {instance?.attached && (
- <div className="flex items-center justify-between gap-3">
- <span className="dashboard-section-title text-[0.68rem]">
- Connection
- </span>
- <span className="text-right">CDP attached</span>
- </div>
- )}
- {instance?.cdpUrl && (
- <div>
- <div className="dashboard-section-title mb-1 text-[0.68rem]">
- CDP URL
- </div>
- <code className="dashboard-mono block break-all text-xs text-text-secondary">
- {instance.cdpUrl}
- </code>
- </div>
- )}
- {profile.path && (
- <div>
- <div className="dashboard-section-title mb-1 text-[0.68rem]">
- Path
- </div>
- <code
- className={`dashboard-mono block break-all text-xs ${
- profile.pathExists
- ? "text-text-secondary"
- : "text-destructive"
- }`}
- >
- {profile.path}
- {!profile.pathExists && " (not found)"}
- </code>
- </div>
- )}
- </div>
- </MetaBlock>
- </div>
- </div>
- )}
-
- {activeTab === "live" && (
- <div className="flex h-full min-h-0 flex-col">
- {isRunning && instance ? (
- tabs.length === 0 ? (
- <div className="flex flex-1 items-center justify-center rounded-xl border border-border-subtle bg-black/10 text-sm text-text-muted">
- No tabs open
- </div>
- ) : (
- <div className="min-h-0 flex-1 overflow-auto">
- <div className="flex min-h-full items-center justify-center">
- <div className="grid w-full max-w-6xl gap-3 xl:grid-cols-2">
- {tabs.map((tab) => (
- <ScreencastTile
- key={tab.id}
- instanceId={instance.id}
- tabId={tab.id}
- label={tab.title?.slice(0, 20) || tab.id.slice(0, 8)}
- url={tab.url}
- />
- ))}
- </div>
- </div>
- </div>
- )
- ) : (
- <div className="flex flex-1 items-center justify-center rounded-xl border border-border-subtle bg-black/10 text-sm text-text-muted">
- Instance not running. Start the profile to see live view.
- </div>
- )}
- </div>
- )}
-
- {activeTab === "tabs" && (
- <div className="flex h-full min-h-0 flex-col">
- {tabs.length === 0 ? (
- <div className="flex h-full items-center justify-center rounded-xl border border-border-subtle bg-black/10 px-4 py-6 text-sm text-text-muted">
- {isRunning ? "No tabs open." : "Instance not running."}
- </div>
- ) : (
- <div className="h-full overflow-auto">
- <div className="space-y-1">
- {tabs.map((tab) => (
- <TabItem key={tab.id} tab={tab} compact />
- ))}
- </div>
- </div>
- )}
- </div>
- )}
-
- {activeTab === "logs" && (
- <div className="flex h-full min-h-0 flex-col">
- {logs ? (
- <pre className="h-full overflow-auto rounded-xl border border-border-subtle bg-black/10 p-3 font-mono text-[10px] leading-4 text-text-secondary">
- {logs}
- </pre>
- ) : (
- <div className="flex h-full items-center justify-center rounded-xl border border-border-subtle bg-black/10 px-4 py-6 text-sm text-text-muted">
- No instance logs available.
- </div>
- )}
- </div>
- )}
- </div>
- </div>
- );
-}
diff --git a/dashboard/src/components/molecules/ScreencastTile.tsx b/dashboard/src/components/molecules/ScreencastTile.tsx
deleted file mode 100644
index afb0ddaa..00000000
--- a/dashboard/src/components/molecules/ScreencastTile.tsx
+++ /dev/null
@@ -1,137 +0,0 @@
-import { useEffect, useRef, useState } from "react";
-import { addTokenToUrl } from "../../services/auth";
-
-interface Props {
- instanceId: string;
- tabId: string;
- label: string;
- url: string;
- quality?: number;
- maxWidth?: number;
- fps?: number;
-}
-
-type Status = "connecting" | "streaming" | "error";
-
-export default function ScreencastTile({
- instanceId,
- tabId,
- label,
- url,
- quality = 30,
- maxWidth = 800,
- fps = 1,
-}: Props) {
- const canvasRef = useRef<HTMLCanvasElement>(null);
- const socketRef = useRef<WebSocket | null>(null);
- const [status, setStatus] = useState<Status>("connecting");
- const [fpsDisplay, setFpsDisplay] = useState("β€”");
- const [sizeDisplay, setSizeDisplay] = useState("β€”");
-
- useEffect(() => {
- const canvas = canvasRef.current;
- if (!canvas) return;
-
- const ctx = canvas.getContext("2d");
- if (!ctx) return;
-
- const params = new URLSearchParams({
- tabId,
- quality: String(quality),
- maxWidth: String(maxWidth),
- fps: String(fps),
- });
- const path = addTokenToUrl(
- `/instances/${encodeURIComponent(instanceId)}/proxy/screencast?${params.toString()}`,
- );
- const wsUrl = new URL(path, window.location.origin);
- wsUrl.protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
-
- const socket = new WebSocket(wsUrl.toString());
- socket.binaryType = "arraybuffer";
- socketRef.current = socket;
-
- let frameCount = 0;
- let lastFpsTime = Date.now();
-
- socket.onopen = () => {
- setStatus("streaming");
- };
-
- socket.onmessage = (evt) => {
- const blob = new Blob([evt.data], { type: "image/jpeg" });
- const imgUrl = URL.createObjectURL(blob);
- const img = new Image();
- img.onload = () => {
- canvas.width = img.width;
- canvas.height = img.height;
- ctx.drawImage(img, 0, 0);
- URL.revokeObjectURL(imgUrl);
- };
- img.src = imgUrl;
-
- frameCount++;
- const now = Date.now();
- if (now - lastFpsTime >= 1000) {
- setFpsDisplay(`${frameCount} fps`);
- setSizeDisplay(`${(evt.data.byteLength / 1024).toFixed(0)} KB/frame`);
- frameCount = 0;
- lastFpsTime = now;
- }
- };
-
- socket.onerror = () => {
- setStatus("error");
- };
-
- socket.onclose = () => {
- setStatus("error");
- };
-
- return () => {
- socket.close();
- socketRef.current = null;
- };
- }, [instanceId, tabId, quality, maxWidth, fps]);
-
- const statusColor =
- status === "streaming"
- ? "bg-success"
- : status === "connecting"
- ? "bg-warning"
- : "bg-destructive";
-
- return (
- <div className="overflow-hidden rounded-lg border border-border-subtle bg-bg-elevated">
- {/* Header */}
- <div className="flex items-center justify-between border-b border-border-subtle px-3 py-2">
- <div className="flex items-center gap-2">
- <span className="font-mono text-xs text-text-secondary">{label}</span>
- <div className={`h-2 w-2 rounded-full ${statusColor}`} />
- </div>
- <span className="max-w-50 truncate text-xs text-text-muted">{url}</span>
- </div>
-
- {/* Canvas */}
- <div className="relative aspect-video bg-black">
- <canvas
- ref={canvasRef}
- className="h-full w-full object-contain"
- width={800}
- height={600}
- />
- {status === "error" && (
- <div className="absolute inset-0 flex items-center justify-center bg-black/80 text-sm text-text-muted">
- Connection lost
- </div>
- )}
- </div>
-
- {/* Footer */}
- <div className="flex justify-between border-t border-border-subtle px-3 py-1 text-xs text-text-muted">
- <span>{fpsDisplay}</span>
- <span>{sizeDisplay}</span>
- </div>
- </div>
- );
-}
diff --git a/dashboard/src/components/molecules/StartInstanceModal.test.tsx b/dashboard/src/components/molecules/StartInstanceModal.test.tsx
new file mode 100644
index 00000000..b0e6d1b8
--- /dev/null
+++ b/dashboard/src/components/molecules/StartInstanceModal.test.tsx
@@ -0,0 +1,87 @@
+import { render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import StartInstanceModal from "./StartInstanceModal";
+import { useAppStore } from "../../stores/useAppStore";
+import type { Instance, Profile } from "../../generated/types";
+
+vi.mock("../../services/api", () => ({
+ launchInstance: vi.fn(),
+ fetchInstances: vi.fn(),
+}));
+
+const profile: Profile = {
+ id: "prof_alpha",
+ name: "alpha",
+ created: "2026-03-01T10:00:00Z",
+ lastUsed: "2026-03-05T10:00:00Z",
+ diskUsage: 1024,
+ sizeMB: 12,
+ running: false,
+};
+
+describe("StartInstanceModal", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ useAppStore.setState({ instances: [] });
+ });
+
+ it("builds its own launch command from local form state", async () => {
+ render(
+ <StartInstanceModal open={true} profile={profile} onClose={() => {}} />,
+ );
+
+ const command = document.querySelector("textarea") as HTMLTextAreaElement;
+ expect(command.value).toContain('"profileId":"prof_alpha"');
+ expect(command.value).toContain('"mode":"headed"');
+
+ await userEvent.type(
+ screen.getByPlaceholderText("Auto-select from configured range"),
+ "9988",
+ );
+ await userEvent.click(
+ screen.getByLabelText("Headless (best for Docker/VPS)"),
+ );
+
+ expect(command.value).toContain('"port":"9988"');
+ expect(command.value).not.toContain('"mode":"headed"');
+ });
+
+ it("launches the selected profile and refreshes instances", async () => {
+ const { fetchInstances, launchInstance } =
+ await import("../../services/api");
+ const onClose = vi.fn();
+ const updatedInstances: Instance[] = [
+ {
+ id: "inst_alpha",
+ profileId: "prof_alpha",
+ profileName: "alpha",
+ port: "9988",
+ headless: false,
+ status: "running",
+ startTime: "2026-03-06T10:00:00Z",
+ attached: false,
+ },
+ ];
+
+ vi.mocked(launchInstance).mockResolvedValue({} as never);
+ vi.mocked(fetchInstances).mockResolvedValue(updatedInstances);
+
+ render(
+ <StartInstanceModal open={true} profile={profile} onClose={onClose} />,
+ );
+
+ await userEvent.click(screen.getByRole("button", { name: "Start" }));
+
+ await waitFor(() => {
+ expect(launchInstance).toHaveBeenCalledWith({
+ name: "alpha",
+ mode: "headed",
+ port: undefined,
+ });
+ });
+ expect(fetchInstances).toHaveBeenCalledTimes(1);
+ expect(useAppStore.getState().instances).toEqual(updatedInstances);
+ expect(onClose).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/dashboard/src/components/molecules/StartInstanceModal.tsx b/dashboard/src/components/molecules/StartInstanceModal.tsx
new file mode 100644
index 00000000..acbeb5a2
--- /dev/null
+++ b/dashboard/src/components/molecules/StartInstanceModal.tsx
@@ -0,0 +1,155 @@
+import { useEffect, useMemo, useState } from "react";
+import { Button, Input, Modal } from "../atoms";
+import { useAppStore } from "../../stores/useAppStore";
+import * as api from "../../services/api";
+import type { LaunchInstanceRequest, Profile } from "../../generated/types";
+
+interface Props {
+ open: boolean;
+ profile: Profile | null;
+ onClose: () => void;
+}
+
+export default function StartInstanceModal({ open, profile, onClose }: Props) {
+ const { setInstances } = useAppStore();
+ const [port, setPort] = useState("");
+ const [headless, setHeadless] = useState(false);
+ const [launchError, setLaunchError] = useState("");
+ const [launchLoading, setLaunchLoading] = useState(false);
+ const [copyFeedback, setCopyFeedback] = useState("");
+
+ useEffect(() => {
+ if (open) {
+ setLaunchError("");
+ setCopyFeedback("");
+ return;
+ }
+
+ setPort("");
+ setHeadless(false);
+ setLaunchError("");
+ setLaunchLoading(false);
+ setCopyFeedback("");
+ }, [open, profile?.id, profile?.name]);
+
+ const launchCommand = useMemo(() => {
+ if (!profile) return "";
+
+ const payload: LaunchInstanceRequest = {
+ profileId: profile.id || profile.name,
+ mode: headless ? undefined : "headed",
+ port: port.trim() || undefined,
+ };
+
+ return `curl -X POST http://localhost:9867/instances/start -H "Content-Type: application/json" -d '${JSON.stringify(payload)}'`;
+ }, [headless, port, profile]);
+
+ const handleLaunch = async () => {
+ if (!profile || launchLoading) return;
+
+ setLaunchError("");
+ setLaunchLoading(true);
+
+ try {
+ const payload: LaunchInstanceRequest = {
+ name: profile.name,
+ port: port.trim() || undefined,
+ mode: headless ? undefined : "headed",
+ };
+
+ await api.launchInstance(payload);
+ const updated = await api.fetchInstances();
+ setInstances(updated);
+ onClose();
+ } catch (e) {
+ console.error("Launch failed:", e);
+ const msg = e instanceof Error ? e.message : "Failed to launch instance";
+ setLaunchError(msg);
+ } finally {
+ setLaunchLoading(false);
+ }
+ };
+
+ const handleCopyCommand = async () => {
+ try {
+ await navigator.clipboard.writeText(launchCommand);
+ setCopyFeedback("Copied!");
+ setTimeout(() => setCopyFeedback(""), 2000);
+ } catch {
+ setCopyFeedback("Failed to copy");
+ setTimeout(() => setCopyFeedback(""), 2000);
+ }
+ };
+
+ return (
+ <Modal
+ open={open}
+ onClose={onClose}
+ title="πŸ–₯️ Start Profile"
+ actions={
+ <>
+ <Button
+ variant="secondary"
+ disabled={launchLoading}
+ onClick={onClose}
+ >
+ Cancel
+ </Button>
+ <Button
+ variant="primary"
+ onClick={handleLaunch}
+ loading={launchLoading}
+ >
+ Start
+ </Button>
+ </>
+ }
+ >
+ <div className="flex flex-col gap-4">
+ {launchError && (
+ <div className="rounded border border-destructive/50 bg-destructive/10 px-3 py-2 text-sm text-destructive">
+ {launchError}
+ </div>
+ )}
+ <Input
+ label="Port"
+ placeholder="Auto-select from configured range"
+ value={port}
+ onChange={(e) => setPort(e.target.value)}
+ />
+ <p className="-mt-2 text-xs text-text-muted">
+ Leave blank to auto-select a free port from the configured instance
+ port range.
+ </p>
+ <label className="flex items-center gap-2 text-sm text-text-secondary">
+ <input
+ type="checkbox"
+ checked={headless}
+ onChange={(e) => setHeadless(e.target.checked)}
+ className="h-4 w-4"
+ />
+ Headless (best for Docker/VPS)
+ </label>
+
+ <div>
+ <label className="mb-1 block text-xs text-text-muted">
+ Direct launch command (backup)
+ </label>
+ <textarea
+ readOnly
+ value={launchCommand}
+ className="h-20 w-full resize-none rounded border border-border-subtle bg-bg-elevated px-3 py-2 font-mono text-xs text-text-secondary"
+ />
+ <div className="mt-2 flex items-center gap-2">
+ <Button size="sm" variant="secondary" onClick={handleCopyCommand}>
+ Copy Command
+ </Button>
+ {copyFeedback && (
+ <span className="text-xs text-success">{copyFeedback}</span>
+ )}
+ </div>
+ </div>
+ </div>
+ </Modal>
+ );
+}
diff --git a/dashboard/src/components/molecules/TabItem.test.tsx b/dashboard/src/components/molecules/TabItem.test.tsx
deleted file mode 100644
index b8c8bcda..00000000
--- a/dashboard/src/components/molecules/TabItem.test.tsx
+++ /dev/null
@@ -1,53 +0,0 @@
-import { render, screen } from "@testing-library/react";
-import { describe, it, expect } from "vitest";
-import TabItem from "./TabItem";
-import type { InstanceTab } from "../../generated/types";
-
-const mockTab: InstanceTab = {
- id: "tab_123",
- instanceId: "inst_456",
- url: "https://pinchtab.com/page",
- title: "Example Page",
-};
-
-describe("TabItem", () => {
- it("renders tab title and url", () => {
- render(<TabItem tab={mockTab} />);
-
- expect(screen.getByText("Example Page")).toBeInTheDocument();
- expect(screen.getByText("https://pinchtab.com/page")).toBeInTheDocument();
- });
-
- it("shows Untitled for tabs without title", () => {
- const noTitleTab = { ...mockTab, title: "" };
- render(<TabItem tab={noTitleTab} />);
-
- expect(screen.getByText("Untitled")).toBeInTheDocument();
- });
-
- it("renders short tab ID badge", () => {
- render(<TabItem tab={mockTab} />);
-
- // Tab ID is shortened to last segment
- expect(screen.getByText("123")).toBeInTheDocument();
- });
-
- it("renders compact variant", () => {
- render(<TabItem tab={mockTab} compact />);
-
- expect(screen.getByText("Example Page")).toBeInTheDocument();
- // Compact renders as a flat bordered row
- const titleEl = screen.getByText("Example Page");
- const outerDiv = titleEl.closest(".rounded-sm");
- expect(outerDiv).toBeInTheDocument();
- });
-
- it("renders flat row variant by default", () => {
- render(<TabItem tab={mockTab} />);
-
- // Default renders as a bordered row, not a nested card shell
- const titleEl = screen.getByText("Example Page");
- const row = titleEl.closest(".rounded-md");
- expect(row).toBeInTheDocument();
- });
-});
diff --git a/dashboard/src/components/molecules/TabItem.tsx b/dashboard/src/components/molecules/TabItem.tsx
deleted file mode 100644
index 2ba9912e..00000000
--- a/dashboard/src/components/molecules/TabItem.tsx
+++ /dev/null
@@ -1,65 +0,0 @@
-import { useState } from "react";
-import type { InstanceTab } from "../../generated/types";
-
-interface Props {
- tab: InstanceTab;
- compact?: boolean;
-}
-
-export default function TabItem({ tab, compact }: Props) {
- const [copied, setCopied] = useState(false);
-
- const handleCopy = (e: React.MouseEvent) => {
- e.stopPropagation();
- navigator.clipboard.writeText(tab.id);
- setCopied(true);
- setTimeout(() => setCopied(false), 2000);
- };
-
- const shortId = tab.id.split("_").pop()?.substring(0, 8) || tab.id;
-
- const idBadge = (
- <button
- onClick={handleCopy}
- title={`Click to copy full ID: ${tab.id}`}
- className="group flex shrink-0 items-center gap-1.5 rounded bg-bg-elevated px-1.5 py-0.5 text-[10px] font-mono text-text-muted transition-colors hover:bg-border-subtle hover:text-text-primary focus:outline-none"
- >
- <span>{shortId}</span>
- <span className="text-[8px] opacity-0 transition-opacity group-hover:opacity-100">
- {copied ? "βœ…" : "πŸ“‹"}
- </span>
- </button>
- );
-
- if (compact) {
- return (
- <div className="rounded-sm border border-border-subtle/70 bg-white/[0.02] px-3 py-2">
- <div className="flex items-center gap-2 overflow-hidden">
- {idBadge}
- <div className="text-text-dim">/</div>
- <div className="truncate text-sm font-medium text-text-primary">
- {tab.title || "Untitled"}
- </div>
- </div>
- <div className="mt-0.5 truncate text-[11px] text-text-muted opacity-70">
- {tab.url}
- </div>
- </div>
- );
- }
-
- return (
- <div className="rounded-md border border-border-subtle/80 bg-white/[0.02] px-3 py-2.5 transition-colors hover:border-border-default hover:bg-white/[0.03]">
- <div className="flex items-center gap-2 overflow-hidden">
- {idBadge}
- <div className="text-text-dim">/</div>
- <div className="truncate text-sm font-medium text-text-primary">
- {tab.title || "Untitled"}
- </div>
- </div>
- <div className="mt-1 truncate text-xs text-text-muted opacity-80">
- {tab.url}
- </div>
- </div>
- );
-}
diff --git a/dashboard/src/components/molecules/TabsChart2.test.tsx b/dashboard/src/components/molecules/TabsChart2.test.tsx
deleted file mode 100644
index 1e8f0d4e..00000000
--- a/dashboard/src/components/molecules/TabsChart2.test.tsx
+++ /dev/null
@@ -1,45 +0,0 @@
-import { render, screen } from "@testing-library/react";
-import { describe, expect, it } from "vitest";
-import TabsChart2 from "./TabsChart2";
-import type { TabDataPoint } from "../../stores/useAppStore";
-
-const mockInstances = [
- { id: "inst_1", profileName: "profile-1" },
- { id: "inst_2", profileName: "profile-2" },
-];
-
-const mockData: TabDataPoint[] = [
- { timestamp: Date.now() - 60000, inst_1: 3, inst_2: 5 },
- { timestamp: Date.now() - 30000, inst_1: 4, inst_2: 6 },
- { timestamp: Date.now(), inst_1: 5, inst_2: 4 },
-];
-
-describe("TabsChart2", () => {
- it('shows "Collecting data..." when no data exists', () => {
- render(
- <TabsChart2
- data={[]}
- instances={[]}
- selectedInstanceId={null}
- onSelectInstance={() => {}}
- />,
- );
-
- expect(screen.getByText("Collecting data...")).toBeInTheDocument();
- });
-
- it("renders the terminal chart shell when data exists", () => {
- render(
- <TabsChart2
- data={mockData}
- instances={mockInstances}
- selectedInstanceId={null}
- onSelectInstance={() => {}}
- />,
- );
-
- expect(screen.getByTestId("terminal-tabs-chart")).toBeInTheDocument();
- expect(screen.getByText("Terminal telemetry")).toBeInTheDocument();
- expect(screen.getByText("Tabs")).toBeInTheDocument();
- });
-});
diff --git a/dashboard/src/components/molecules/TabsChart2.tsx b/dashboard/src/components/molecules/TabsChart2.tsx
deleted file mode 100644
index 112bbfec..00000000
--- a/dashboard/src/components/molecules/TabsChart2.tsx
+++ /dev/null
@@ -1,370 +0,0 @@
-import { useMemo } from "react";
-import type {
- MemoryDataPoint,
- ServerDataPoint,
- TabDataPoint,
-} from "../../stores/useAppStore";
-
-interface Props {
- data: TabDataPoint[];
- memoryData?: MemoryDataPoint[];
- serverData?: ServerDataPoint[];
- instances: { id: string; profileName: string }[];
- selectedInstanceId: string | null;
- onSelectInstance: (id: string) => void;
-}
-
-interface SeriesDefinition {
- id: string;
- key: string;
- label: string;
- color: string;
- selectable: boolean;
- selected: boolean;
-}
-
-interface TrackDefinition {
- id: string;
- title: string;
- suffix: string;
- rows: number;
- series: SeriesDefinition[];
- data: Record<string, number>[];
-}
-
-const COLORS = [
- "#60a5fa",
- "#93c5fd",
- "#38bdf8",
- "#22c55e",
- "#fbbf24",
- "#ef4444",
- "#818cf8",
- "#2dd4bf",
-];
-
-function formatTime(timestamp: number): string {
- return new Date(timestamp).toLocaleTimeString("en-GB", {
- hour: "2-digit",
- minute: "2-digit",
- });
-}
-
-function formatMetricValue(value: number, maximumFractionDigits = 0): string {
- if (!Number.isFinite(value)) return "0";
-
- return new Intl.NumberFormat("en-US", {
- maximumFractionDigits,
- }).format(value);
-}
-
-function formatValue(value: number, suffix: string): string {
- return suffix
- ? `${formatMetricValue(value, 1)}${suffix}`
- : formatMetricValue(value);
-}
-
-function clampCellCount(value: number, maxValue: number, rows: number): number {
- if (value <= 0 || maxValue <= 0) return 0;
- return Math.max(1, Math.min(rows, Math.round((value / maxValue) * rows)));
-}
-
-function TerminalTrack({
- track,
- selectedInstanceId,
- onSelectInstance,
-}: {
- track: TrackDefinition;
- selectedInstanceId: string | null;
- onSelectInstance: (id: string) => void;
-}) {
- const cell = 4;
- const gap = 3;
- const rowStride = cell + gap;
- const colInset = 3;
- const topInset = 10;
- const bottomInset = 20;
- const rightInset = 8;
- const columns = track.data.length;
- const seriesCount = Math.max(track.series.length, 1);
- const groupWidth = Math.max(12, seriesCount * (cell + 2) + 8);
- const width = colInset + columns * groupWidth + rightInset;
- const height = topInset + track.rows * rowStride + bottomInset;
- const maxValue = Math.max(
- 1,
- ...track.data.flatMap((point) =>
- track.series.map((series) => point[series.key] ?? 0),
- ),
- );
- const labelStep = Math.max(1, Math.ceil(columns / 6));
-
- return (
- <div className="rounded-md border border-border-subtle bg-[rgb(var(--brand-surface-code-rgb)/0.55)] px-3 py-3">
- <div className="mb-3 flex items-center justify-between">
- <div className="dashboard-section-title">{track.title}</div>
- <div className="dashboard-mono text-[0.68rem] text-text-muted">
- max {formatValue(maxValue, track.suffix)}
- </div>
- </div>
-
- <div className="overflow-x-auto">
- <svg
- width={width}
- height={height}
- viewBox={`0 0 ${width} ${height}`}
- className="block min-w-full"
- role="img"
- aria-label={`${track.title} terminal chart`}
- >
- {track.data.map((point, pointIndex) => {
- const groupX = colInset + pointIndex * groupWidth;
-
- return track.series.map((series, seriesIndex) => {
- const value = point[series.key] ?? 0;
- const lit = clampCellCount(value, maxValue, track.rows);
- const x = groupX + seriesIndex * (cell + 2);
- const dimmed =
- selectedInstanceId &&
- series.selectable &&
- selectedInstanceId !== series.id;
-
- return (
- <g key={`${track.id}-${series.key}-${point.timestamp}`}>
- {Array.from({ length: track.rows }).map((_, rowIndex) => {
- const y =
- topInset + (track.rows - 1 - rowIndex) * rowStride;
- const active = rowIndex < lit;
-
- return (
- <rect
- key={`${track.id}-${series.key}-${pointIndex}-${rowIndex}`}
- x={x}
- y={y}
- width={cell}
- height={cell}
- rx={0.8}
- fill={active ? series.color : "rgb(255 255 255 / 0.07)"}
- opacity={active ? (dimmed ? 0.3 : 0.92) : 1}
- >
- <title>
- {`${series.label} ${formatValue(value, track.suffix)} at ${formatTime(point.timestamp)}`}
- </title>
- </rect>
- );
- })}
- </g>
- );
- });
- })}
-
- {track.data.map(
- (point, pointIndex) =>
- (pointIndex % labelStep === 0 || pointIndex === columns - 1) && (
- <text
- key={`${track.id}-label-${point.timestamp}`}
- x={colInset + pointIndex * groupWidth}
- y={height - 4}
- fill="#64748b"
- fontSize="10"
- fontFamily="JetBrains Mono, monospace"
- >
- {formatTime(point.timestamp)}
- </text>
- ),
- )}
- </svg>
- </div>
-
- <div className="mt-3 flex flex-wrap gap-1.5">
- {track.series.map((series) => {
- const active = selectedInstanceId === series.id;
- return (
- <button
- key={`${track.id}-${series.key}-legend`}
- type="button"
- onClick={() => series.selectable && onSelectInstance(series.id)}
- className={`inline-flex items-center gap-2 rounded-sm border px-2 py-1 text-[0.68rem] font-semibold uppercase tracking-[0.08em] transition-all ${
- series.selectable
- ? active
- ? "border-primary/35 bg-primary/10 text-primary"
- : "border-border-subtle bg-white/[0.03] text-text-secondary hover:border-border-default hover:text-text-primary"
- : "cursor-default border-border-subtle bg-white/[0.03] text-text-secondary"
- }`}
- >
- <span
- className="h-2 w-2 rounded-[2px]"
- style={{ backgroundColor: series.color }}
- aria-hidden="true"
- />
- {series.label}
- </button>
- );
- })}
- </div>
- </div>
- );
-}
-
-export default function TabsChart2({
- data,
- memoryData,
- serverData,
- instances,
- selectedInstanceId,
- onSelectInstance,
-}: Props) {
- const mergedData = useMemo(() => {
- const memByTime = new Map((memoryData || []).map((m) => [m.timestamp, m]));
- const serverByTime = new Map(
- (serverData || []).map((s) => [s.timestamp, s]),
- );
-
- const baseData =
- data.length > 0
- ? data
- : (serverData || []).map((s) => ({ timestamp: s.timestamp }));
-
- return baseData.map((d) => {
- const merged: Record<string, number> = { timestamp: d.timestamp };
-
- for (const [key, val] of Object.entries(d)) {
- if (key !== "timestamp") {
- merged[key] = val as number;
- }
- }
-
- const mem = memByTime.get(d.timestamp);
- if (mem) {
- for (const [key, val] of Object.entries(mem)) {
- if (key !== "timestamp") {
- merged[`${key}_mem`] = val;
- }
- }
- }
-
- const srv = serverByTime.get(d.timestamp);
- if (srv) {
- merged.goHeapMB = srv.goHeapMB;
- }
-
- return merged;
- });
- }, [data, memoryData, serverData]);
-
- const hasMemory = Boolean(memoryData && memoryData.length > 0);
- const hasServer = Boolean(serverData && serverData.length > 0);
-
- const tracks = useMemo<TrackDefinition[]>(() => {
- const tabSeries: SeriesDefinition[] = instances.map((instance, index) => ({
- id: instance.id,
- key: instance.id,
- label: instance.profileName,
- color: COLORS[index % COLORS.length],
- selectable: true,
- selected: selectedInstanceId === instance.id,
- }));
-
- const memorySeries: SeriesDefinition[] = hasMemory
- ? instances.map((instance, index) => ({
- id: instance.id,
- key: `${instance.id}_mem`,
- label: instance.profileName,
- color: COLORS[index % COLORS.length],
- selectable: true,
- selected: selectedInstanceId === instance.id,
- }))
- : [];
-
- const nextTracks: TrackDefinition[] = [];
-
- if (tabSeries.length > 0) {
- nextTracks.push({
- id: "tabs",
- title: "Tabs",
- suffix: "",
- rows: 10,
- series: tabSeries,
- data: mergedData,
- });
- }
-
- if (memorySeries.length > 0) {
- nextTracks.push({
- id: "memory",
- title: "Memory",
- suffix: "MB",
- rows: 8,
- series: memorySeries,
- data: mergedData,
- });
- }
-
- if (hasServer) {
- nextTracks.push({
- id: "server",
- title: "Heap",
- suffix: "MB",
- rows: 6,
- series: [
- {
- id: "goHeapMB",
- key: "goHeapMB",
- label: "Server Heap",
- color: "#cbd5e1",
- selectable: false,
- selected: false,
- },
- ],
- data: mergedData,
- });
- }
-
- return nextTracks;
- }, [hasMemory, hasServer, instances, mergedData, selectedInstanceId]);
-
- if (mergedData.length < 2) {
- return (
- <div className="dashboard-panel flex h-56 items-center justify-center text-sm text-text-muted">
- {mergedData.length === 0
- ? "Collecting data..."
- : "Waiting for more data..."}
- </div>
- );
- }
-
- return (
- <div
- className="dashboard-panel overflow-hidden"
- data-testid="terminal-tabs-chart"
- >
- <div className="flex items-center justify-between border-b border-border-subtle px-4 py-3">
- <div>
- <div className="dashboard-section-label">Monitoring</div>
- <div className="mt-1 text-sm font-semibold text-text-primary">
- Terminal telemetry
- </div>
- </div>
- <div className="dashboard-mono text-[0.72rem] uppercase tracking-[0.12em] text-text-muted">
- {mergedData.length} samples
- </div>
- </div>
-
- <div className="flex flex-col gap-3 p-3">
- {tracks.length === 0 ? (
- <div className="rounded-md border border-border-subtle bg-[rgb(var(--brand-surface-code-rgb)/0.55)] px-4 py-6 text-sm text-text-muted">
- No terminal tracks available.
- </div>
- ) : (
- tracks.map((track) => (
- <TerminalTrack
- key={track.id}
- track={track}
- selectedInstanceId={selectedInstanceId}
- onSelectInstance={onSelectInstance}
- />
- ))
- )}
- </div>
- </div>
- );
-}
diff --git a/dashboard/src/components/molecules/TabsLayout.tsx b/dashboard/src/components/molecules/TabsLayout.tsx
new file mode 100644
index 00000000..c146d6aa
--- /dev/null
+++ b/dashboard/src/components/molecules/TabsLayout.tsx
@@ -0,0 +1,52 @@
+import React from "react";
+
+export interface TabItem<T extends string> {
+ id: T;
+ label: string;
+ badge?: string | number;
+}
+
+interface Props<T extends string> {
+ tabs: TabItem<T>[];
+ activeTab: T;
+ onChange: (id: T) => void;
+ children: React.ReactNode;
+ className?: string;
+}
+
+export default function TabsLayout<T extends string>({
+ tabs,
+ activeTab,
+ onChange,
+ children,
+ className = "",
+}: Props<T>) {
+ return (
+ <div className={`flex h-full flex-col overflow-hidden ${className}`}>
+ <div className="border-b border-border-subtle px-4 py-2">
+ <div className="flex flex-wrap gap-1">
+ {tabs.map((tab) => (
+ <button
+ key={tab.id}
+ type="button"
+ onClick={() => onChange(tab.id)}
+ className={`rounded px-3 py-1.5 text-xs font-medium transition-colors ${
+ activeTab === tab.id
+ ? "bg-bg-hover text-text-primary"
+ : "text-text-muted hover:bg-bg-hover hover:text-text-secondary"
+ }`}
+ >
+ {tab.label}
+ {tab.badge !== undefined && (
+ <span className="ml-1.5 rounded-full bg-bg-elevated px-1.5 py-0.5 text-[10px] opacity-70">
+ {tab.badge}
+ </span>
+ )}
+ </button>
+ ))}
+ </div>
+ </div>
+ <div className="min-h-0 flex-1 overflow-auto p-4">{children}</div>
+ </div>
+ );
+}
diff --git a/dashboard/src/components/molecules/index.ts b/dashboard/src/components/molecules/index.ts
index 3edcb099..ab4e203a 100644
--- a/dashboard/src/components/molecules/index.ts
+++ b/dashboard/src/components/molecules/index.ts
@@ -1,13 +1,13 @@
+export { default as TabsLayout } from "./TabsLayout";
+export { default as EmptyView } from "./EmptyView";
export { default as NavBar } from "./NavBar";
-export { default as ProfileCard } from "./ProfileCard";
-export { default as ProfileDetailsModal } from "./ProfileDetailsModal";
-export { default as ProfileDetailsPanel } from "./ProfileDetailsPanel";
-export { default as ScreencastTile } from "./ScreencastTile";
-export { default as InstanceCard } from "./InstanceCard";
-export { default as InstanceListItem } from "./InstanceListItem";
-export { default as TabItem } from "./TabItem";
+export { default as CreateProfileModal } from "./CreateProfileModal";
+export { default as ProfileCard } from "../profiles/ProfileCard";
+export { default as ProfileDetailsPanel } from "../profiles/ProfileDetailsPanel";
+export { default as StartInstanceModal } from "./StartInstanceModal";
+export { default as ScreencastTile } from "../screencast/ScreencastTile";
+export { InstanceTabsPanel, TabItem } from "../tabs";
export { default as AgentItem } from "./AgentItem";
export { default as ActivityLine } from "./ActivityLine";
export { default as TabsChart } from "./TabsChart";
-export { default as TabsChart2 } from "./TabsChart2";
export { default as ServerSummary } from "./ServerSummary";
diff --git a/dashboard/src/components/profiles/InstanceLogsPanel.test.tsx b/dashboard/src/components/profiles/InstanceLogsPanel.test.tsx
new file mode 100644
index 00000000..dc88d437
--- /dev/null
+++ b/dashboard/src/components/profiles/InstanceLogsPanel.test.tsx
@@ -0,0 +1,72 @@
+import { act, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import InstanceLogsPanel from "./InstanceLogsPanel";
+
+const { fetchInstanceLogs, subscribeToInstanceLogs } = vi.hoisted(() => ({
+ fetchInstanceLogs: vi.fn(),
+ subscribeToInstanceLogs: vi.fn(),
+}));
+
+vi.mock("../../services/api", () => ({
+ fetchInstanceLogs,
+ subscribeToInstanceLogs,
+}));
+
+describe("InstanceLogsPanel", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ subscribeToInstanceLogs.mockReturnValue(() => {});
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("loads logs on mount when an instance id is provided", async () => {
+ fetchInstanceLogs.mockResolvedValue("first line\nsecond line");
+
+ render(<InstanceLogsPanel instanceId="inst_123" />);
+
+ expect(screen.getByText("Loading logs...")).toBeInTheDocument();
+
+ await waitFor(() => {
+ expect(document.querySelector("pre")).toHaveTextContent(
+ "first line second line",
+ );
+ });
+ expect(fetchInstanceLogs).toHaveBeenCalledWith("inst_123");
+ expect(subscribeToInstanceLogs).toHaveBeenCalledWith("inst_123", {
+ onLogs: expect.any(Function),
+ });
+ });
+
+ it("updates rendered logs from the subscription stream", async () => {
+ fetchInstanceLogs.mockResolvedValue("");
+ let onLogs: ((logs: string) => void) | undefined;
+
+ subscribeToInstanceLogs.mockImplementation((_id, handlers) => {
+ onLogs = handlers.onLogs;
+ return () => {};
+ });
+
+ render(<InstanceLogsPanel instanceId="inst_123" />);
+
+ await waitFor(() => {
+ expect(subscribeToInstanceLogs).toHaveBeenCalledTimes(1);
+ });
+
+ await act(async () => {
+ onLogs?.("streamed logs");
+ });
+
+ expect(document.querySelector("pre")).toHaveTextContent("streamed logs");
+ });
+
+ it("shows the empty state when no instance is available", () => {
+ render(<InstanceLogsPanel />);
+
+ expect(screen.getByText("No instance logs available.")).toBeInTheDocument();
+ expect(fetchInstanceLogs).not.toHaveBeenCalled();
+ expect(subscribeToInstanceLogs).not.toHaveBeenCalled();
+ });
+});
diff --git a/dashboard/src/components/profiles/InstanceLogsPanel.tsx b/dashboard/src/components/profiles/InstanceLogsPanel.tsx
new file mode 100644
index 00000000..978b0359
--- /dev/null
+++ b/dashboard/src/components/profiles/InstanceLogsPanel.tsx
@@ -0,0 +1,77 @@
+import { useEffect, useState } from "react";
+import * as api from "../../services/api";
+
+interface Props {
+ instanceId?: string;
+ emptyMessage?: string;
+}
+
+export default function InstanceLogsPanel({
+ instanceId,
+ emptyMessage = "No instance logs available.",
+}: Props) {
+ const [logs, setLogs] = useState("");
+ const [loading, setLoading] = useState(false);
+
+ useEffect(() => {
+ if (!instanceId) {
+ setLogs("");
+ setLoading(false);
+ return;
+ }
+
+ let cancelled = false;
+ setLoading(true);
+
+ api
+ .fetchInstanceLogs(instanceId)
+ .then((nextLogs) => {
+ if (!cancelled) {
+ setLogs(nextLogs);
+ }
+ })
+ .catch((error) => {
+ console.error("Failed to load instance logs", error);
+ if (!cancelled) {
+ setLogs("");
+ }
+ })
+ .finally(() => {
+ if (!cancelled) {
+ setLoading(false);
+ }
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [instanceId]);
+
+ useEffect(() => {
+ if (!instanceId) {
+ return;
+ }
+
+ return api.subscribeToInstanceLogs(instanceId, {
+ onLogs: (nextLogs) => setLogs(nextLogs),
+ });
+ }, [instanceId]);
+
+ return (
+ <div className="flex h-full min-h-0 flex-col">
+ {loading && !logs ? (
+ <div className="flex h-full items-center justify-center rounded-xl border border-border-subtle bg-black/10 px-4 py-6 text-sm text-text-muted">
+ Loading logs...
+ </div>
+ ) : logs ? (
+ <pre className="h-full overflow-auto rounded-xl border border-border-subtle bg-black/10 p-3 font-mono text-[10px] leading-4 text-text-secondary">
+ {logs}
+ </pre>
+ ) : (
+ <div className="flex h-full items-center justify-center rounded-xl border border-border-subtle bg-black/10 px-4 py-6 text-sm text-text-muted">
+ {emptyMessage}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/dashboard/src/components/profiles/ProfileBasicInfoPanel.tsx b/dashboard/src/components/profiles/ProfileBasicInfoPanel.tsx
new file mode 100644
index 00000000..b5d24f4a
--- /dev/null
+++ b/dashboard/src/components/profiles/ProfileBasicInfoPanel.tsx
@@ -0,0 +1,48 @@
+import { useState, useEffect } from "react";
+import { Input } from "../atoms";
+import type { Profile } from "../../generated/types";
+
+interface Props {
+ profile: Profile;
+ onChange: (name: string, useWhen: string) => void;
+ minHeight?: string;
+}
+
+export default function ProfileBasicInfoPanel({
+ profile,
+ onChange,
+ minHeight = "min-h-[180px]",
+}: Props) {
+ const [name, setName] = useState(profile.name);
+ const [useWhen, setUseWhen] = useState(profile.useWhen || "");
+
+ useEffect(() => {
+ setName(profile.name);
+ setUseWhen(profile.useWhen || "");
+ }, [profile]);
+
+ useEffect(() => {
+ onChange(name, useWhen);
+ }, [name, useWhen, onChange]);
+
+ return (
+ <div className="space-y-4">
+ <Input
+ label="Name"
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ />
+
+ <div>
+ <label className="dashboard-section-title mb-1 block text-[0.68rem]">
+ Use this profile when
+ </label>
+ <textarea
+ value={useWhen}
+ onChange={(e) => setUseWhen(e.target.value)}
+ className={`${minHeight} w-full resize-y rounded border border-border-subtle bg-bg-elevated px-3 py-2 text-sm text-text-primary`}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/dashboard/src/components/molecules/ProfileCard.test.tsx b/dashboard/src/components/profiles/ProfileCard.test.tsx
similarity index 100%
rename from dashboard/src/components/molecules/ProfileCard.test.tsx
rename to dashboard/src/components/profiles/ProfileCard.test.tsx
diff --git a/dashboard/src/components/molecules/ProfileCard.tsx b/dashboard/src/components/profiles/ProfileCard.tsx
similarity index 100%
rename from dashboard/src/components/molecules/ProfileCard.tsx
rename to dashboard/src/components/profiles/ProfileCard.tsx
diff --git a/dashboard/src/components/profiles/ProfileDetailsPanel.tsx b/dashboard/src/components/profiles/ProfileDetailsPanel.tsx
new file mode 100644
index 00000000..c530d01b
--- /dev/null
+++ b/dashboard/src/components/profiles/ProfileDetailsPanel.tsx
@@ -0,0 +1,155 @@
+import { useState, useEffect, useCallback } from "react";
+import InstanceLogsPanel from "./InstanceLogsPanel";
+import ProfileMetaInfoPanel from "./ProfileMetaInfoPanel";
+import ProfileBasicInfoPanel from "./ProfileBasicInfoPanel";
+import ProfileLiveViewPanel from "./ProfileLiveViewPanel";
+import ProfileToolbar from "./ProfileToolbar";
+import { InstanceTabsPanel } from "../tabs";
+import { TabsLayout, EmptyView } from "../molecules";
+import type { Profile, Instance, InstanceTab } from "../../generated/types";
+import * as api from "../../services/api";
+
+interface Props {
+ profile: Profile | null;
+ instance?: Instance;
+ onLaunch: () => void;
+ onStop?: () => void;
+ onSave?: (name: string, useWhen: string) => void;
+ onDelete?: () => void;
+}
+
+type TabId = "profile" | "live" | "tabs" | "logs";
+
+export default function ProfileDetailsPanel({
+ profile,
+ instance,
+ onLaunch,
+ onStop,
+ onSave,
+ onDelete,
+}: Props) {
+ const [activeTab, setActiveTab] = useState<TabId>("profile");
+ const [tabs, setTabs] = useState<InstanceTab[]>([]);
+ const [formValues, setFormValues] = useState({ name: "", useWhen: "" });
+
+ const isRunning = instance?.status === "running";
+
+ useEffect(() => {
+ if (profile) {
+ setFormValues({ name: profile.name, useWhen: profile.useWhen || "" });
+ } else {
+ setTabs([]);
+ setFormValues({ name: "", useWhen: "" });
+ }
+ }, [profile]);
+
+ const handleProfileChange = useCallback((name: string, useWhen: string) => {
+ setFormValues({ name, useWhen });
+ }, []);
+
+ const loadTabs = useCallback(async () => {
+ if (!instance?.id) {
+ setTabs([]);
+ return;
+ }
+
+ try {
+ const instanceTabs = await api
+ .fetchInstanceTabs(instance.id)
+ .catch(() => []);
+ setTabs(instanceTabs);
+ } catch (e) {
+ console.error("Failed to load tabs", e);
+ }
+ }, [instance]);
+
+ useEffect(() => {
+ if (activeTab === "live" || activeTab === "tabs" || activeTab === "logs") {
+ loadTabs();
+ }
+ }, [activeTab, loadTabs]);
+
+ const handleSave = () => {
+ onSave?.(formValues.name, formValues.useWhen);
+ };
+
+ if (!profile) {
+ return (
+ <div className="dashboard-panel h-full min-h-112">
+ <EmptyView message="Select a profile to inspect its instance, live tabs, and logs." />
+ </div>
+ );
+ }
+
+ const hasChanges =
+ formValues.name.trim() !== profile.name ||
+ formValues.useWhen !== (profile.useWhen || "");
+
+ const profileTabs: { id: TabId; label: string; badge?: string | number }[] = [
+ { id: "profile", label: "Profile" },
+ { id: "live", label: "Live" },
+ { id: "tabs", label: "Tabs", badge: tabs.length },
+ { id: "logs", label: "Logs" },
+ ];
+
+ return (
+ <div className="dashboard-panel flex h-full min-h-112 flex-col overflow-hidden">
+ <div className="border-b border-border-subtle px-4 py-3 lg:px-5">
+ <ProfileToolbar
+ profile={profile}
+ instance={instance}
+ onLaunch={onLaunch}
+ onStop={onStop || (() => {})}
+ onSave={handleSave}
+ onDelete={onDelete || (() => {})}
+ isSaveDisabled={!formValues.name.trim() || !hasChanges}
+ />
+ </div>
+
+ <div className="min-h-0 flex-1 overflow-hidden">
+ <TabsLayout
+ tabs={profileTabs}
+ activeTab={activeTab}
+ onChange={(id) => setActiveTab(id)}
+ >
+ {activeTab === "profile" && (
+ <div className="h-full overflow-auto">
+ <div className="grid gap-4 xl:grid-cols-2">
+ <ProfileBasicInfoPanel
+ profile={profile}
+ onChange={handleProfileChange}
+ />
+
+ <ProfileMetaInfoPanel profile={profile} instance={instance} />
+ </div>
+ </div>
+ )}
+
+ {activeTab === "live" && (
+ <ProfileLiveViewPanel
+ instance={instance}
+ tabs={tabs}
+ isRunning={isRunning}
+ />
+ )}
+
+ {activeTab === "tabs" && (
+ <div className="flex h-full min-h-0 flex-col">
+ <InstanceTabsPanel
+ tabs={tabs}
+ instanceId={instance?.id}
+ emptyMessage={
+ isRunning ? "No tabs open." : "Instance not running."
+ }
+ />
+ </div>
+ )}
+
+ {activeTab === "logs" && (
+ <InstanceLogsPanel instanceId={instance?.id} />
+ )}
+ </TabsLayout>
+ </div>
+ </div>
+ );
+}
diff --git a/dashboard/src/components/profiles/ProfileLiveViewPanel.tsx b/dashboard/src/components/profiles/ProfileLiveViewPanel.tsx
new file mode 100644
index 00000000..c3aefb71
--- /dev/null
+++ b/dashboard/src/components/profiles/ProfileLiveViewPanel.tsx
@@ -0,0 +1,40 @@
+import type { Instance, InstanceTab } from "../../generated/types";
+import ScreencastTile from "../screencast/ScreencastTile";
+import { EmptyView } from "../molecules";
+
+interface Props {
+ instance?: Instance;
+ tabs: InstanceTab[];
+ isRunning: boolean;
+}
+
+export default function ProfileLiveViewPanel({
+ instance,
+ tabs,
+ isRunning,
+}: Props) {
+ return (
+ <div className="h-full overflow-y-auto">
+ {isRunning && instance ? (
+ tabs.length === 0 ? (
+ <EmptyView message="No tabs open" />
+ ) : (
+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
+ {tabs.map((tab) => (
+ <div key={tab.id} className="aspect-video">
+ <ScreencastTile
+ instanceId={instance.id}
+ tabId={tab.id}
+ label={tab.title?.slice(0, 20) || tab.id.slice(0, 8)}
+ url={tab.url}
+ />
+ </div>
+ ))}
+ </div>
+ )
+ ) : (
+ <EmptyView message="Instance not running. Start the profile to see live view." />
+ )}
+ </div>
+ );
+}
diff --git a/dashboard/src/components/profiles/ProfileMetaInfoPanel.tsx b/dashboard/src/components/profiles/ProfileMetaInfoPanel.tsx
new file mode 100644
index 00000000..d52cb442
--- /dev/null
+++ b/dashboard/src/components/profiles/ProfileMetaInfoPanel.tsx
@@ -0,0 +1,107 @@
+import type { Profile, Instance } from "../../generated/types";
+
+interface Props {
+ profile: Profile;
+ instance?: Instance;
+}
+
+function MetaBlock({
+ label,
+ children,
+}: {
+ label: string;
+ children: React.ReactNode;
+}) {
+ return (
+ <div className="rounded-xl border border-border-subtle bg-black/10 p-4">
+ <div className="dashboard-section-title mb-2 text-[0.68rem]">{label}</div>
+ {children}
+ </div>
+ );
+}
+
+export default function ProfileMetaInfoPanel({ profile, instance }: Props) {
+ const accountText = profile.accountEmail || profile.accountName || "";
+ const sizeText = profile.sizeMB ? `${profile.sizeMB.toFixed(0)} MB` : "β€”";
+ const browserType = instance?.attached
+ ? "Attached via CDP"
+ : instance?.headless
+ ? "Headless"
+ : "Headed";
+
+ return (
+ <MetaBlock label="Profile panel">
+ <div className="space-y-3 text-sm text-text-secondary">
+ <div className="flex items-center justify-between gap-3">
+ <span className="dashboard-section-title text-[0.68rem]">Status</span>
+ <span className="text-right">{instance?.status || "stopped"}</span>
+ </div>
+ {instance?.port && (
+ <div className="flex items-center justify-between gap-3">
+ <span className="dashboard-section-title text-[0.68rem]">Port</span>
+ <span className="text-right">{instance.port}</span>
+ </div>
+ )}
+ <div className="flex items-center justify-between gap-3">
+ <span className="dashboard-section-title text-[0.68rem]">
+ Browser
+ </span>
+ <span className="text-right">{browserType}</span>
+ </div>
+ <div className="flex items-center justify-between gap-3">
+ <span className="dashboard-section-title text-[0.68rem]">Size</span>
+ <span className="text-right">{sizeText}</span>
+ </div>
+ {accountText && (
+ <div className="flex items-center justify-between gap-3">
+ <span className="dashboard-section-title text-[0.68rem]">
+ Account
+ </span>
+ <span className="text-right">{accountText}</span>
+ </div>
+ )}
+ {profile.chromeProfileName && (
+ <div className="flex items-center justify-between gap-3">
+ <span className="dashboard-section-title text-[0.68rem]">
+ Identity
+ </span>
+ <span className="text-right">{profile.chromeProfileName}</span>
+ </div>
+ )}
+ {instance?.attached && (
+ <div className="flex items-center justify-between gap-3">
+ <span className="dashboard-section-title text-[0.68rem]">
+ Connection
+ </span>
+ <span className="text-right">CDP attached</span>
+ </div>
+ )}
+ {instance?.cdpUrl && (
+ <div>
+ <div className="dashboard-section-title mb-1 text-[0.68rem]">
+ CDP URL
+ </div>
+ <code className="dashboard-mono block break-all text-xs text-text-secondary">
+ {instance.cdpUrl}
+ </code>
+ </div>
+ )}
+ {profile.path && (
+ <div>
+ <div className="dashboard-section-title mb-1 text-[0.68rem]">
+ Path
+ </div>
+ <code
+ className={`dashboard-mono block break-all text-xs ${
+ profile.pathExists ? "text-text-secondary" : "text-destructive"
+ }`}
+ >
+ {profile.path}
+ {!profile.pathExists && " (not found)"}
+ </code>
+ </div>
+ )}
+ </div>
+ </MetaBlock>
+ );
+}
diff --git a/dashboard/src/components/profiles/ProfileToolbar.tsx b/dashboard/src/components/profiles/ProfileToolbar.tsx
new file mode 100644
index 00000000..23aaa52c
--- /dev/null
+++ b/dashboard/src/components/profiles/ProfileToolbar.tsx
@@ -0,0 +1,89 @@
+import { useState } from "react";
+import { Button } from "../atoms";
+import type { Profile, Instance } from "../../generated/types";
+
+interface Props {
+ profile: Profile;
+ instance?: Instance;
+ onLaunch: () => void;
+ onStop: () => void;
+ onSave: () => void;
+ onDelete: () => void;
+ isSaveDisabled: boolean;
+}
+
+export default function ProfileToolbar({
+ profile,
+ instance,
+ onLaunch,
+ onStop,
+ onSave,
+ onDelete,
+ isSaveDisabled,
+}: Props) {
+ const [copyFeedback, setCopyFeedback] = useState("");
+ const isRunning = instance?.status === "running";
+
+ const handleCopyId = async () => {
+ if (!profile.id) return;
+ try {
+ await navigator.clipboard.writeText(profile.id);
+ setCopyFeedback("Copied");
+ setTimeout(() => setCopyFeedback(""), 2000);
+ } catch {
+ setCopyFeedback("Failed");
+ setTimeout(() => setCopyFeedback(""), 2000);
+ }
+ };
+
+ const headerMeta = [instance?.attached ? "CDP attached" : null].filter(
+ Boolean,
+ );
+
+ return (
+ <div className="flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between">
+ <div className="min-w-0">
+ <div className="flex flex-wrap items-center gap-3">
+ <h2 className="truncate text-lg font-semibold text-text-primary">
+ {profile.name}
+ </h2>
+ {headerMeta.length > 0 && (
+ <div className="text-sm text-text-muted">
+ {headerMeta.join(" Β· ")}
+ </div>
+ )}
+ </div>
+ {profile.useWhen?.trim() && (
+ <p className="mt-1 text-sm text-text-muted">{profile.useWhen}</p>
+ )}
+ </div>
+ <div className="flex shrink-0 flex-wrap gap-2">
+ {profile.id && (
+ <Button size="sm" variant="secondary" onClick={handleCopyId}>
+ {copyFeedback || "Copy ID"}
+ </Button>
+ )}
+ <Button size="sm" variant="secondary" onClick={onDelete}>
+ Delete
+ </Button>
+ <Button
+ size="sm"
+ variant="primary"
+ onClick={onSave}
+ disabled={isSaveDisabled}
+ >
+ Save
+ </Button>
+ {isRunning ? (
+ <Button size="sm" variant="danger" onClick={onStop}>
+ Stop
+ </Button>
+ ) : (
+ <Button size="sm" variant="primary" onClick={onLaunch}>
+ Start
+ </Button>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/dashboard/src/components/molecules/ScreencastTile.test.tsx b/dashboard/src/components/screencast/ScreencastTile.test.tsx
similarity index 95%
rename from dashboard/src/components/molecules/ScreencastTile.test.tsx
rename to dashboard/src/components/screencast/ScreencastTile.test.tsx
index 280c3eb0..cff589ba 100644
--- a/dashboard/src/components/molecules/ScreencastTile.test.tsx
+++ b/dashboard/src/components/screencast/ScreencastTile.test.tsx
@@ -1,6 +1,6 @@
import { render, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import ScreencastTile from "./ScreencastTile";
+import ScreencastTile from "../screencast/ScreencastTile";
const webSocketMock = vi.fn(function MockWebSocket(
this: Record<string, unknown>,
diff --git a/dashboard/src/components/screencast/ScreencastTile.tsx b/dashboard/src/components/screencast/ScreencastTile.tsx
new file mode 100644
index 00000000..9f0c0c17
--- /dev/null
+++ b/dashboard/src/components/screencast/ScreencastTile.tsx
@@ -0,0 +1,291 @@
+import { useEffect, useRef, useState } from "react";
+import { addTokenToUrl } from "../../services/auth";
+import * as api from "../../services/api";
+
+interface Props {
+ instanceId: string;
+ tabId: string;
+ label: string;
+ url: string;
+ quality?: number;
+ maxWidth?: number;
+ fps?: number;
+ showTitle?: boolean;
+}
+
+type Status = "connecting" | "streaming" | "error";
+
+export default function ScreencastTile({
+ instanceId,
+ tabId,
+ label,
+ url,
+ quality = 30,
+ maxWidth = 800,
+ fps = 1,
+ showTitle = true,
+}: Props) {
+ const canvasRef = useRef<HTMLCanvasElement>(null);
+ const socketRef = useRef<WebSocket | null>(null);
+ const [status, setStatus] = useState<Status>("connecting");
+ const [fpsDisplay, setFpsDisplay] = useState("β€”");
+ const [sizeDisplay, setSizeDisplay] = useState("β€”");
+ const [localFps, setLocalFps] = useState(fps);
+ const [isCapturing, setIsCapturing] = useState(false);
+ const [isPdfGenerating, setIsPdfGenerating] = useState(false);
+ const [fallbackUrl, setFallbackUrl] = useState<string | null>(null);
+
+ // Reset local FPS when the tab changes to match the new tab's initial request
+ useEffect(() => {
+ setLocalFps(fps);
+ setStatus("connecting");
+ setFallbackUrl(null);
+ }, [tabId, fps]);
+
+ // Clean up static preview URL on unmount or tab change
+ useEffect(() => {
+ return () => {
+ if (fallbackUrl) {
+ URL.revokeObjectURL(fallbackUrl);
+ }
+ };
+ }, [fallbackUrl]);
+
+ const takeScreenshot = async () => {
+ if (isCapturing) return;
+ setIsCapturing(true);
+
+ try {
+ const blob = await api.fetchTabScreenshot(tabId, "png");
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement("a");
+ link.href = url;
+ link.download = `screenshot-${tabId}-${Date.now()}.png`;
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+ URL.revokeObjectURL(url);
+ } catch (e) {
+ console.error("Screenshot capture failed", e);
+ } finally {
+ setIsCapturing(false);
+ }
+ };
+
+ const downloadPdf = async () => {
+ if (isPdfGenerating) return;
+ setIsPdfGenerating(true);
+
+ try {
+ const blob = await api.fetchTabPdf(tabId);
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement("a");
+ link.href = url;
+ link.download = `page-${tabId}-${Date.now()}.pdf`;
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+ URL.revokeObjectURL(url);
+ } catch (e) {
+ console.error("PDF generation failed", e);
+ } finally {
+ setIsPdfGenerating(false);
+ }
+ };
+
+ const captureFallback = async () => {
+ try {
+ const blob = await api.fetchTabScreenshot(tabId, "png");
+ if (fallbackUrl) URL.revokeObjectURL(fallbackUrl);
+ setFallbackUrl(URL.createObjectURL(blob));
+ } catch (e) {
+ console.error("Fallback capture failed", e);
+ }
+ };
+
+ useEffect(() => {
+ const canvas = canvasRef.current;
+ if (!canvas) return;
+
+ const ctx = canvas.getContext("2d");
+ if (!ctx) return;
+
+ const params = new URLSearchParams({
+ tabId,
+ quality: String(quality),
+ maxWidth: String(maxWidth),
+ fps: String(localFps),
+ });
+ const path = addTokenToUrl(
+ `/instances/${encodeURIComponent(instanceId)}/proxy/screencast?${params.toString()}`,
+ );
+ const wsUrl = new URL(path, window.location.origin);
+ wsUrl.protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
+
+ const socket = new WebSocket(wsUrl.toString());
+ socket.binaryType = "arraybuffer";
+ socketRef.current = socket;
+
+ let frameCount = 0;
+ let lastFpsTime = Date.now();
+
+ socket.onopen = () => {
+ setStatus("streaming");
+ };
+
+ socket.onmessage = (evt) => {
+ const blob = new Blob([evt.data], { type: "image/jpeg" });
+ const imgUrl = URL.createObjectURL(blob);
+ const img = new Image();
+ img.onload = () => {
+ canvas.width = img.width;
+ canvas.height = img.height;
+ ctx.drawImage(img, 0, 0);
+ URL.revokeObjectURL(imgUrl);
+ };
+ img.src = imgUrl;
+
+ frameCount++;
+ const now = Date.now();
+ if (now - lastFpsTime >= 1000) {
+ setFpsDisplay(`${frameCount} fps`);
+ setSizeDisplay(`${(evt.data.byteLength / 1024).toFixed(0)} KB/frame`);
+ frameCount = 0;
+ lastFpsTime = now;
+ }
+ };
+
+ socket.onerror = () => {
+ setStatus("error");
+ };
+
+ socket.onclose = () => {
+ setStatus("error");
+ };
+
+ return () => {
+ socket.close();
+ socketRef.current = null;
+ };
+ }, [instanceId, tabId, quality, maxWidth, localFps]);
+
+ const statusColor =
+ status === "streaming"
+ ? "bg-success"
+ : status === "connecting"
+ ? "bg-warning"
+ : "bg-destructive";
+ return (
+ <div className="flex h-full flex-col overflow-hidden rounded-lg border border-border-subtle bg-bg-elevated">
+ {/* Header */}
+ {showTitle && (
+ <div className="flex shrink-0 items-center justify-between border-b border-border-subtle px-3 py-2">
+ <div className="flex items-center gap-2">
+ <span className="font-mono text-xs text-text-secondary">
+ {label}
+ </span>
+ <div className={`h-2 w-2 rounded-full ${statusColor}`} />
+ </div>
+ <span className="max-w-50 truncate text-xs text-text-muted">
+ {url}
+ </span>
+ </div>
+ )}
+ {/* Canvas */}
+ <div className="relative flex min-h-0 flex-1 items-center justify-center bg-black">
+ {status === "error" && fallbackUrl ? (
+ <img
+ src={fallbackUrl}
+ alt="Tab preview"
+ className="max-h-full max-w-full object-contain"
+ />
+ ) : (
+ <canvas
+ ref={canvasRef}
+ className="max-h-full max-w-full object-contain"
+ width={800}
+ height={600}
+ />
+ )}
+
+ {status === "error" && (
+ <div className="absolute inset-0 flex flex-col items-center justify-center gap-3 bg-black/80 text-sm text-text-primary backdrop-blur-[2px]">
+ <div className="font-semibold text-white drop-shadow-md">
+ Connection lost
+ </div>
+ <div className="flex gap-2">
+ {!fallbackUrl && (
+ <button
+ onClick={captureFallback}
+ className="rounded bg-white/10 px-3 py-1.5 font-medium shadow-lg backdrop-blur-md transition-colors hover:bg-white/20"
+ >
+ Show static preview
+ </button>
+ )}
+ <button
+ onClick={() => setStatus("connecting")}
+ className="rounded bg-primary/30 px-3 py-1.5 font-medium text-white shadow-lg backdrop-blur-md transition-colors hover:bg-primary/40"
+ >
+ Retry connection
+ </button>
+ </div>
+ </div>
+ )}
+ </div>
+ <div className="flex shrink-0 items-center justify-between border-t border-border-subtle px-3 py-1 text-xs text-text-muted">
+ <div className="flex items-center gap-3">
+ <div className="flex items-center overflow-hidden rounded border border-border-subtle bg-black/20">
+ <button
+ onClick={() => setLocalFps((prev) => Math.max(1, prev - 1))}
+ className="flex h-5 w-5 items-center justify-center hover:bg-white/5 active:bg-white/10"
+ title="Decrease FPS"
+ >
+ -
+ </button>
+ <div className="min-w-16 px-1.5 text-center font-mono text-[10px] text-text-secondary">
+ {localFps} FPS ({fpsDisplay})
+ </div>
+ <button
+ onClick={() => setLocalFps((prev) => Math.min(30, prev + 1))}
+ className="flex h-5 w-5 items-center justify-center hover:bg-white/5 active:bg-white/10"
+ title="Increase FPS"
+ >
+ +
+ </button>
+ </div>
+
+ <button
+ onClick={takeScreenshot}
+ disabled={isCapturing || status !== "streaming"}
+ className={`flex h-6 w-6 items-center justify-center rounded-md border border-border-subtle transition-colors hover:bg-white/5 disabled:opacity-50 ${
+ isCapturing ? "bg-primary/20" : "bg-black/20"
+ }`}
+ title="Take full quality screenshot (PNG)"
+ >
+ {isCapturing ? (
+ <span className="animate-pulse">βŒ›</span>
+ ) : (
+ <span>πŸ“Έ</span>
+ )}
+ </button>
+
+ <button
+ onClick={downloadPdf}
+ disabled={isPdfGenerating || status !== "streaming"}
+ className={`flex h-6 w-6 items-center justify-center rounded-md border border-border-subtle transition-colors hover:bg-white/5 disabled:opacity-50 ${
+ isPdfGenerating ? "bg-primary/20" : "bg-black/20"
+ }`}
+ title="Download as PDF"
+ >
+ {isPdfGenerating ? (
+ <span className="animate-pulse">βŒ›</span>
+ ) : (
+ <span>πŸ“„</span>
+ )}
+ </button>
+ </div>
+ <span>{sizeDisplay}</span>
+ </div>
+ </div>
+ );
+}
diff --git a/dashboard/src/components/tabs/IdBadge.test.tsx b/dashboard/src/components/tabs/IdBadge.test.tsx
new file mode 100644
index 00000000..07ede0c0
--- /dev/null
+++ b/dashboard/src/components/tabs/IdBadge.test.tsx
@@ -0,0 +1,51 @@
+import { render, screen, fireEvent, waitFor } from "@testing-library/react";
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import IdBadge from "./IdBadge";
+
+describe("IdBadge", () => {
+ const mockId = "tab_1234567890";
+
+ beforeEach(() => {
+ vi.stubGlobal("navigator", {
+ clipboard: {
+ writeText: vi.fn(),
+ },
+ });
+ });
+
+ it("renders shortened ID", () => {
+ render(<IdBadge id={mockId} />);
+ // Should split by _ and take the last part, shortened to 8 chars
+ expect(screen.getByText("12345678")).toBeInTheDocument();
+ });
+
+ it("renders full ID if no underscore", () => {
+ render(<IdBadge id="simpleid" />);
+ expect(screen.getByText("simpleid")).toBeInTheDocument();
+ });
+
+ it("copies full ID to clipboard on click", async () => {
+ render(<IdBadge id={mockId} />);
+ const button = screen.getByRole("button");
+ fireEvent.click(button);
+
+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith(mockId);
+
+ // Check for success emoji
+ expect(screen.getByText("βœ…")).toBeInTheDocument();
+
+ // Wait for it to reset (optional, but shows we understand the logic)
+ await waitFor(
+ () => {
+ expect(screen.queryByText("βœ…")).not.toBeInTheDocument();
+ },
+ { timeout: 2500 },
+ );
+ });
+
+ it("renders as div if not copyable", () => {
+ render(<IdBadge id={mockId} copyable={false} />);
+ expect(screen.queryByRole("button")).not.toBeInTheDocument();
+ expect(screen.getByText("12345678")).toBeInTheDocument();
+ });
+});
diff --git a/dashboard/src/components/tabs/IdBadge.tsx b/dashboard/src/components/tabs/IdBadge.tsx
new file mode 100644
index 00000000..e5741ba7
--- /dev/null
+++ b/dashboard/src/components/tabs/IdBadge.tsx
@@ -0,0 +1,40 @@
+import { useState } from "react";
+
+interface Props {
+ id: string;
+ copyable?: boolean;
+}
+
+export default function IdBadge({ id, copyable = true }: Props) {
+ const [copied, setCopied] = useState(false);
+
+ const handleCopy = (e: React.MouseEvent) => {
+ e.stopPropagation();
+ navigator.clipboard.writeText(id);
+ setCopied(true);
+ setTimeout(() => setCopied(false), 2000);
+ };
+
+ const shortId = id.split("_").pop()?.substring(0, 8) || id;
+
+ if (copyable) {
+ return (
+ <button
+ onClick={handleCopy}
+ title={`Click to copy full ID: ${id}`}
+ className="group flex shrink-0 items-center gap-1.5 rounded bg-bg-elevated px-1.5 py-0.5 text-[10px] font-mono text-text-muted transition-colors hover:bg-border-subtle hover:text-text-primary focus:outline-none"
+ >
+ <span>{shortId}</span>
+ <span className="text-[8px] opacity-0 transition-opacity group-hover:opacity-100">
+ {copied ? "βœ…" : "πŸ“‹"}
+ </span>
+ </button>
+ );
+ }
+
+ return (
+ <div className="flex shrink-0 items-center gap-1.5 rounded bg-bg-elevated px-1.5 py-0.5 text-[10px] font-mono text-text-muted">
+ <span>{shortId}</span>
+ </div>
+ );
+}
diff --git a/dashboard/src/components/tabs/InstanceTabsPanel.test.tsx b/dashboard/src/components/tabs/InstanceTabsPanel.test.tsx
new file mode 100644
index 00000000..6dd14095
--- /dev/null
+++ b/dashboard/src/components/tabs/InstanceTabsPanel.test.tsx
@@ -0,0 +1,66 @@
+import { render, screen, within } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { describe, expect, it } from "vitest";
+import type { InstanceTab } from "../../generated/types";
+import InstanceTabsPanel from "./InstanceTabsPanel";
+
+const tabs: InstanceTab[] = [
+ {
+ id: "tab_alpha",
+ instanceId: "inst_123",
+ title: "Alpha Tab",
+ url: "https://example.com/alpha",
+ },
+ {
+ id: "tab_beta",
+ instanceId: "inst_123",
+ title: "Beta Tab",
+ url: "https://example.com/beta",
+ },
+];
+
+describe("InstanceTabsPanel", () => {
+ it("auto-selects the first tab and shows its details", () => {
+ render(<InstanceTabsPanel tabs={tabs} />);
+
+ expect(screen.getByText("Open Tabs (2)")).toBeInTheDocument();
+
+ // Find heading for first tab title
+ const titleHeading = screen.getByRole("heading", { name: "Alpha Tab" });
+ const detailPanel = titleHeading.closest(".rounded-xl") as HTMLElement;
+
+ expect(
+ within(detailPanel).getByText("https://example.com/alpha"),
+ ).toBeInTheDocument();
+
+ // IdBadge will show "alpha" instead of "tab_alpha"
+ expect(within(detailPanel).getByText("alpha")).toBeInTheDocument();
+ });
+
+ it("updates the selected tab details when a tab is clicked", async () => {
+ const user = userEvent.setup();
+ render(<InstanceTabsPanel tabs={tabs} />);
+
+ // Select Beta tab from list
+ const betaTabItem = screen
+ .getByText("Beta Tab")
+ .closest('[role="button"]')!;
+ await user.click(betaTabItem);
+
+ // Find heading for beta tab title
+ const titleHeading = screen.getByRole("heading", { name: "Beta Tab" });
+ const detailPanel = titleHeading.closest(".rounded-xl") as HTMLElement;
+
+ expect(
+ within(detailPanel).getByText("https://example.com/beta"),
+ ).toBeInTheDocument();
+ expect(within(detailPanel).getByText("beta")).toBeInTheDocument();
+ });
+
+ it("shows an empty state when there are no tabs", () => {
+ render(<InstanceTabsPanel tabs={[]} />);
+
+ expect(screen.getByText("Open Tabs (0)")).toBeInTheDocument();
+ expect(screen.getByText("No tabs open")).toBeInTheDocument();
+ });
+});
diff --git a/dashboard/src/components/tabs/InstanceTabsPanel.tsx b/dashboard/src/components/tabs/InstanceTabsPanel.tsx
new file mode 100644
index 00000000..2c56ed30
--- /dev/null
+++ b/dashboard/src/components/tabs/InstanceTabsPanel.tsx
@@ -0,0 +1,82 @@
+import { useEffect, useMemo, useState } from "react";
+import type { InstanceTab } from "../../generated/types";
+import TabItem from "./TabItem";
+import SelectedTabPanel from "./SelectedTabPanel";
+
+interface Props {
+ tabs: InstanceTab[];
+ emptyMessage?: string;
+ instanceId?: string;
+}
+
+export default function InstanceTabsPanel({
+ tabs,
+ emptyMessage = "No tabs open",
+ instanceId,
+}: Props) {
+ const [selectedTabId, setSelectedTabId] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (tabs.length === 0) {
+ setSelectedTabId(null);
+ return;
+ }
+
+ if (!tabs.some((tab) => tab.id === selectedTabId)) {
+ setSelectedTabId(tabs[0].id);
+ }
+ }, [selectedTabId, tabs]);
+
+ const selectedTab = useMemo(
+ () => tabs.find((tab) => tab.id === selectedTabId) ?? null,
+ [selectedTabId, tabs],
+ );
+
+ return (
+ <div className="flex flex-1 min-h-0 flex-col p-3">
+ <h4 className="mb-2 text-xs font-semibold uppercase tracking-wide text-text-muted">
+ Open Tabs ({tabs.length})
+ </h4>
+
+ {tabs.length === 0 ? (
+ <div className="py-8 text-center text-sm text-text-muted">
+ {emptyMessage}
+ </div>
+ ) : (
+ <div className="flex min-h-0 flex-1 flex-col gap-3 xl:flex-row">
+ <div className="min-h-0 overflow-auto xl:w-80 xl:shrink-0">
+ <div className="space-y-1">
+ {tabs.map((tab) => {
+ const isSelected = tab.id === selectedTabId;
+
+ return (
+ <div
+ key={tab.id}
+ role="button"
+ tabIndex={0}
+ onClick={() => setSelectedTabId(tab.id)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ setSelectedTabId(tab.id);
+ }
+ }}
+ className={`w-full rounded-xl border text-left transition ${
+ isSelected
+ ? "border-primary bg-primary/10"
+ : "border-border-subtle bg-white/2 hover:border-border-default hover:bg-white/3"
+ }`}
+ >
+ <TabItem tab={tab} />
+ </div>
+ );
+ })}
+ </div>
+ </div>
+
+ <SelectedTabPanel selectedTab={selectedTab} instanceId={instanceId} />
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/dashboard/src/components/tabs/SelectedTabPanel.tsx b/dashboard/src/components/tabs/SelectedTabPanel.tsx
new file mode 100644
index 00000000..23ee371e
--- /dev/null
+++ b/dashboard/src/components/tabs/SelectedTabPanel.tsx
@@ -0,0 +1,86 @@
+import { useState } from "react";
+import type { InstanceTab } from "../../generated/types";
+import IdBadge from "./IdBadge";
+import { TabsLayout, EmptyView } from "../molecules";
+import ScreencastTile from "../screencast/ScreencastTile";
+
+interface Props {
+ selectedTab: InstanceTab | null;
+ instanceId?: string;
+}
+
+type SubTabId = "actions" | "live" | "console" | "errors";
+
+export default function SelectedTabPanel({ selectedTab, instanceId }: Props) {
+ const [activeSubTab, setActiveSubTab] = useState<SubTabId>("live");
+
+ const subTabs: { id: SubTabId; label: string }[] = [
+ { id: "live", label: "Live" },
+ { id: "actions", label: "Actions" },
+ { id: "console", label: "Console" },
+ { id: "errors", label: "Errors" },
+ ];
+
+ if (!selectedTab) {
+ return (
+ <div className="flex flex-1 rounded-xl border border-border-subtle bg-white/2">
+ <EmptyView message="Select a tab to view details" />
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex min-h-48 flex-1 flex-col rounded-xl border border-border-subtle bg-white/2 relative overflow-hidden">
+ <div className="border-b border-border-subtle bg-black/5 p-4">
+ <div className="flex items-center justify-between gap-4">
+ <div className="min-w-0 flex-1">
+ <h5 className="truncate text-base font-semibold text-text-primary">
+ {selectedTab.title || "Untitled"}
+ </h5>
+ <div className="mt-1 truncate text-xs text-text-muted">
+ {selectedTab.url}
+ </div>
+ </div>
+ <IdBadge id={selectedTab.id} />
+ </div>
+ </div>
+ <div className="flex-1 min-h-0">
+ <TabsLayout
+ tabs={subTabs}
+ activeTab={activeSubTab}
+ onChange={(id) => setActiveSubTab(id)}
+ >
+ {activeSubTab === "actions" && (
+ <EmptyView message="No actions available for this tab yet." />
+ )}
+ {activeSubTab === "live" && (
+ <div className="h-full">
+ {instanceId ? (
+ <div className="flex h-full items-center justify-center">
+ <div className="h-full w-full">
+ <ScreencastTile
+ key={selectedTab.id}
+ instanceId={instanceId}
+ tabId={selectedTab.id}
+ label={selectedTab.title || selectedTab.id.slice(0, 8)}
+ url={selectedTab.url}
+ showTitle={false}
+ />
+ </div>
+ </div>
+ ) : (
+ <EmptyView message="No instance ID provided for live view." />
+ )}
+ </div>
+ )}
+ {activeSubTab === "console" && (
+ <EmptyView message="Console logs for this tab will appear here." />
+ )}
+ {activeSubTab === "errors" && (
+ <EmptyView message="Runtime errors for this tab will appear here." />
+ )}
+ </TabsLayout>
+ </div>
+ </div>
+ );
+}
diff --git a/dashboard/src/components/tabs/TabItem.tsx b/dashboard/src/components/tabs/TabItem.tsx
new file mode 100644
index 00000000..74a4e5a2
--- /dev/null
+++ b/dashboard/src/components/tabs/TabItem.tsx
@@ -0,0 +1,18 @@
+import type { InstanceTab } from "../../generated/types";
+
+interface Props {
+ tab: InstanceTab;
+}
+
+export default function TabItem({ tab }: Props) {
+ return (
+ <div className="rounded-md border border-border-subtle/80 bg-white/2 px-3 py-2.5 transition-colors hover:border-border-default hover:bg-white/[0.03]">
+ <div className="truncate text-sm font-medium text-text-primary">
+ {tab.title || "Untitled"}
+ </div>
+ <div className="mt-1 line-clamp-2 text-xs text-text-muted opacity-80 break-all">
+ {tab.url}
+ </div>
+ </div>
+ );
+}
diff --git a/dashboard/src/components/tabs/index.ts b/dashboard/src/components/tabs/index.ts
new file mode 100644
index 00000000..92948ece
--- /dev/null
+++ b/dashboard/src/components/tabs/index.ts
@@ -0,0 +1,4 @@
+export { default as InstanceTabsPanel } from "./InstanceTabsPanel";
+export { default as SelectedTabPanel } from "./SelectedTabPanel";
+export { default as TabItem } from "./TabItem";
+export { default as IdBadge } from "./IdBadge";
diff --git a/dashboard/src/pages/MonitoringPage.test.tsx b/dashboard/src/pages/MonitoringPage.test.tsx
new file mode 100644
index 00000000..17331852
--- /dev/null
+++ b/dashboard/src/pages/MonitoringPage.test.tsx
@@ -0,0 +1,95 @@
+import { render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { MemoryRouter, Route, Routes, useLocation } from "react-router-dom";
+import MonitoringPage from "./MonitoringPage";
+import { useAppStore } from "../stores/useAppStore";
+import type { Instance } from "../generated/types";
+
+vi.mock("../services/api", () => ({
+ stopInstance: vi.fn(),
+}));
+
+vi.mock("../components/molecules", () => ({
+ TabsChart: () => <div>Tabs Chart</div>,
+ InstanceListItem: ({
+ instance,
+ onClick,
+ }: {
+ instance: Instance;
+ onClick: () => void;
+ }) => <button onClick={onClick}>{instance.profileName}</button>,
+ InstanceTabsPanel: ({ tabs }: { tabs: { title: string }[] }) => (
+ <div>Tabs Panel ({tabs.length})</div>
+ ),
+}));
+
+const instances: Instance[] = [
+ {
+ id: "inst_beta",
+ profileId: "prof_beta",
+ profileName: "beta",
+ port: "9988",
+ headless: false,
+ status: "running",
+ startTime: "2026-03-06T10:00:00Z",
+ attached: false,
+ },
+];
+
+function ProfilesRouteProbe() {
+ const location = useLocation();
+ const state = location.state as { selectedProfileKey?: string } | null;
+
+ return (
+ <div>
+ <div>Profiles Route</div>
+ <div>{state?.selectedProfileKey ?? "missing"}</div>
+ </div>
+ );
+}
+
+describe("MonitoringPage", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ useAppStore.setState({
+ instances,
+ tabsChartData: [],
+ memoryChartData: [],
+ serverChartData: [],
+ currentTabs: {
+ inst_beta: [],
+ },
+ currentMemory: {},
+ settings: {
+ ...useAppStore.getState().settings,
+ monitoring: {
+ ...useAppStore.getState().settings.monitoring,
+ memoryMetrics: false,
+ },
+ },
+ });
+ });
+
+ it("opens the selected profile from the active instance header", async () => {
+ render(
+ <MemoryRouter initialEntries={["/dashboard/monitoring"]}>
+ <Routes>
+ <Route path="/dashboard/monitoring" element={<MonitoringPage />} />
+ <Route path="/dashboard/profiles" element={<ProfilesRouteProbe />} />
+ </Routes>
+ </MemoryRouter>,
+ );
+
+ await waitFor(() => {
+ expect(screen.getByRole("heading", { name: "beta" })).toBeInTheDocument();
+ });
+
+ await userEvent.click(screen.getByRole("button", { name: "Open Profile" }));
+
+ await waitFor(() => {
+ expect(screen.getByText("Profiles Route")).toBeInTheDocument();
+ });
+ expect(screen.getByText("prof_beta")).toBeInTheDocument();
+ });
+});
diff --git a/dashboard/src/pages/MonitoringPage.tsx b/dashboard/src/pages/MonitoringPage.tsx
index bc2694e6..349dc781 100644
--- a/dashboard/src/pages/MonitoringPage.tsx
+++ b/dashboard/src/pages/MonitoringPage.tsx
@@ -1,7 +1,10 @@
import { useEffect, useState } from "react";
+import { useNavigate } from "react-router-dom";
import { useAppStore } from "../stores/useAppStore";
import { EmptyState, Button, ErrorBoundary } from "../components/atoms";
-import { TabsChart, InstanceListItem, TabItem } from "../components/molecules";
+import { TabsChart } from "../components/molecules";
+import InstanceListItem from "../components/instances/InstanceListItem";
+import InstanceTabsPanel from "../components/tabs/InstanceTabsPanel";
import * as api from "../services/api";
export default function MonitoringPage() {
@@ -14,6 +17,7 @@ export default function MonitoringPage() {
currentMemory,
settings,
} = useAppStore();
+ const navigate = useNavigate();
const [selectedId, setSelectedId] = useState<string | null>(null);
const memoryEnabled = settings.monitoring?.memoryMetrics ?? false;
@@ -116,34 +120,37 @@ export default function MonitoringPage() {
{selectedInstance.headless ? "Headless" : "Headed"}
</div>
</div>
- {selectedInstance.status === "running" && (
+ <div className="flex items-center gap-2">
<Button
size="sm"
- variant="danger"
- onClick={() => handleStop(selectedInstance.id)}
+ variant="secondary"
+ onClick={() =>
+ navigate("/dashboard/profiles", {
+ state: {
+ selectedProfileKey:
+ selectedInstance.profileId ||
+ selectedInstance.profileName,
+ },
+ })
+ }
>
- Stop
+ Open Profile
</Button>
- )}
- </div>
-
- {/* Tabs list */}
- <div className="flex-1 overflow-auto p-3">
- <h4 className="mb-2 text-xs font-semibold uppercase tracking-wide text-text-muted">
- Open Tabs ({selectedTabs.length})
- </h4>
- {selectedTabs.length === 0 ? (
- <div className="py-8 text-center text-sm text-text-muted">
- No tabs open
- </div>
- ) : (
- <div className="space-y-1">
- {selectedTabs.map((tab) => (
- <TabItem key={tab.id} tab={tab} />
- ))}
- </div>
- )}
+ {selectedInstance.status === "running" && (
+ <Button
+ size="sm"
+ variant="danger"
+ onClick={() => handleStop(selectedInstance.id)}
+ >
+ Stop
+ </Button>
+ )}
+ </div>
</div>
+ <InstanceTabsPanel
+ tabs={selectedTabs}
+ instanceId={selectedId || undefined}
+ />
</>
) : (
<div className="flex flex-1 items-center justify-center text-sm text-text-muted">
diff --git a/dashboard/src/pages/ProfilesPage.test.tsx b/dashboard/src/pages/ProfilesPage.test.tsx
index 37f6ec51..69b69f1b 100644
--- a/dashboard/src/pages/ProfilesPage.test.tsx
+++ b/dashboard/src/pages/ProfilesPage.test.tsx
@@ -1,6 +1,7 @@
import { render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { beforeEach, describe, expect, it, vi } from "vitest";
+import { MemoryRouter } from "react-router-dom";
import ProfilesPage from "./ProfilesPage";
import { useAppStore } from "../stores/useAppStore";
import type { Instance, Profile } from "../generated/types";
@@ -53,6 +54,14 @@ const instances: Instance[] = [
},
];
+function renderProfilesPage() {
+ return render(
+ <MemoryRouter>
+ <ProfilesPage />
+ </MemoryRouter>,
+ );
+}
+
describe("ProfilesPage", () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -63,65 +72,66 @@ describe("ProfilesPage", () => {
});
});
- it("auto-selects the first profile and renders its details", async () => {
- render(<ProfilesPage />);
+ it("moves the running profile to the top and auto-selects it", async () => {
+ renderProfilesPage();
let detailPanel: HTMLElement;
await waitFor(() => {
detailPanel = screen
- .getByRole("heading", { name: "alpha" })
+ .getByRole("heading", { name: "beta" })
.closest(".dashboard-panel") as HTMLElement;
expect(detailPanel).toBeInTheDocument();
});
+ const [firstProfileButton, secondProfileButton] = screen.getAllByRole(
+ "button",
+ { name: /alpha|beta/i },
+ );
+ expect(firstProfileButton).toHaveTextContent("beta");
+ expect(secondProfileButton).toHaveTextContent("alpha");
+
detailPanel = screen
- .getByRole("heading", { name: "alpha" })
+ .getByRole("heading", { name: "beta" })
.closest(".dashboard-panel") as HTMLElement;
expect(
- within(detailPanel).getAllByText("Use for personal logins").length,
+ within(detailPanel).getAllByText("[email protected]").length,
).toBeGreaterThan(0);
- expect(
- within(detailPanel).getByRole("button", { name: "Start" }),
- ).toBeInTheDocument();
+ expect(within(detailPanel).getByText("running")).toBeInTheDocument();
+ expect(within(detailPanel).getByText("9988")).toBeInTheDocument();
});
it("switches the right detail pane when selecting another profile", async () => {
- render(<ProfilesPage />);
+ renderProfilesPage();
await waitFor(() => {
- expect(
- screen.getByRole("heading", { name: "alpha" }),
- ).toBeInTheDocument();
+ expect(screen.getByRole("heading", { name: "beta" })).toBeInTheDocument();
});
- await userEvent.click(screen.getByRole("button", { name: /beta/i }));
+ await userEvent.click(screen.getByRole("button", { name: /alpha/i }));
const detailPanel = screen
- .getByRole("heading", { name: "beta" })
+ .getByRole("heading", { name: "alpha" })
.closest(".dashboard-panel") as HTMLElement;
expect(detailPanel).toBeInTheDocument();
expect(
- within(detailPanel).getAllByText("[email protected]").length,
+ within(detailPanel).getAllByText("Use for personal logins").length,
).toBeGreaterThan(0);
expect(
- within(detailPanel).getByText("Running on :9988"),
- ).toBeInTheDocument();
- expect(
- within(detailPanel).getByRole("button", { name: "Stop" }),
+ within(detailPanel).getByRole("button", { name: "Start" }),
).toBeInTheDocument();
});
it("enables save only after profile fields change", async () => {
- render(<ProfilesPage />);
+ renderProfilesPage();
await waitFor(() => {
- expect(
- screen.getByRole("heading", { name: "alpha" }),
- ).toBeInTheDocument();
+ expect(screen.getByRole("heading", { name: "beta" })).toBeInTheDocument();
});
+ await userEvent.click(screen.getByRole("button", { name: /alpha/i }));
+
const detailPanel = screen
.getByRole("heading", { name: "alpha" })
.closest(".dashboard-panel") as HTMLElement;
diff --git a/dashboard/src/pages/ProfilesPage.tsx b/dashboard/src/pages/ProfilesPage.tsx
index 739109e6..0043d4a3 100644
--- a/dashboard/src/pages/ProfilesPage.tsx
+++ b/dashboard/src/pages/ProfilesPage.tsx
@@ -1,22 +1,25 @@
import { useEffect, useState, useMemo } from "react";
+import { useLocation } from "react-router-dom";
import { useAppStore } from "../stores/useAppStore";
+import { Toolbar, EmptyState, Button, Badge } from "../components/atoms";
import {
- Toolbar,
- EmptyState,
- Button,
- Modal,
- Input,
- Badge,
-} from "../components/atoms";
-import { ProfileDetailsPanel } from "../components/molecules";
+ CreateProfileModal,
+ ProfileDetailsPanel,
+ StartInstanceModal,
+} from "../components/molecules";
import * as api from "../services/api";
-import type { LaunchInstanceRequest, Profile } from "../generated/types";
+import type { Profile } from "../generated/types";
function getProfileKey(profile: Profile) {
return profile.id || profile.name;
}
+interface ProfilesLocationState {
+ selectedProfileKey?: string;
+}
+
export default function ProfilesPage() {
+ const location = useLocation();
const {
profiles,
instances,
@@ -26,22 +29,13 @@ export default function ProfilesPage() {
setInstances,
} = useAppStore();
const [showCreate, setShowCreate] = useState(false);
- const [showLaunch, setShowLaunch] = useState<string | null>(null);
+ const [launchProfileKey, setLaunchProfileKey] = useState<string | null>(null);
const [selectedProfileKey, setSelectedProfileKey] = useState<string | null>(
null,
);
- // Create form
- const [createName, setCreateName] = useState("");
- const [createUseWhen, setCreateUseWhen] = useState("");
- const [createSource, setCreateSource] = useState("");
-
- // Launch form
- const [launchPort, setLaunchPort] = useState("");
- const [launchHeadless, setLaunchHeadless] = useState(false);
- const [launchError, setLaunchError] = useState("");
- const [launchLoading, setLaunchLoading] = useState(false);
- const [copyFeedback, setCopyFeedback] = useState("");
+ const locationState = location.state as ProfilesLocationState | null;
+ const routeSelectedProfileKey = locationState?.selectedProfileKey ?? null;
const loadProfiles = async (preferredProfileKey?: string) => {
setProfilesLoading(true);
@@ -68,55 +62,25 @@ export default function ProfilesPage() {
// Load once on mount if empty β€” SSE handles updates
useEffect(() => {
if (profiles.length === 0) {
- loadProfiles();
+ loadProfiles(routeSelectedProfileKey ?? undefined);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
- const handleCreate = async () => {
- if (!createName.trim()) return;
- try {
- const created = await api.createProfile({
- name: createName.trim(),
- useWhen: createUseWhen.trim() || undefined,
- });
- setShowCreate(false);
- setCreateName("");
- setCreateUseWhen("");
- setCreateSource("");
- loadProfiles(created.id || created.name);
- } catch (e) {
- console.error("Failed to create profile", e);
+ useEffect(() => {
+ if (!routeSelectedProfileKey || profiles.length === 0) {
+ return;
}
- };
- const handleLaunch = async () => {
- if (!showLaunch || launchLoading) return;
- setLaunchError("");
- setLaunchLoading(true);
- try {
- const payload: LaunchInstanceRequest = {
- name: showLaunch,
- port: launchPort.trim() || undefined,
- mode: launchHeadless ? undefined : "headed",
- };
- console.log("Launching instance:", payload);
- const result = await api.launchInstance(payload);
- console.log("Launch result:", result);
- setShowLaunch(null);
- setLaunchPort("");
- setLaunchHeadless(false);
- // Refresh instances list
- const updated = await api.fetchInstances();
- setInstances(updated);
- } catch (e) {
- console.error("Launch failed:", e);
- const msg = e instanceof Error ? e.message : "Failed to launch instance";
- setLaunchError(msg);
- } finally {
- setLaunchLoading(false);
+ const preferred = profiles.find(
+ (profile) =>
+ getProfileKey(profile) === routeSelectedProfileKey ||
+ profile.name === routeSelectedProfileKey,
+ );
+ if (preferred && getProfileKey(preferred) !== selectedProfileKey) {
+ setSelectedProfileKey(getProfileKey(preferred));
}
- };
+ }, [profiles, routeSelectedProfileKey, selectedProfileKey]);
const handleStop = async (profileName: string) => {
const inst = instanceByProfile.get(profileName);
@@ -154,52 +118,61 @@ export default function ProfilesPage() {
}
};
- // Generate launch command
- const launchCommand = useMemo(() => {
- if (!showLaunch) return "";
- const profile = profiles.find((p) => p.name === showLaunch);
- const profileId = profile?.id || showLaunch;
- const payload: LaunchInstanceRequest = {
- profileId,
- mode: launchHeadless ? undefined : "headed",
- port: launchPort.trim() || undefined,
- };
-
- return `curl -X POST http://localhost:9867/instances/start -H "Content-Type: application/json" -d '${JSON.stringify(payload)}'`;
- }, [showLaunch, launchHeadless, launchPort, profiles]);
+ const instanceByProfile = useMemo(
+ () => new Map(instances.map((i) => [i.profileName, i])),
+ [instances],
+ );
+ const orderedProfiles = useMemo(() => {
+ const running: Profile[] = [];
+ const stopped: Profile[] = [];
- const handleCopyCommand = async () => {
- try {
- await navigator.clipboard.writeText(launchCommand);
- setCopyFeedback("Copied!");
- setTimeout(() => setCopyFeedback(""), 2000);
- } catch {
- setCopyFeedback("Failed to copy");
- setTimeout(() => setCopyFeedback(""), 2000);
- }
- };
+ profiles.forEach((profile) => {
+ if (instanceByProfile.get(profile.name)?.status === "running") {
+ running.push(profile);
+ return;
+ }
+ stopped.push(profile);
+ });
- const instanceByProfile = new Map(instances.map((i) => [i.profileName, i]));
+ return [...running, ...stopped];
+ }, [instanceByProfile, profiles]);
+ const runningProfileKeys = orderedProfiles
+ .filter(
+ (profile) => instanceByProfile.get(profile.name)?.status === "running",
+ )
+ .map((profile) => getProfileKey(profile));
+ const singleRunningProfileKey =
+ runningProfileKeys.length === 1 ? runningProfileKeys[0] : null;
const selectedProfile =
- profiles.find((profile) => getProfileKey(profile) === selectedProfileKey) ||
- null;
+ orderedProfiles.find(
+ (profile) => getProfileKey(profile) === selectedProfileKey,
+ ) || null;
+ const launchProfile =
+ orderedProfiles.find(
+ (profile) => getProfileKey(profile) === launchProfileKey,
+ ) || null;
const runningProfiles = instances.filter(
(instance) => instance.status === "running",
).length;
useEffect(() => {
- if (profiles.length === 0) {
+ if (orderedProfiles.length === 0) {
setSelectedProfileKey(null);
return;
}
- if (
- !selectedProfileKey ||
- !profiles.some((profile) => getProfileKey(profile) === selectedProfileKey)
- ) {
- setSelectedProfileKey(getProfileKey(profiles[0]));
+ const hasValidSelection =
+ !!selectedProfileKey &&
+ orderedProfiles.some(
+ (profile) => getProfileKey(profile) === selectedProfileKey,
+ );
+
+ if (!hasValidSelection) {
+ setSelectedProfileKey(
+ singleRunningProfileKey ?? getProfileKey(orderedProfiles[0]),
+ );
}
- }, [profiles, selectedProfileKey]);
+ }, [orderedProfiles, selectedProfileKey, singleRunningProfileKey]);
return (
<div className="flex h-full flex-col">
@@ -250,7 +223,7 @@ export default function ProfilesPage() {
<div className="flex-1 overflow-auto p-2">
<div className="space-y-2">
- {profiles.map((profile) => {
+ {orderedProfiles.map((profile) => {
const instance = instanceByProfile.get(profile.name);
const isSelected =
getProfileKey(profile) === selectedProfileKey;
@@ -317,7 +290,8 @@ export default function ProfilesPage() {
: undefined
}
onLaunch={() =>
- selectedProfile && setShowLaunch(selectedProfile.name)
+ selectedProfile &&
+ setLaunchProfileKey(getProfileKey(selectedProfile))
}
onStop={() =>
selectedProfile && handleStop(selectedProfile.name)
@@ -331,126 +305,17 @@ export default function ProfilesPage() {
</div>
</div>
- {/* Create Profile Modal */}
- <Modal
+ <CreateProfileModal
open={showCreate}
onClose={() => setShowCreate(false)}
- title="πŸ“ New Profile"
- wide
- actions={
- <>
- <Button variant="secondary" onClick={() => setShowCreate(false)}>
- Cancel
- </Button>
- <Button
- variant="primary"
- onClick={handleCreate}
- disabled={!createName.trim()}
- >
- Create
- </Button>
- </>
- }
- >
- <div className="flex flex-col gap-4">
- <Input
- label="Name"
- placeholder="e.g. personal, work, scraping"
- value={createName}
- onChange={(e) => setCreateName(e.target.value)}
- />
- <Input
- label="Use this profile when (helps agents pick the right profile)"
- placeholder="e.g. I need to access Gmail for the team account"
- value={createUseWhen}
- onChange={(e) => setCreateUseWhen(e.target.value)}
- />
- <Input
- label="Import from (optional β€” Chrome user data path)"
- placeholder="e.g. /Users/you/Library/Application Support/Google/Chrome"
- value={createSource}
- onChange={(e) => setCreateSource(e.target.value)}
- />
- </div>
- </Modal>
-
- {/* Launch Modal */}
- <Modal
- open={!!showLaunch}
- onClose={() => {
- setShowLaunch(null);
- setLaunchError("");
- }}
- title="πŸ–₯️ Start Profile"
- actions={
- <>
- <Button
- variant="secondary"
- disabled={launchLoading}
- onClick={() => {
- setShowLaunch(null);
- setLaunchError("");
- }}
- >
- Cancel
- </Button>
- <Button
- variant="primary"
- onClick={handleLaunch}
- loading={launchLoading}
- >
- Start
- </Button>
- </>
- }
- >
- <div className="flex flex-col gap-4">
- {launchError && (
- <div className="rounded border border-destructive/50 bg-destructive/10 px-3 py-2 text-sm text-destructive">
- {launchError}
- </div>
- )}
- <Input
- label="Port"
- placeholder="Auto-select from configured range"
- value={launchPort}
- onChange={(e) => setLaunchPort(e.target.value)}
- />
- <p className="-mt-2 text-xs text-text-muted">
- Leave blank to auto-select a free port from the configured instance
- port range.
- </p>
- <label className="flex items-center gap-2 text-sm text-text-secondary">
- <input
- type="checkbox"
- checked={launchHeadless}
- onChange={(e) => setLaunchHeadless(e.target.checked)}
- className="h-4 w-4"
- />
- Headless (best for Docker/VPS)
- </label>
+ onCreated={loadProfiles}
+ />
- {/* Command */}
- <div>
- <label className="mb-1 block text-xs text-text-muted">
- Direct launch command (backup)
- </label>
- <textarea
- readOnly
- value={launchCommand}
- className="h-20 w-full resize-none rounded border border-border-subtle bg-bg-elevated px-3 py-2 font-mono text-xs text-text-secondary"
- />
- <div className="mt-2 flex items-center gap-2">
- <Button size="sm" variant="secondary" onClick={handleCopyCommand}>
- Copy Command
- </Button>
- {copyFeedback && (
- <span className="text-xs text-success">{copyFeedback}</span>
- )}
- </div>
- </div>
- </div>
- </Modal>
+ <StartInstanceModal
+ open={!!launchProfile}
+ profile={launchProfile}
+ onClose={() => setLaunchProfileKey(null)}
+ />
</div>
);
}
diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.ts
index a78f7a8b..df127dd0 100644
--- a/dashboard/src/services/api.ts
+++ b/dashboard/src/services/api.ts
@@ -93,6 +93,36 @@ async function requestText(
return res.text();
}
+async function requestBlob(
+ url: string,
+ options?: RequestInit,
+ meta?: RequestMeta,
+): Promise<Blob> {
+ const headers = new Headers(options?.headers ?? {});
+ const token = meta?.authToken?.trim() || getStoredAuthToken();
+ if (token) {
+ headers.set("Authorization", `Bearer ${token}`);
+ }
+
+ const res = await fetch(BASE + url, {
+ ...options,
+ headers,
+ });
+ if (!res.ok) {
+ const err = await res.json().catch(() => ({ error: res.statusText }));
+ if (
+ res.status === 401 &&
+ !meta?.suppressAuthRedirect &&
+ typeof window !== "undefined"
+ ) {
+ window.localStorage.removeItem("pinchtab.auth.token");
+ dispatchAuthRequired(err.code || "unauthorized");
+ }
+ throw new Error(err.error || "Request failed");
+ }
+ return res.blob();
+}
+
// Profiles β€” endpoint is /profiles (no /api prefix)
export async function fetchProfiles(): Promise<Profile[]> {
return request<Profile[]>("/profiles");
@@ -166,6 +196,19 @@ export async function fetchInstanceLogs(id: string): Promise<string> {
return requestText(`/instances/${encodeURIComponent(id)}/logs`);
}
+export async function fetchTabScreenshot(
+ tabId: string,
+ format: "jpeg" | "png" = "jpeg",
+): Promise<Blob> {
+ return requestBlob(
+ `/tabs/${encodeURIComponent(tabId)}/screenshot?raw=true&format=${format}`,
+ );
+}
+
+export async function fetchTabPdf(tabId: string): Promise<Blob> {
+ return requestBlob(`/tabs/${encodeURIComponent(tabId)}/pdf?raw=true`);
+}
+
export function subscribeToInstanceLogs(
id: string,
handlers: { onLogs?: (logs: string) => void },
diff --git a/dev b/dev
index aa42337c..c84541ca 100755
--- a/dev
+++ b/dev
@@ -21,7 +21,8 @@ COMMANDS=(
"dev:πŸš€:Build & run"
"run:πŸƒ:Run the application"
"check:πŸ§ͺ:All checks"
- "test:πŸ”¬:Unit tests"
+ "test unit:πŸ”¬:Go unit tests"
+ "test dashboard:πŸ”¬:Dashboard unit tests"
"e2e:🐳:E2E tests"
" recent:🐳:E2E Recent tests"
" curl:🐳:E2E Curl tests"
@@ -112,12 +113,22 @@ run_command() {
echo ""
exec bash scripts/test.sh all
;;
- "test unit"|"unit")
+ "test unit")
+ echo " ${ACCENT}${BOLD}πŸ”¬ Go unit tests${NC}"
+ echo ""
+ exec bash scripts/test.sh unit
+ ;;
+ "test dashboard")
+ echo " ${ACCENT}${BOLD}πŸ”¬ Dashboard tests${NC}"
+ echo ""
+ exec bash scripts/test.sh dashboard
+ ;;
+ "unit")
echo " ${ACCENT}${BOLD}πŸ”¬ Unit tests${NC}"
echo ""
exec bash scripts/test.sh unit
;;
- "test system"|"system")
+ "system")
echo " ${ACCENT}${BOLD}πŸ”¬ System tests${NC}"
echo ""
exec bash scripts/test.sh system
diff --git a/docs/commands.md b/docs/commands.md
index 3fea692b..6dd2ba20 100644
--- a/docs/commands.md
+++ b/docs/commands.md
@@ -92,7 +92,7 @@ pinchtab eval <expression> # Evaluate JavaScript
```
pinchtab screenshot # Take a screenshot (JPEG)
-pinchtab screenshot -o <path> # Save to specific path
+pinchtab screenshot -o <path> # Save to specific path (format based on extension)
pinchtab screenshot -q <0-100> # Set JPEG quality
pinchtab pdf # Export page as PDF
pinchtab pdf -o <path> # Save PDF to path
diff --git a/docs/mcp.md b/docs/mcp.md
index 885e46b1..d4dee0ec 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -84,7 +84,7 @@ Add to your Cursor MCP settings:
|------|-------------|
| `pinchtab_navigate` | Navigate to a URL |
| `pinchtab_snapshot` | Get accessibility tree snapshot |
-| `pinchtab_screenshot` | Take a screenshot (base64 PNG) |
+| `pinchtab_screenshot` | Take a screenshot (base64 JPEG or PNG) |
| `pinchtab_get_text` | Extract readable text content |
### Interaction (8 tools)
@@ -149,11 +149,12 @@ Get an accessibility tree snapshot of the page. This is the primary way agents u
### pinchtab_screenshot
-Capture a screenshot of the page.
+Capture a screenshot of the page. Defaults to JPEG.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `tabId` | string | No | Target tab |
+| `format` | string | No | `jpeg` (default) or `png` |
| `quality` | number | No | JPEG quality 0-100 |
### pinchtab_get_text
diff --git a/docs/reference/screenshot.md b/docs/reference/screenshot.md
index 2d775d13..9ffed9b9 100644
--- a/docs/reference/screenshot.md
+++ b/docs/reference/screenshot.md
@@ -1,12 +1,21 @@
# Screenshot
-Capture the current page as an image.
+Capture the current page as an image. Defaults to **JPEG** format.
```bash
+# Get raw PNG bytes
+curl "http://localhost:9867/screenshot?format=png&raw=true" > page.png
+
+# Get JSON with base64 JPEG (default)
+curl "http://localhost:9867/screenshot"
+
+# Save to server state directory
curl "http://localhost:9867/screenshot?output=file"
-# CLI Alternative
-pinchtab ss -o page.jpg
-# Response
+```
+
+## Response (JSON)
+
+```json
{
"path": "/path/to/state/screenshots/screenshot-20260308-120001.jpg",
"size": 34567,
@@ -15,10 +24,21 @@ pinchtab ss -o page.jpg
}
```
-Useful flags:
+## Useful flags
+
+### API Query Parameters
+
+- `format`: `jpeg` (default) or `png`.
+- `quality`: JPEG quality `0-100` (default: `80`). Ignored for PNG.
+- `raw`: `true` to return image bytes directly instead of JSON.
+- `output`: `file` to save to state directory.
+- `tabId`: Target a specific tab.
+
+### CLI
-- CLI: `-o`, `-q`, `--tab`
-- API query: `quality`, `raw`, `output=file`, `tabId`
+- `-o <path>`: Save to specific path.
+- `-q <0-100>`: Set JPEG quality.
+- `--tab <id>`: Target a specific tab.
## Related Pages
diff --git a/internal/handlers/screenshot.go b/internal/handlers/screenshot.go
index 5f7ea4ff..e125988a 100644
--- a/internal/handlers/screenshot.go
+++ b/internal/handlers/screenshot.go
@@ -56,13 +56,24 @@ func (h *Handlers) HandleScreenshot(w http.ResponseWriter, r *http.Request) {
}
}
+ format := page.CaptureScreenshotFormatJpeg
+ contentType := "image/jpeg"
+ ext := ".jpg"
+
+ if r.URL.Query().Get("format") == "png" {
+ format = page.CaptureScreenshotFormatPng
+ contentType = "image/png"
+ ext = ".png"
+ }
+
if err := chromedp.Run(tCtx,
chromedp.ActionFunc(func(ctx context.Context) error {
var err error
- buf, err = page.CaptureScreenshot().
- WithFormat(page.CaptureScreenshotFormatJpeg).
- WithQuality(int64(quality)).
- Do(ctx)
+ shot := page.CaptureScreenshot().WithFormat(format)
+ if format == page.CaptureScreenshotFormatJpeg {
+ shot = shot.WithQuality(int64(quality))
+ }
+ buf, err = shot.Do(ctx)
return err
}),
); err != nil {
@@ -78,7 +89,7 @@ func (h *Handlers) HandleScreenshot(w http.ResponseWriter, r *http.Request) {
}
timestamp := time.Now().Format("20060102-150405")
- filename := fmt.Sprintf("screenshot-%s.jpg", timestamp)
+ filename := fmt.Sprintf("screenshot-%s%s", timestamp, ext)
filePath := filepath.Join(screenshotDir, filename)
if err := os.WriteFile(filePath, buf, 0600); err != nil {
@@ -89,14 +100,14 @@ func (h *Handlers) HandleScreenshot(w http.ResponseWriter, r *http.Request) {
web.JSON(w, 200, map[string]any{
"path": filePath,
"size": len(buf),
- "format": "jpeg",
+ "format": string(format),
"timestamp": timestamp,
})
return
}
if r.URL.Query().Get("raw") == "true" {
- w.Header().Set("Content-Type", "image/jpeg")
+ w.Header().Set("Content-Type", contentType)
if _, err := w.Write(buf); err != nil {
slog.Error("screenshot write", "err", err)
}
@@ -104,7 +115,7 @@ func (h *Handlers) HandleScreenshot(w http.ResponseWriter, r *http.Request) {
}
web.JSON(w, 200, map[string]any{
- "format": "jpeg",
+ "format": string(format),
"base64": base64.StdEncoding.EncodeToString(buf),
})
}
diff --git a/internal/mcp/handlers.go b/internal/mcp/handlers.go
index 8a5edc0f..276e4678 100644
--- a/internal/mcp/handlers.go
+++ b/internal/mcp/handlers.go
@@ -148,6 +148,9 @@ func handleScreenshot(c *Client) func(context.Context, mcp.CallToolRequest) (*mc
if tabID := optString(r, "tabId"); tabID != "" {
q.Set("tabId", tabID)
}
+ if format := optString(r, "format"); format != "" {
+ q.Set("format", format)
+ }
if quality, ok := optFloat(r, "quality"); ok {
q.Set("quality", fmt.Sprintf("%d", int(quality)))
}
diff --git a/internal/mcp/tools.go b/internal/mcp/tools.go
index 41d9b14c..d374fbff 100644
--- a/internal/mcp/tools.go
+++ b/internal/mcp/tools.go
@@ -20,8 +20,9 @@ func allTools() []mcp.Tool {
mcp.WithString("selector", mcp.Description("CSS selector to scope the snapshot")),
),
mcp.NewTool("pinchtab_screenshot",
- mcp.WithDescription("Take a screenshot of the current page (returns base64 PNG)"),
+ mcp.WithDescription("Take a screenshot of the current page"),
mcp.WithString("tabId", mcp.Description("Target tab ID")),
+ mcp.WithString("format", mcp.Description("Image format: 'jpeg' (default) or 'png'")),
mcp.WithNumber("quality", mcp.Description("JPEG quality 0-100 (only for JPEG format)")),
),
mcp.NewTool("pinchtab_get_text",
diff --git a/scripts/run.sh b/scripts/run.sh
index ec4ab3ed..a8b51303 100755
--- a/scripts/run.sh
+++ b/scripts/run.sh
@@ -10,4 +10,9 @@ if [ ! -x ./pinchtab ]; then
exit 1
fi
+# Default to 'server' if no arguments are provided
+if [ $# -eq 0 ]; then
+ set -- server
+fi
+
exec ./pinchtab "$@"
diff --git a/scripts/test-dashboard.sh b/scripts/test-dashboard.sh
new file mode 100755
index 00000000..13c646cc
--- /dev/null
+++ b/scripts/test-dashboard.sh
@@ -0,0 +1,35 @@
+#!/bin/bash
+set -e
+
+# test-dashboard.sh β€” Run dashboard tests (matches CI: dashboard.yml)
+# Runs: vitest run
+
+cd "$(dirname "$0")/.."
+
+BOLD=$'\033[1m'
+ACCENT=$'\033[38;2;251;191;36m'
+SUCCESS=$'\033[38;2;0;229;204m'
+ERROR=$'\033[38;2;230;57;70m'
+NC=$'\033[0m'
+
+fail() { echo -e " ${ERROR}βœ—${NC} $1"; exit 1; }
+
+if [ ! -d "dashboard" ]; then
+ fail "Dashboard directory not found"
+fi
+
+cd dashboard
+
+# Use bun as in workflow
+if ! command -v bun &>/dev/null; then
+ fail "bun not found (required for dashboard tests)"
+fi
+
+if bun run test:run; then
+ echo ""
+ echo -e " ${SUCCESS}${BOLD}Dashboard tests passed!${NC}"
+ echo ""
+else
+ echo ""
+ fail "Dashboard tests failed"
+fi
diff --git a/scripts/test.sh b/scripts/test.sh
index f91f1b7a..05f07963 100755
--- a/scripts/test.sh
+++ b/scripts/test.sh
@@ -252,19 +252,26 @@ trap 'rm -rf "$TMPDIR_TEST"' EXIT
# ── Unit tests ───────────────────────────────────────────────────────
if [ "$SCOPE" = "all" ] || [ "$SCOPE" = "unit" ]; then
- section "Unit Tests"
+ section "test:πŸ”¬:go unit"
UNIT_JSON="$TMPDIR_TEST/unit.json"
if ! run_go_test_json "$UNIT_JSON" "unit" -p 1 -count=1 ./...; then
- fail "Unit tests"
+ fail "test:πŸ”¬:go unit"
test_summary "$UNIT_JSON" "Unit Test Results"
exit 1
fi
- ok "Unit tests"
+ ok "test:πŸ”¬:go unit"
test_summary "$UNIT_JSON" "Unit Test Results"
fi
+# ── Dashboard ────────────────────────────────────────────────────────
+
+if [ "$SCOPE" = "all" ] || [ "$SCOPE" = "dashboard" ]; then
+ section "test:πŸ”¬:dashboard"
+ ./scripts/test-dashboard.sh
+fi
+
# ── Summary ──────────────────────────────────────────────────────────
section "Summary"
diff --git a/skills/pinchtab/SKILL.md b/skills/pinchtab/SKILL.md
index 92aa3860..1c349257 100644
--- a/skills/pinchtab/SKILL.md
+++ b/skills/pinchtab/SKILL.md
@@ -215,7 +215,7 @@ Rules:
```bash
pinchtab screenshot
-pinchtab screenshot -o /tmp/pinchtab-page.jpg
+pinchtab screenshot -o /tmp/pinchtab-page.png # Format driven by extension
pinchtab screenshot -q 60
pinchtab pdf
pinchtab pdf -o /tmp/pinchtab-report.pdf
diff --git a/skills/pinchtab/references/api.md b/skills/pinchtab/references/api.md
index 37ed434b..d93be101 100644
--- a/skills/pinchtab/references/api.md
+++ b/skills/pinchtab/references/api.md
@@ -230,8 +230,12 @@ Sets files on `<input type=file>` elements via CDP. Fires `change` events. Selec
```bash
# CLI: pinchtab ss [-o file.jpg] [-q 80]
+# Returns raw JPEG (default)
curl "/screenshot?raw=true" -o screenshot.jpg
curl "/screenshot?raw=true&quality=50" -o screenshot.jpg
+
+# Returns raw PNG
+curl "/screenshot?raw=true&format=png" -o screenshot.png
```
## Evaluate JavaScript