Skip to content

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

ci: add dashboard CI workflow and pre-commit hooks

Bosch7839570fa5cd
diff --git a/.github/workflows/dashboard.yml b/.github/workflows/dashboard.yml
new file mode 100644
index 00000000..569f0e91
--- /dev/null
+++ b/.github/workflows/dashboard.yml
@@ -0,0 +1,69 @@
+name: Dashboard
+
+on:
+ push:
+ branches: [main]
+ paths:
+ - 'dashboard/**'
+ - '.github/workflows/dashboard.yml'
+ pull_request:
+ paths:
+ - 'dashboard/**'
+ - '.github/workflows/dashboard.yml'
+ workflow_dispatch:
+
+defaults:
+ run:
+ working-directory: dashboard
+
+jobs:
+ check:
+ name: Lint, Type Check & Test
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Setup Bun
+ uses: oven-sh/setup-bun@v2
+ with:
+ bun-version: latest
+
+ - name: Install dependencies
+ run: bun install --frozen-lockfile
+
+ - name: TypeScript check
+ run: bun run typecheck
+
+ - name: ESLint
+ run: bun run lint
+
+ - name: Prettier check
+ run: bun run format:check
+
+ - name: Run tests
+ run: bun run test:run
+
+ build:
+ name: Build
+ runs-on: ubuntu-latest
+ needs: check
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Setup Bun
+ uses: oven-sh/setup-bun@v2
+ with:
+ bun-version: latest
+
+ - name: Install dependencies
+ run: bun install --frozen-lockfile
+
+ - name: Build
+ run: bun run build
+
+ - name: Upload build artifacts
+ uses: actions/upload-artifact@v4
+ with:
+ name: dashboard-dist
+ path: dashboard/dist/
+ retention-days: 7
diff --git a/.gitignore b/.gitignore
index 57f90235..41a966ae 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,6 +7,8 @@ coverage.out
dist/
*.js
!scripts/**/*.js
+!dashboard/eslint.config.js
+!dashboard/vite.config.ts
!npm/bin/pinchtab
# React dashboard build output (generated by scripts/build-dashboard.sh)
internal/dashboard/dashboard/assets/
diff --git a/dashboard/eslint.config.js b/dashboard/eslint.config.js
new file mode 100644
index 00000000..c9d5a0c5
--- /dev/null
+++ b/dashboard/eslint.config.js
@@ -0,0 +1,37 @@
+import js from '@eslint/js'
+import globals from 'globals'
+import reactHooks from 'eslint-plugin-react-hooks'
+import reactRefresh from 'eslint-plugin-react-refresh'
+import tseslint from 'typescript-eslint'
+import { defineConfig, globalIgnores } from 'eslint/config'
+
+export default defineConfig([
+ globalIgnores(['dist', 'src/generated']),
+ {
+ files: ['**/*.{ts,tsx}'],
+ extends: [
+ js.configs.recommended,
+ tseslint.configs.recommended,
+ reactHooks.configs.flat.recommended,
+ reactRefresh.configs.vite,
+ ],
+ languageOptions: {
+ ecmaVersion: 2020,
+ globals: globals.browser,
+ },
+ rules: {
+ // Downgrade to warnings for existing code
+ 'react-hooks/exhaustive-deps': 'warn',
+ '@typescript-eslint/no-explicit-any': 'warn',
+ // This rule is too strict - setting state in effect is valid for form resets
+ 'react-hooks/set-state-in-effect': 'off',
+ },
+ },
+ // Allow any in test files
+ {
+ files: ['**/*.test.{ts,tsx}'],
+ rules: {
+ '@typescript-eslint/no-explicit-any': 'off',
+ },
+ },
+])
diff --git a/dashboard/package.json b/dashboard/package.json
index 8ed7ad0e..0267ff4d 100644
--- a/dashboard/package.json
+++ b/dashboard/package.json
@@ -7,9 +7,14 @@
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
+ "lint:fix": "eslint . --fix",
+ "format": "prettier --write 'src/**/*.{ts,tsx,css}'",
+ "format:check": "prettier --check 'src/**/*.{ts,tsx,css}'",
+ "typecheck": "tsc --noEmit",
"preview": "vite preview",
"test": "vitest",
- "test:run": "vitest run"
+ "test:run": "vitest run",
+ "check": "bun run typecheck && bun run lint && bun run format:check && bun run test:run"
},
"dependencies": {
"react": "^19.2.4",
diff --git a/dashboard/src/App.tsx b/dashboard/src/App.tsx
index 58659116..189a95fd 100644
--- a/dashboard/src/App.tsx
+++ b/dashboard/src/App.tsx
@@ -1,12 +1,17 @@
-import { useEffect } from 'react'
-import { HashRouter, Routes, Route, Navigate } from 'react-router-dom'
-import { useAppStore } from './stores/useAppStore'
-import { NavBar } from './components/molecules'
-import { MonitoringPage, ProfilesPage, AgentsPage, SettingsPage } from './pages'
-import * as api from './services/api'
+import { useEffect } from "react";
+import { HashRouter, Routes, Route, Navigate } from "react-router-dom";
+import { useAppStore } from "./stores/useAppStore";
+import { NavBar } from "./components/molecules";
+import {
+ MonitoringPage,
+ ProfilesPage,
+ AgentsPage,
+ SettingsPage,
+} from "./pages";
+import * as api from "./services/api";
function AppContent() {
- const { setInstances, setProfiles, setAgents } = useAppStore()
+ const { setInstances, setProfiles, setAgents } = useAppStore();
// Initial load
useEffect(() => {
@@ -15,42 +20,42 @@ function AppContent() {
const [instances, profiles] = await Promise.all([
api.fetchInstances(),
api.fetchProfiles(),
- ])
- setInstances(instances)
- setProfiles(profiles)
+ ]);
+ setInstances(instances);
+ setProfiles(profiles);
} catch (e) {
- console.error('Failed to load initial data', e)
+ console.error("Failed to load initial data", e);
}
- }
- load()
- }, [setInstances, setProfiles])
+ };
+ load();
+ }, [setInstances, setProfiles]);
// Subscribe to SSE events
useEffect(() => {
const unsubscribe = api.subscribeToEvents({
onInit: (agents) => {
- setAgents(agents)
+ setAgents(agents);
},
onSystem: async (event) => {
- console.log('System event:', event)
- if (event.type.startsWith('instance.')) {
+ console.log("System event:", event);
+ if (event.type.startsWith("instance.")) {
try {
- const instances = await api.fetchInstances()
- setInstances(instances)
- const profiles = await api.fetchProfiles()
- setProfiles(profiles)
+ const instances = await api.fetchInstances();
+ setInstances(instances);
+ const profiles = await api.fetchProfiles();
+ setProfiles(profiles);
} catch (e) {
- console.error('Failed to refresh after event', e)
+ console.error("Failed to refresh after event", e);
}
}
},
onAgent: (event) => {
- console.log('Agent event:', event)
+ console.log("Agent event:", event);
},
- })
+ });
- return unsubscribe
- }, [setInstances, setProfiles, setAgents])
+ return unsubscribe;
+ }, [setInstances, setProfiles, setAgents]);
return (
<div className="flex h-screen flex-col bg-bg-app">
@@ -65,7 +70,7 @@ function AppContent() {
</Routes>
</main>
</div>
- )
+ );
}
export default function App() {
@@ -73,5 +78,5 @@ export default function App() {
<HashRouter>
<AppContent />
</HashRouter>
- )
+ );
}
diff --git a/dashboard/src/components/atoms/Badge.test.tsx b/dashboard/src/components/atoms/Badge.test.tsx
index fb8213a3..17e33b93 100644
--- a/dashboard/src/components/atoms/Badge.test.tsx
+++ b/dashboard/src/components/atoms/Badge.test.tsx
@@ -1,46 +1,52 @@
-import { render, screen } from '@testing-library/react'
-import { describe, it, expect } from 'vitest'
-import Badge from './Badge'
+import { render, screen } from "@testing-library/react";
+import { describe, it, expect } from "vitest";
+import Badge from "./Badge";
-describe('Badge', () => {
- it('renders children', () => {
- render(<Badge>Status</Badge>)
- expect(screen.getByText('Status')).toBeInTheDocument()
- })
+describe("Badge", () => {
+ it("renders children", () => {
+ render(<Badge>Status</Badge>);
+ expect(screen.getByText("Status")).toBeInTheDocument();
+ });
- it('applies default variant styles', () => {
- render(<Badge>Default</Badge>)
- const badge = screen.getByText('Default')
- expect(badge).toHaveClass('bg-bg-elevated', 'text-text-secondary')
- })
+ it("applies default variant styles", () => {
+ render(<Badge>Default</Badge>);
+ const badge = screen.getByText("Default");
+ expect(badge).toHaveClass("bg-bg-elevated", "text-text-secondary");
+ });
- it('applies success variant styles', () => {
- render(<Badge variant="success">Running</Badge>)
- const badge = screen.getByText('Running')
- expect(badge).toHaveClass('text-success')
- })
+ it("applies success variant styles", () => {
+ render(<Badge variant="success">Running</Badge>);
+ const badge = screen.getByText("Running");
+ expect(badge).toHaveClass("text-success");
+ });
- it('applies danger variant styles', () => {
- render(<Badge variant="danger">Error</Badge>)
- const badge = screen.getByText('Error')
- expect(badge).toHaveClass('text-destructive')
- })
+ it("applies danger variant styles", () => {
+ render(<Badge variant="danger">Error</Badge>);
+ const badge = screen.getByText("Error");
+ expect(badge).toHaveClass("text-destructive");
+ });
- it('applies warning variant styles', () => {
- render(<Badge variant="warning">Warning</Badge>)
- const badge = screen.getByText('Warning')
- expect(badge).toHaveClass('text-warning')
- })
+ it("applies warning variant styles", () => {
+ render(<Badge variant="warning">Warning</Badge>);
+ const badge = screen.getByText("Warning");
+ expect(badge).toHaveClass("text-warning");
+ });
- it('applies info variant styles', () => {
- render(<Badge variant="info">Info</Badge>)
- const badge = screen.getByText('Info')
- expect(badge).toHaveClass('text-info')
- })
+ it("applies info variant styles", () => {
+ render(<Badge variant="info">Info</Badge>);
+ const badge = screen.getByText("Info");
+ expect(badge).toHaveClass("text-info");
+ });
- it('has correct base styles', () => {
- render(<Badge>Test</Badge>)
- const badge = screen.getByText('Test')
- expect(badge).toHaveClass('inline-flex', 'items-center', 'rounded', 'text-xs', 'font-medium')
- })
-})
+ it("has correct base styles", () => {
+ render(<Badge>Test</Badge>);
+ const badge = screen.getByText("Test");
+ expect(badge).toHaveClass(
+ "inline-flex",
+ "items-center",
+ "rounded",
+ "text-xs",
+ "font-medium",
+ );
+ });
+});
diff --git a/dashboard/src/components/atoms/Badge.tsx b/dashboard/src/components/atoms/Badge.tsx
index 1b11fe0d..d56cf0de 100644
--- a/dashboard/src/components/atoms/Badge.tsx
+++ b/dashboard/src/components/atoms/Badge.tsx
@@ -1,24 +1,24 @@
-type Variant = 'default' | 'success' | 'warning' | 'danger' | 'info'
+type Variant = "default" | "success" | "warning" | "danger" | "info";
interface Props {
- variant?: Variant
- children: React.ReactNode
+ variant?: Variant;
+ children: React.ReactNode;
}
const variants: Record<Variant, string> = {
- default: 'bg-bg-elevated text-text-secondary',
- success: 'bg-success/15 text-success',
- warning: 'bg-warning/15 text-warning',
- danger: 'bg-destructive/15 text-destructive',
- info: 'bg-info/15 text-info',
-}
+ default: "bg-bg-elevated text-text-secondary",
+ success: "bg-success/15 text-success",
+ warning: "bg-warning/15 text-warning",
+ danger: "bg-destructive/15 text-destructive",
+ info: "bg-info/15 text-info",
+};
-export default function Badge({ variant = 'default', children }: Props) {
+export default function Badge({ variant = "default", children }: Props) {
return (
<span
className={`inline-flex items-center rounded px-1.5 py-0.5 text-xs font-medium ${variants[variant]}`}
>
{children}
</span>
- )
+ );
}
diff --git a/dashboard/src/components/atoms/Button.test.tsx b/dashboard/src/components/atoms/Button.test.tsx
index 89f8e2b2..8dd9f19c 100644
--- a/dashboard/src/components/atoms/Button.test.tsx
+++ b/dashboard/src/components/atoms/Button.test.tsx
@@ -1,36 +1,38 @@
-import { render, screen } from '@testing-library/react'
-import userEvent from '@testing-library/user-event'
-import { describe, it, expect, vi } from 'vitest'
-import Button from './Button'
+import { render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { describe, it, expect, vi } from "vitest";
+import Button from "./Button";
-describe('Button', () => {
- it('renders children', () => {
- render(<Button>Click me</Button>)
- expect(screen.getByRole('button', { name: 'Click me' })).toBeInTheDocument()
- })
+describe("Button", () => {
+ it("renders children", () => {
+ render(<Button>Click me</Button>);
+ expect(
+ screen.getByRole("button", { name: "Click me" }),
+ ).toBeInTheDocument();
+ });
- it('handles click events', async () => {
- const handleClick = vi.fn()
- render(<Button onClick={handleClick}>Click me</Button>)
-
- await userEvent.click(screen.getByRole('button'))
- expect(handleClick).toHaveBeenCalledTimes(1)
- })
+ it("handles click events", async () => {
+ const handleClick = vi.fn();
+ render(<Button onClick={handleClick}>Click me</Button>);
- it('applies variant styles', () => {
- render(<Button variant="primary">Primary</Button>)
- const button = screen.getByRole('button')
- expect(button).toHaveClass('bg-primary')
- })
+ await userEvent.click(screen.getByRole("button"));
+ expect(handleClick).toHaveBeenCalledTimes(1);
+ });
- it('applies size styles', () => {
- render(<Button size="sm">Small</Button>)
- const button = screen.getByRole('button')
- expect(button).toHaveClass('text-xs')
- })
+ it("applies variant styles", () => {
+ render(<Button variant="primary">Primary</Button>);
+ const button = screen.getByRole("button");
+ expect(button).toHaveClass("bg-primary");
+ });
- it('can be disabled', () => {
- render(<Button disabled>Disabled</Button>)
- expect(screen.getByRole('button')).toBeDisabled()
- })
-})
+ it("applies size styles", () => {
+ render(<Button size="sm">Small</Button>);
+ const button = screen.getByRole("button");
+ expect(button).toHaveClass("text-xs");
+ });
+
+ it("can be disabled", () => {
+ render(<Button disabled>Disabled</Button>);
+ expect(screen.getByRole("button")).toBeDisabled();
+ });
+});
diff --git a/dashboard/src/components/atoms/Button.tsx b/dashboard/src/components/atoms/Button.tsx
index 7a4b61ef..ae322bc8 100644
--- a/dashboard/src/components/atoms/Button.tsx
+++ b/dashboard/src/components/atoms/Button.tsx
@@ -1,34 +1,39 @@
-import type { ButtonHTMLAttributes } from 'react'
-import { forwardRef } from 'react'
+import type { ButtonHTMLAttributes } from "react";
+import { forwardRef } from "react";
-type Variant = 'default' | 'primary' | 'secondary' | 'danger' | 'ghost'
-type Size = 'sm' | 'md' | 'lg'
+type Variant = "default" | "primary" | "secondary" | "danger" | "ghost";
+type Size = "sm" | "md" | "lg";
interface Props extends ButtonHTMLAttributes<HTMLButtonElement> {
- variant?: Variant
- size?: Size
+ variant?: Variant;
+ size?: Size;
}
const base =
- 'inline-flex items-center justify-center gap-1.5 rounded font-medium transition-all duration-150 disabled:cursor-not-allowed disabled:opacity-40'
+ "inline-flex items-center justify-center gap-1.5 rounded font-medium transition-all duration-150 disabled:cursor-not-allowed disabled:opacity-40";
const variants: Record<Variant, string> = {
default:
- 'border border-border-default bg-bg-elevated text-text-secondary hover:bg-bg-hover hover:text-text-primary',
- primary: 'bg-primary text-white hover:bg-primary-hover',
- secondary: 'border border-border-subtle bg-transparent text-text-muted hover:bg-bg-elevated hover:text-text-secondary',
- danger: 'bg-destructive text-white hover:bg-destructive/80',
- ghost: 'bg-transparent text-text-muted hover:bg-bg-elevated hover:text-text-secondary',
-}
+ "border border-border-default bg-bg-elevated text-text-secondary hover:bg-bg-hover hover:text-text-primary",
+ primary: "bg-primary text-white hover:bg-primary-hover",
+ secondary:
+ "border border-border-subtle bg-transparent text-text-muted hover:bg-bg-elevated hover:text-text-secondary",
+ danger: "bg-destructive text-white hover:bg-destructive/80",
+ ghost:
+ "bg-transparent text-text-muted hover:bg-bg-elevated hover:text-text-secondary",
+};
const sizes: Record<Size, string> = {
- sm: 'px-2 py-1 text-xs',
- md: 'px-3 py-1.5 text-sm',
- lg: 'px-4 py-2 text-base',
-}
+ sm: "px-2 py-1 text-xs",
+ md: "px-3 py-1.5 text-sm",
+ lg: "px-4 py-2 text-base",
+};
const Button = forwardRef<HTMLButtonElement, Props>(
- ({ variant = 'default', size = 'md', className = '', children, ...props }, ref) => {
+ (
+ { variant = "default", size = "md", className = "", children, ...props },
+ ref,
+ ) => {
return (
<button
ref={ref}
@@ -37,9 +42,9 @@ const Button = forwardRef<HTMLButtonElement, Props>(
>
{children}
</button>
- )
- }
-)
+ );
+ },
+);
-Button.displayName = 'Button'
-export default Button
+Button.displayName = "Button";
+export default Button;
diff --git a/dashboard/src/components/atoms/Card.tsx b/dashboard/src/components/atoms/Card.tsx
index b41623d9..437cfdd2 100644
--- a/dashboard/src/components/atoms/Card.tsx
+++ b/dashboard/src/components/atoms/Card.tsx
@@ -1,31 +1,29 @@
-import type { HTMLAttributes } from 'react'
+import type { HTMLAttributes } from "react";
interface Props extends HTMLAttributes<HTMLDivElement> {
- hover?: boolean
- selected?: boolean
+ hover?: boolean;
+ selected?: boolean;
}
export default function Card({
hover = false,
selected = false,
- className = '',
+ className = "",
children,
...props
}: Props) {
return (
<div
className={`rounded-lg border bg-bg-surface ${
- selected
- ? 'border-primary'
- : 'border-border-subtle'
+ selected ? "border-primary" : "border-border-subtle"
} ${
hover
- ? 'cursor-pointer transition-all duration-150 hover:border-border-default hover:bg-bg-elevated'
- : ''
+ ? "cursor-pointer transition-all duration-150 hover:border-border-default hover:bg-bg-elevated"
+ : ""
} ${className}`}
{...props}
>
{children}
</div>
- )
+ );
}
diff --git a/dashboard/src/components/atoms/EmptyState.tsx b/dashboard/src/components/atoms/EmptyState.tsx
index fe67ae45..0d55bb3a 100644
--- a/dashboard/src/components/atoms/EmptyState.tsx
+++ b/dashboard/src/components/atoms/EmptyState.tsx
@@ -1,11 +1,16 @@
interface Props {
- icon?: string
- title: string
- description?: string
- action?: React.ReactNode
+ icon?: string;
+ title: string;
+ description?: string;
+ action?: React.ReactNode;
}
-export default function EmptyState({ icon = '🦀', title, description, action }: Props) {
+export default function EmptyState({
+ icon = "🦀",
+ title,
+ description,
+ action,
+}: Props) {
return (
<div className="flex flex-col items-center justify-center py-16 text-center">
<div className="mb-3 text-5xl">{icon}</div>
@@ -15,5 +20,5 @@ export default function EmptyState({ icon = '🦀', title, description, action }
)}
{action && <div className="mt-4">{action}</div>}
</div>
- )
+ );
}
diff --git a/dashboard/src/components/atoms/Input.tsx b/dashboard/src/components/atoms/Input.tsx
index 115acd4a..968ccb2f 100644
--- a/dashboard/src/components/atoms/Input.tsx
+++ b/dashboard/src/components/atoms/Input.tsx
@@ -1,30 +1,26 @@
-import type { InputHTMLAttributes } from 'react'
-import { forwardRef } from 'react'
+import type { InputHTMLAttributes } from "react";
+import { forwardRef } from "react";
interface Props extends InputHTMLAttributes<HTMLInputElement> {
- label?: string
- hint?: string
+ label?: string;
+ hint?: string;
}
const Input = forwardRef<HTMLInputElement, Props>(
- ({ label, hint, className = '', ...props }, ref) => {
+ ({ label, hint, className = "", ...props }, ref) => {
return (
<div className="flex flex-col gap-1">
- {label && (
- <label className="text-xs text-text-muted">{label}</label>
- )}
+ {label && <label className="text-xs text-text-muted">{label}</label>}
<input
ref={ref}
className={`rounded border border-border-default bg-bg-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-primary focus:outline-none ${className}`}
{...props}
/>
- {hint && (
- <span className="text-xs text-text-muted">{hint}</span>
- )}
+ {hint && <span className="text-xs text-text-muted">{hint}</span>}
</div>
- )
- }
-)
+ );
+ },
+);
-Input.displayName = 'Input'
-export default Input
+Input.displayName = "Input";
+export default Input;
diff --git a/dashboard/src/components/atoms/Modal.tsx b/dashboard/src/components/atoms/Modal.tsx
index cc806b30..70bbaeb3 100644
--- a/dashboard/src/components/atoms/Modal.tsx
+++ b/dashboard/src/components/atoms/Modal.tsx
@@ -1,31 +1,38 @@
-import { useEffect } from 'react'
-import Button from './Button'
+import { useEffect } from "react";
+import Button from "./Button";
interface Props {
- open: boolean
- onClose: () => void
- title: string
- children: React.ReactNode
- actions?: React.ReactNode
- wide?: boolean
+ open: boolean;
+ onClose: () => void;
+ title: string;
+ children: React.ReactNode;
+ actions?: React.ReactNode;
+ wide?: boolean;
}
-export default function Modal({ open, onClose, title, children, actions, wide }: Props) {
+export default function Modal({
+ open,
+ onClose,
+ title,
+ children,
+ actions,
+ wide,
+}: Props) {
useEffect(() => {
const handleEsc = (e: KeyboardEvent) => {
- if (e.key === 'Escape') onClose()
- }
+ if (e.key === "Escape") onClose();
+ };
if (open) {
- document.addEventListener('keydown', handleEsc)
- document.body.style.overflow = 'hidden'
+ document.addEventListener("keydown", handleEsc);
+ document.body.style.overflow = "hidden";
}
return () => {
- document.removeEventListener('keydown', handleEsc)
- document.body.style.overflow = ''
- }
- }, [open, onClose])
+ document.removeEventListener("keydown", handleEsc);
+ document.body.style.overflow = "";
+ };
+ }, [open, onClose]);
- if (!open) return null
+ if (!open) return null;
return (
<div
@@ -34,11 +41,13 @@ export default function Modal({ open, onClose, title, children, actions, wide }:
>
<div
className={`max-h-[90vh] overflow-y-auto rounded-lg border border-border-subtle bg-bg-surface p-5 shadow-xl ${
- wide ? 'w-full max-w-lg' : 'w-full max-w-sm'
+ wide ? "w-full max-w-lg" : "w-full max-w-sm"
}`}
onClick={(e) => e.stopPropagation()}
>
- <h3 className="mb-4 text-lg font-semibold text-text-primary">{title}</h3>
+ <h3 className="mb-4 text-lg font-semibold text-text-primary">
+ {title}
+ </h3>
<div className="text-sm text-text-secondary">{children}</div>
<div className="mt-5 flex justify-end gap-2">
{actions ?? (
@@ -49,5 +58,5 @@ export default function Modal({ open, onClose, title, children, actions, wide }:
</div>
</div>
</div>
- )
+ );
}
diff --git a/dashboard/src/components/atoms/StatusDot.test.tsx b/dashboard/src/components/atoms/StatusDot.test.tsx
index d100d244..ababccbf 100644
--- a/dashboard/src/components/atoms/StatusDot.test.tsx
+++ b/dashboard/src/components/atoms/StatusDot.test.tsx
@@ -1,52 +1,52 @@
-import { render, screen } from '@testing-library/react'
-import { describe, it, expect } from 'vitest'
-import StatusDot from './StatusDot'
-
-describe('StatusDot', () => {
- it('renders online status with success color', () => {
- const { container } = render(<StatusDot status="online" />)
- const dot = container.querySelector('.rounded-full')
- expect(dot).toHaveClass('bg-success')
- })
-
- it('renders offline status with muted color', () => {
- const { container } = render(<StatusDot status="offline" />)
- const dot = container.querySelector('.rounded-full')
- expect(dot).toHaveClass('bg-text-muted')
- })
-
- it('renders warning status with warning color', () => {
- const { container } = render(<StatusDot status="warning" />)
- const dot = container.querySelector('.rounded-full')
- expect(dot).toHaveClass('bg-warning')
- })
-
- it('renders loading status with pulse animation', () => {
- const { container } = render(<StatusDot status="loading" />)
- const dot = container.querySelector('.rounded-full')
- expect(dot).toHaveClass('bg-primary', 'animate-pulse')
- })
-
- it('renders label when provided', () => {
- render(<StatusDot status="online" label="Connected" />)
- expect(screen.getByText('Connected')).toBeInTheDocument()
- })
-
- it('does not render label when not provided', () => {
- const { container } = render(<StatusDot status="online" />)
- const label = container.querySelector('.text-xs')
- expect(label).not.toBeInTheDocument()
- })
-
- it('applies small size', () => {
- const { container } = render(<StatusDot status="online" size="sm" />)
- const dot = container.querySelector('.rounded-full')
- expect(dot).toHaveClass('h-2', 'w-2')
- })
-
- it('applies medium size by default', () => {
- const { container } = render(<StatusDot status="online" />)
- const dot = container.querySelector('.rounded-full')
- expect(dot).toHaveClass('h-2.5', 'w-2.5')
- })
-})
+import { render, screen } from "@testing-library/react";
+import { describe, it, expect } from "vitest";
+import StatusDot from "./StatusDot";
+
+describe("StatusDot", () => {
+ it("renders online status with success color", () => {
+ const { container } = render(<StatusDot status="online" />);
+ const dot = container.querySelector(".rounded-full");
+ expect(dot).toHaveClass("bg-success");
+ });
+
+ it("renders offline status with muted color", () => {
+ const { container } = render(<StatusDot status="offline" />);
+ const dot = container.querySelector(".rounded-full");
+ expect(dot).toHaveClass("bg-text-muted");
+ });
+
+ it("renders warning status with warning color", () => {
+ const { container } = render(<StatusDot status="warning" />);
+ const dot = container.querySelector(".rounded-full");
+ expect(dot).toHaveClass("bg-warning");
+ });
+
+ it("renders loading status with pulse animation", () => {
+ const { container } = render(<StatusDot status="loading" />);
+ const dot = container.querySelector(".rounded-full");
+ expect(dot).toHaveClass("bg-primary", "animate-pulse");
+ });
+
+ it("renders label when provided", () => {
+ render(<StatusDot status="online" label="Connected" />);
+ expect(screen.getByText("Connected")).toBeInTheDocument();
+ });
+
+ it("does not render label when not provided", () => {
+ const { container } = render(<StatusDot status="online" />);
+ const label = container.querySelector(".text-xs");
+ expect(label).not.toBeInTheDocument();
+ });
+
+ it("applies small size", () => {
+ const { container } = render(<StatusDot status="online" size="sm" />);
+ const dot = container.querySelector(".rounded-full");
+ expect(dot).toHaveClass("h-2", "w-2");
+ });
+
+ it("applies medium size by default", () => {
+ const { container } = render(<StatusDot status="online" />);
+ const dot = container.querySelector(".rounded-full");
+ expect(dot).toHaveClass("h-2.5", "w-2.5");
+ });
+});
diff --git a/dashboard/src/components/atoms/StatusDot.tsx b/dashboard/src/components/atoms/StatusDot.tsx
index 900a4f32..496b2ec0 100644
--- a/dashboard/src/components/atoms/StatusDot.tsx
+++ b/dashboard/src/components/atoms/StatusDot.tsx
@@ -1,28 +1,28 @@
-type Status = 'online' | 'offline' | 'warning' | 'loading'
+type Status = "online" | "offline" | "warning" | "loading";
interface Props {
- status: Status
- label?: string
- size?: 'sm' | 'md'
+ status: Status;
+ label?: string;
+ size?: "sm" | "md";
}
const colors: Record<Status, string> = {
- online: 'bg-success',
- offline: 'bg-text-muted',
- warning: 'bg-warning',
- loading: 'bg-primary animate-pulse',
-}
+ online: "bg-success",
+ offline: "bg-text-muted",
+ warning: "bg-warning",
+ loading: "bg-primary animate-pulse",
+};
const sizes = {
- sm: 'h-2 w-2',
- md: 'h-2.5 w-2.5',
-}
+ sm: "h-2 w-2",
+ md: "h-2.5 w-2.5",
+};
-export default function StatusDot({ status, label, size = 'md' }: Props) {
+export default function StatusDot({ status, label, size = "md" }: Props) {
return (
<div className="flex items-center gap-1.5">
<div className={`rounded-full ${colors[status]} ${sizes[size]}`} />
{label && <span className="text-xs text-text-secondary">{label}</span>}
</div>
- )
+ );
}
diff --git a/dashboard/src/components/atoms/Toolbar.tsx b/dashboard/src/components/atoms/Toolbar.tsx
index 1c7104e4..5ef3832b 100644
--- a/dashboard/src/components/atoms/Toolbar.tsx
+++ b/dashboard/src/components/atoms/Toolbar.tsx
@@ -1,21 +1,21 @@
interface ToolbarAction {
- key: string
- label: string
- onClick: () => void
- variant?: 'default' | 'primary'
- disabled?: boolean
+ key: string;
+ label: string;
+ onClick: () => void;
+ variant?: "default" | "primary";
+ disabled?: boolean;
}
interface Props {
- actions?: ToolbarAction[]
- children?: React.ReactNode
+ actions?: ToolbarAction[];
+ children?: React.ReactNode;
}
const actionBtn =
- 'inline-flex cursor-pointer items-center gap-1.5 whitespace-nowrap rounded border border-border-subtle bg-bg-elevated px-3 py-1.5 text-xs font-medium text-text-secondary transition-all duration-150 hover:not-disabled:border-border-default hover:not-disabled:bg-bg-hover hover:not-disabled:text-text-primary disabled:cursor-not-allowed disabled:opacity-40'
+ "inline-flex cursor-pointer items-center gap-1.5 whitespace-nowrap rounded border border-border-subtle bg-bg-elevated px-3 py-1.5 text-xs font-medium text-text-secondary transition-all duration-150 hover:not-disabled:border-border-default hover:not-disabled:bg-bg-hover hover:not-disabled:text-text-primary disabled:cursor-not-allowed disabled:opacity-40";
const primaryBtn =
- 'border-primary/50 bg-primary/10 text-primary hover:not-disabled:border-primary hover:not-disabled:bg-primary/20'
+ "border-primary/50 bg-primary/10 text-primary hover:not-disabled:border-primary hover:not-disabled:bg-primary/20";
export default function Toolbar({ actions, children }: Props) {
return (
@@ -23,7 +23,7 @@ export default function Toolbar({ actions, children }: Props) {
{actions?.map((a) => (
<button
key={a.key}
- className={`${actionBtn} ${a.variant === 'primary' ? primaryBtn : ''}`}
+ className={`${actionBtn} ${a.variant === "primary" ? primaryBtn : ""}`}
onClick={a.onClick}
disabled={a.disabled}
>
@@ -32,5 +32,5 @@ export default function Toolbar({ actions, children }: Props) {
))}
{children}
</div>
- )
+ );
}
diff --git a/dashboard/src/components/atoms/index.ts b/dashboard/src/components/atoms/index.ts
index 709883b0..bb306ef5 100644
--- a/dashboard/src/components/atoms/index.ts
+++ b/dashboard/src/components/atoms/index.ts
@@ -1,8 +1,8 @@
-export { default as Button } from './Button'
-export { default as Input } from './Input'
-export { default as Card } from './Card'
-export { default as Badge } from './Badge'
-export { default as StatusDot } from './StatusDot'
-export { default as Modal } from './Modal'
-export { default as Toolbar } from './Toolbar'
-export { default as EmptyState } from './EmptyState'
+export { default as Button } from "./Button";
+export { default as Input } from "./Input";
+export { default as Card } from "./Card";
+export { default as Badge } from "./Badge";
+export { default as StatusDot } from "./StatusDot";
+export { default as Modal } from "./Modal";
+export { default as Toolbar } from "./Toolbar";
+export { default as EmptyState } from "./EmptyState";
diff --git a/dashboard/src/components/molecules/ActivityLine.tsx b/dashboard/src/components/molecules/ActivityLine.tsx
index ee851afc..319126c1 100644
--- a/dashboard/src/components/molecules/ActivityLine.tsx
+++ b/dashboard/src/components/molecules/ActivityLine.tsx
@@ -1,46 +1,48 @@
-import { Badge } from '../atoms'
-import type { ActivityEvent } from '../../types'
+import { Badge } from "../atoms";
+import type { ActivityEvent } from "../../types";
interface Props {
- event: ActivityEvent
+ event: ActivityEvent;
}
-const typeColors: Record<string, 'default' | 'success' | 'info' | 'warning'> = {
- navigate: 'info',
- snapshot: 'success',
- action: 'warning',
- screenshot: 'default',
- other: 'default',
-}
+const typeColors: Record<string, "default" | "success" | "info" | "warning"> = {
+ navigate: "info",
+ snapshot: "success",
+ action: "warning",
+ screenshot: "default",
+ other: "default",
+};
const typeIcons: Record<string, string> = {
- navigate: '🧭',
- snapshot: '📸',
- action: '👆',
- screenshot: '🖼️',
- other: '📝',
-}
+ navigate: "🧭",
+ snapshot: "📸",
+ action: "👆",
+ screenshot: "🖼️",
+ other: "📝",
+};
function formatTime(ts: string): string {
- return new Date(ts).toLocaleTimeString('en-GB', {
- hour: '2-digit',
- minute: '2-digit',
- second: '2-digit',
- })
+ return new Date(ts).toLocaleTimeString("en-GB", {
+ hour: "2-digit",
+ minute: "2-digit",
+ second: "2-digit",
+ });
}
export default function ActivityLine({ event }: Props) {
return (
<div className="flex items-center gap-3 border-b border-border-subtle px-4 py-2 text-sm">
- <span className="text-lg">{typeIcons[event.type] || '📝'}</span>
+ <span className="text-lg">{typeIcons[event.type] || "📝"}</span>
<span className="w-16 shrink-0 font-mono text-xs text-text-muted">
{formatTime(event.timestamp)}
</span>
- <Badge variant={typeColors[event.type] || 'default'}>{event.method}</Badge>
+ <Badge variant={typeColors[event.type] || "default"}>
+ {event.method}
+ </Badge>
<span className="min-w-0 flex-1 truncate font-mono text-text-secondary">
{event.path}
</span>
<span className="shrink-0 text-xs text-text-muted">{event.agentId}</span>
</div>
- )
+ );
}
diff --git a/dashboard/src/components/molecules/AgentItem.tsx b/dashboard/src/components/molecules/AgentItem.tsx
index b8da7500..49e5dc3a 100644
--- a/dashboard/src/components/molecules/AgentItem.tsx
+++ b/dashboard/src/components/molecules/AgentItem.tsx
@@ -1,19 +1,19 @@
-import { Badge } from '../atoms'
-import type { Agent } from '../../types'
+import { Badge } from "../atoms";
+import type { Agent } from "../../types";
interface Props {
- agent: Agent
- selected: boolean
- onClick: () => void
+ agent: Agent;
+ selected: boolean;
+ onClick: () => void;
}
function timeAgo(date: string): string {
- const diff = Date.now() - new Date(date).getTime()
- const secs = Math.floor(diff / 1000)
- if (secs < 5) return 'just now'
- if (secs < 60) return `${secs}s ago`
- if (secs < 3600) return `${Math.floor(secs / 60)}m ago`
- return `${Math.floor(secs / 3600)}h ago`
+ const diff = Date.now() - new Date(date).getTime();
+ const secs = Math.floor(diff / 1000);
+ if (secs < 5) return "just now";
+ if (secs < 60) return `${secs}s ago`;
+ if (secs < 3600) return `${Math.floor(secs / 60)}m ago`;
+ return `${Math.floor(secs / 3600)}h ago`;
}
export default function AgentItem({ agent, selected, onClick }: Props) {
@@ -21,8 +21,8 @@ export default function AgentItem({ agent, selected, onClick }: Props) {
<button
className={`flex w-full items-center gap-3 rounded-lg px-3 py-2 text-left transition-all duration-150 ${
selected
- ? 'bg-primary/10 border border-primary'
- : 'border border-transparent hover:bg-bg-elevated'
+ ? "bg-primary/10 border border-primary"
+ : "border border-transparent hover:bg-bg-elevated"
}`}
onClick={onClick}
>
@@ -39,5 +39,5 @@ export default function AgentItem({ agent, selected, onClick }: Props) {
</div>
<Badge>{agent.requestCount}</Badge>
</button>
- )
+ );
}
diff --git a/dashboard/src/components/molecules/InstanceCard.tsx b/dashboard/src/components/molecules/InstanceCard.tsx
index 942008ba..a081ccb8 100644
--- a/dashboard/src/components/molecules/InstanceCard.tsx
+++ b/dashboard/src/components/molecules/InstanceCard.tsx
@@ -1,19 +1,19 @@
-import { Card, Badge, Button, StatusDot } from '../atoms'
-import type { Instance } from '../../types'
+import { Card, Badge, Button, StatusDot } from "../atoms";
+import type { Instance } from "../../types";
interface Props {
- instance: Instance
- onOpen: () => void
- onStop: () => void
+ instance: Instance;
+ onOpen: () => void;
+ onStop: () => void;
}
function formatUptime(startTime: string): string {
- const diff = Date.now() - new Date(startTime).getTime()
- const mins = Math.floor(diff / 60000)
- if (mins < 60) return `${mins}m`
- const hours = Math.floor(mins / 60)
- if (hours < 24) return `${hours}h ${mins % 60}m`
- return `${Math.floor(hours / 24)}d ${hours % 24}h`
+ const diff = Date.now() - new Date(startTime).getTime();
+ const mins = Math.floor(diff / 60000);
+ if (mins < 60) return `${mins}m`;
+ const hours = Math.floor(mins / 60);
+ if (hours < 24) return `${hours}h ${mins % 60}m`;
+ return `${Math.floor(hours / 24)}d ${hours % 24}h`;
}
export default function InstanceCard({ instance, onOpen, onStop }: Props) {
@@ -23,18 +23,22 @@ export default function InstanceCard({ instance, onOpen, onStop }: Props) {
<div className="flex items-center gap-2">
<StatusDot status="online" />
<div>
- <div className="font-medium text-text-primary">{instance.profileName}</div>
+ <div className="font-medium text-text-primary">
+ {instance.profileName}
+ </div>
<div className="text-xs text-text-muted">:{instance.port}</div>
</div>
</div>
- <Badge variant={instance.headless ? 'info' : 'default'}>
- {instance.headless ? 'Headless' : 'Headed'}
+ <Badge variant={instance.headless ? "info" : "default"}>
+ {instance.headless ? "Headless" : "Headed"}
</Badge>
</div>
<div className="mb-3 rounded bg-bg-elevated px-2 py-1.5 text-xs">
- <span className="text-text-muted">Uptime:</span>{' '}
- <span className="text-text-secondary">{formatUptime(instance.startTime)}</span>
+ <span className="text-text-muted">Uptime:</span>{" "}
+ <span className="text-text-secondary">
+ {formatUptime(instance.startTime)}
+ </span>
</div>
<div className="mt-auto flex gap-2">
@@ -46,5 +50,5 @@ export default function InstanceCard({ instance, onOpen, onStop }: Props) {
</Button>
</div>
</Card>
- )
+ );
}
diff --git a/dashboard/src/components/molecules/InstanceListItem.test.tsx b/dashboard/src/components/molecules/InstanceListItem.test.tsx
index 9afda148..1cb6b781 100644
--- a/dashboard/src/components/molecules/InstanceListItem.test.tsx
+++ b/dashboard/src/components/molecules/InstanceListItem.test.tsx
@@ -1,87 +1,87 @@
-import { render, screen } from '@testing-library/react'
-import userEvent from '@testing-library/user-event'
-import { describe, it, expect, vi } from 'vitest'
-import InstanceListItem from './InstanceListItem'
-import type { Instance } from '../../generated/types'
+import { render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { describe, it, expect, vi } from "vitest";
+import InstanceListItem from "./InstanceListItem";
+import type { Instance } from "../../generated/types";
const mockInstance: Instance = {
- id: 'inst_123',
- profileId: 'prof_456',
- profileName: 'test-profile',
- port: '9868',
+ id: "inst_123",
+ profileId: "prof_456",
+ profileName: "test-profile",
+ port: "9868",
headless: false,
- status: 'running',
+ status: "running",
startTime: new Date().toISOString(),
-}
+};
-describe('InstanceListItem', () => {
- it('renders instance name and port', () => {
+describe("InstanceListItem", () => {
+ it("renders instance name and port", () => {
render(
<InstanceListItem
instance={mockInstance}
tabCount={5}
selected={false}
onClick={() => {}}
- />
- )
-
- expect(screen.getByText('test-profile')).toBeInTheDocument()
- expect(screen.getByText(':9868 · 5 tabs')).toBeInTheDocument()
- })
+ />,
+ );
- it('shows running status badge', () => {
+ expect(screen.getByText("test-profile")).toBeInTheDocument();
+ expect(screen.getByText(":9868 · 5 tabs")).toBeInTheDocument();
+ });
+
+ it("shows running status badge", () => {
render(
<InstanceListItem
instance={mockInstance}
tabCount={0}
selected={false}
onClick={() => {}}
- />
- )
-
- expect(screen.getByText('running')).toBeInTheDocument()
- })
+ />,
+ );
+
+ expect(screen.getByText("running")).toBeInTheDocument();
+ });
- it('shows error status for errored instances', () => {
- const errorInstance = { ...mockInstance, status: 'error' }
+ it("shows error status for errored instances", () => {
+ const errorInstance = { ...mockInstance, status: "error" };
render(
<InstanceListItem
instance={errorInstance}
tabCount={0}
selected={false}
onClick={() => {}}
- />
- )
-
- expect(screen.getByText('error')).toBeInTheDocument()
- })
+ />,
+ );
+
+ expect(screen.getByText("error")).toBeInTheDocument();
+ });
- it('applies selected styles when selected', () => {
+ it("applies selected styles when selected", () => {
render(
<InstanceListItem
instance={mockInstance}
tabCount={0}
selected={true}
onClick={() => {}}
- />
- )
-
- const button = screen.getByRole('button')
- expect(button).toHaveClass('border-primary')
- })
+ />,
+ );
- it('calls onClick when clicked', async () => {
- const handleClick = vi.fn()
+ const button = screen.getByRole("button");
+ expect(button).toHaveClass("border-primary");
+ });
+
+ it("calls onClick when clicked", async () => {
+ const handleClick = vi.fn();
render(
<InstanceListItem
instance={mockInstance}
tabCount={0}
selected={false}
onClick={handleClick}
- />
- )
-
- await userEvent.click(screen.getByRole('button'))
- expect(handleClick).toHaveBeenCalledTimes(1)
- })
-})
+ />,
+ );
+
+ await userEvent.click(screen.getByRole("button"));
+ expect(handleClick).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/dashboard/src/components/molecules/InstanceListItem.tsx b/dashboard/src/components/molecules/InstanceListItem.tsx
index 3499405c..ff511843 100644
--- a/dashboard/src/components/molecules/InstanceListItem.tsx
+++ b/dashboard/src/components/molecules/InstanceListItem.tsx
@@ -1,11 +1,11 @@
-import { Badge } from '../atoms'
-import type { Instance } from '../../generated/types'
+import { Badge } from "../atoms";
+import type { Instance } from "../../generated/types";
interface Props {
- instance: Instance
- tabCount: number
- selected: boolean
- onClick: () => void
+ instance: Instance;
+ tabCount: number;
+ selected: boolean;
+ onClick: () => void;
}
export default function InstanceListItem({
@@ -15,26 +15,26 @@ export default function InstanceListItem({
onClick,
}: Props) {
const statusColor =
- instance.status === 'running'
- ? 'bg-success'
- : instance.status === 'error'
- ? 'bg-destructive'
- : 'bg-text-muted'
+ instance.status === "running"
+ ? "bg-success"
+ : instance.status === "error"
+ ? "bg-destructive"
+ : "bg-text-muted";
const badgeVariant =
- instance.status === 'running'
- ? 'success'
- : instance.status === 'error'
- ? 'danger'
- : 'default'
+ instance.status === "running"
+ ? "success"
+ : instance.status === "error"
+ ? "danger"
+ : "default";
return (
<button
onClick={onClick}
className={`mb-1 flex w-full items-center gap-2 rounded-lg px-3 py-2 text-left transition-all ${
selected
- ? 'bg-primary/10 border border-primary'
- : 'border border-transparent hover:bg-bg-elevated'
+ ? "bg-primary/10 border border-primary"
+ : "border border-transparent hover:bg-bg-elevated"
}`}
>
<div className={`h-2 w-2 rounded-full ${statusColor}`} />
@@ -48,5 +48,5 @@ export default function InstanceListItem({
</div>
<Badge variant={badgeVariant}>{instance.status}</Badge>
</button>
- )
+ );
}
diff --git a/dashboard/src/components/molecules/NavBar.css b/dashboard/src/components/molecules/NavBar.css
index 789b25c5..3f713fbc 100644
--- a/dashboard/src/components/molecules/NavBar.css
+++ b/dashboard/src/components/molecules/NavBar.css
@@ -14,7 +14,7 @@
}
.navbar-tab.active::after {
- content: '';
+ content: "";
position: absolute;
bottom: 0;
left: 8px;
diff --git a/dashboard/src/components/molecules/NavBar.tsx b/dashboard/src/components/molecules/NavBar.tsx
index ea67c19b..2f2b305d 100644
--- a/dashboard/src/components/molecules/NavBar.tsx
+++ b/dashboard/src/components/molecules/NavBar.tsx
@@ -1,52 +1,52 @@
-import { useCallback, useEffect, useRef, useState } from 'react'
-import { NavLink } from 'react-router-dom'
-import './NavBar.css'
+import { useCallback, useEffect, useRef, useState } from "react";
+import { NavLink } from "react-router-dom";
+import "./NavBar.css";
interface Tab {
- id: string
- path: string
- label: string
+ id: string;
+ path: string;
+ label: string;
}
const tabs: Tab[] = [
- { id: 'monitoring', path: '/monitoring', label: 'Monitoring' },
- { id: 'agents', path: '/agents', label: 'Agents' },
- { id: 'profiles', path: '/profiles', label: 'Profiles' },
- { id: 'settings', path: '/settings', label: 'Settings' },
-]
+ { id: "monitoring", path: "/monitoring", label: "Monitoring" },
+ { id: "agents", path: "/agents", label: "Agents" },
+ { id: "profiles", path: "/profiles", label: "Profiles" },
+ { id: "settings", path: "/settings", label: "Settings" },
+];
interface NavBarProps {
- onRefresh?: () => void
+ onRefresh?: () => void;
}
export default function NavBar({ onRefresh }: NavBarProps) {
- const [refreshing, setRefreshing] = useState(false)
- const tabsRef = useRef<HTMLElement>(null)
+ const [refreshing, setRefreshing] = useState(false);
+ const tabsRef = useRef<HTMLElement>(null);
const handleRefresh = useCallback(() => {
- if (!onRefresh || refreshing) return
- setRefreshing(true)
- onRefresh()
- setTimeout(() => setRefreshing(false), 800)
- }, [onRefresh, refreshing])
+ if (!onRefresh || refreshing) return;
+ setRefreshing(true);
+ onRefresh();
+ setTimeout(() => setRefreshing(false), 800);
+ }, [onRefresh, refreshing]);
useEffect(() => {
const handler = (e: KeyboardEvent) => {
- if (!e.metaKey && !e.ctrlKey) return
- const num = parseInt(e.key)
+ if (!e.metaKey && !e.ctrlKey) return;
+ const num = parseInt(e.key);
if (num >= 1 && num <= tabs.length) {
- e.preventDefault()
- window.location.hash = tabs[num - 1].path
- return
+ e.preventDefault();
+ window.location.hash = tabs[num - 1].path;
+ return;
}
- if (e.key === 'r' && onRefresh) {
- e.preventDefault()
- handleRefresh()
+ if (e.key === "r" && onRefresh) {
+ e.preventDefault();
+ handleRefresh();
}
- }
- window.addEventListener('keydown', handler)
- return () => window.removeEventListener('keydown', handler)
- }, [onRefresh, handleRefresh])
+ };
+ window.addEventListener("keydown", handler);
+ return () => window.removeEventListener("keydown", handler);
+ }, [onRefresh, handleRefresh]);
return (
<header className="sticky top-0 z-50 flex h-[52px] items-center gap-0 border-b border-border-subtle bg-bg-app px-4">
@@ -61,7 +61,7 @@ export default function NavBar({ onRefresh }: NavBarProps) {
to={tab.path}
className={({ isActive }) =>
`navbar-tab relative cursor-pointer border-none bg-transparent px-3.5 py-3.5 text-sm font-medium leading-none whitespace-nowrap transition-colors duration-150 hover:text-text-primary focus-visible:rounded focus-visible:shadow-[0_0_0_2px_var(--primary)/25] focus-visible:outline-none ${
- isActive ? 'active text-text-primary' : 'text-text-secondary'
+ isActive ? "active text-text-primary" : "text-text-secondary"
}`
}
title={`${tab.label} (⌘${i + 1})`}
@@ -75,7 +75,7 @@ export default function NavBar({ onRefresh }: NavBarProps) {
{onRefresh && (
<button
className={`navbar-icon-btn flex h-8 w-8 cursor-pointer items-center justify-center rounded-md border border-transparent bg-transparent text-base text-text-muted transition-all duration-150 hover:border-border-subtle hover:bg-bg-elevated hover:text-text-secondary focus-visible:shadow-[0_0_0_2px_var(--primary)/25] focus-visible:outline-none ${
- refreshing ? 'spinning' : ''
+ refreshing ? "spinning" : ""
}`}
onClick={handleRefresh}
title="Refresh (⌘R)"
@@ -85,5 +85,5 @@ export default function NavBar({ onRefresh }: NavBarProps) {
)}
</div>
</header>
- )
+ );
}
diff --git a/dashboard/src/components/molecules/ProfileCard.test.tsx b/dashboard/src/components/molecules/ProfileCard.test.tsx
index 19ee6870..9c8575ea 100644
--- a/dashboard/src/components/molecules/ProfileCard.test.tsx
+++ b/dashboard/src/components/molecules/ProfileCard.test.tsx
@@ -1,170 +1,176 @@
-import { render, screen } from '@testing-library/react'
-import userEvent from '@testing-library/user-event'
-import { describe, it, expect, vi } from 'vitest'
-import ProfileCard from './ProfileCard'
-import type { Profile, Instance } from '../../types'
+import { render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { describe, it, expect, vi } from "vitest";
+import ProfileCard from "./ProfileCard";
+import type { Profile, Instance } from "../../types";
const mockProfile: Profile = {
- id: 'prof_123',
- name: 'test-profile',
+ id: "prof_123",
+ name: "test-profile",
created: new Date().toISOString(),
lastUsed: new Date().toISOString(),
diskUsage: 1024 * 1024 * 100, // 100MB
sizeMB: 100,
running: false,
-}
+};
const mockRunningInstance: Instance = {
- id: 'inst_123',
- profileId: 'prof_123',
- profileName: 'test-profile',
- port: '9868',
+ id: "inst_123",
+ profileId: "prof_123",
+ profileName: "test-profile",
+ port: "9868",
headless: false,
- status: 'running',
+ status: "running",
startTime: new Date().toISOString(),
-}
+};
const mockErrorInstance: Instance = {
...mockRunningInstance,
- status: 'error',
- error: 'Failed to start Chrome',
-}
-
-describe('ProfileCard', () => {
- it('renders profile name', () => {
- render(<ProfileCard profile={mockProfile} onLaunch={() => {}} />)
- expect(screen.getByText('test-profile')).toBeInTheDocument()
- })
-
- it('shows stopped badge when no instance', () => {
- render(<ProfileCard profile={mockProfile} onLaunch={() => {}} />)
- expect(screen.getByText('stopped')).toBeInTheDocument()
- })
-
- it('shows port badge when running', () => {
+ status: "error",
+ error: "Failed to start Chrome",
+};
+
+describe("ProfileCard", () => {
+ it("renders profile name", () => {
+ render(<ProfileCard profile={mockProfile} onLaunch={() => {}} />);
+ expect(screen.getByText("test-profile")).toBeInTheDocument();
+ });
+
+ it("shows stopped badge when no instance", () => {
+ render(<ProfileCard profile={mockProfile} onLaunch={() => {}} />);
+ expect(screen.getByText("stopped")).toBeInTheDocument();
+ });
+
+ it("shows port badge when running", () => {
render(
<ProfileCard
profile={mockProfile}
instance={mockRunningInstance}
onLaunch={() => {}}
- />
- )
- expect(screen.getByText(':9868')).toBeInTheDocument()
- })
+ />,
+ );
+ expect(screen.getByText(":9868")).toBeInTheDocument();
+ });
- it('shows error badge when errored', () => {
+ it("shows error badge when errored", () => {
render(
<ProfileCard
profile={mockProfile}
instance={mockErrorInstance}
onLaunch={() => {}}
- />
- )
- expect(screen.getByText('error')).toBeInTheDocument()
- })
+ />,
+ );
+ expect(screen.getByText("error")).toBeInTheDocument();
+ });
- it('shows error message when errored', () => {
+ it("shows error message when errored", () => {
render(
<ProfileCard
profile={mockProfile}
instance={mockErrorInstance}
onLaunch={() => {}}
- />
- )
- expect(screen.getByText('Failed to start Chrome')).toBeInTheDocument()
- })
-
- it('displays size in MB', () => {
- render(<ProfileCard profile={mockProfile} onLaunch={() => {}} />)
- expect(screen.getByText('100 MB')).toBeInTheDocument()
- })
-
- it('displays dash for missing size', () => {
- const noSizeProfile = { ...mockProfile, sizeMB: undefined }
- render(<ProfileCard profile={noSizeProfile} onLaunch={() => {}} />)
- expect(screen.getAllByText('—')).toHaveLength(2) // Size and Account both show —
- })
-
- it('displays account email', () => {
- const profileWithEmail = { ...mockProfile, accountEmail: '[email protected]' }
- render(<ProfileCard profile={profileWithEmail} onLaunch={() => {}} />)
- expect(screen.getByText('[email protected]')).toBeInTheDocument()
- })
-
- it('displays account name when no email', () => {
- const profileWithName = { ...mockProfile, accountName: 'Test User' }
- render(<ProfileCard profile={profileWithName} onLaunch={() => {}} />)
- expect(screen.getByText('Test User')).toBeInTheDocument()
- })
-
- it('displays useWhen text', () => {
- const profileWithUseWhen = { ...mockProfile, useWhen: 'For testing purposes' }
- render(<ProfileCard profile={profileWithUseWhen} onLaunch={() => {}} />)
- expect(screen.getByText('For testing purposes')).toBeInTheDocument()
- })
-
- it('shows Start button when stopped', () => {
- render(<ProfileCard profile={mockProfile} onLaunch={() => {}} />)
- expect(screen.getByRole('button', { name: 'Start' })).toBeInTheDocument()
- })
-
- it('shows Stop button when running', () => {
+ />,
+ );
+ expect(screen.getByText("Failed to start Chrome")).toBeInTheDocument();
+ });
+
+ it("displays size in MB", () => {
+ render(<ProfileCard profile={mockProfile} onLaunch={() => {}} />);
+ expect(screen.getByText("100 MB")).toBeInTheDocument();
+ });
+
+ it("displays dash for missing size", () => {
+ const noSizeProfile = { ...mockProfile, sizeMB: undefined };
+ render(<ProfileCard profile={noSizeProfile} onLaunch={() => {}} />);
+ expect(screen.getAllByText("—")).toHaveLength(2); // Size and Account both show —
+ });
+
+ it("displays account email", () => {
+ const profileWithEmail = {
+ ...mockProfile,
+ accountEmail: "[email protected]",
+ };
+ render(<ProfileCard profile={profileWithEmail} onLaunch={() => {}} />);
+ expect(screen.getByText("[email protected]")).toBeInTheDocument();
+ });
+
+ it("displays account name when no email", () => {
+ const profileWithName = { ...mockProfile, accountName: "Test User" };
+ render(<ProfileCard profile={profileWithName} onLaunch={() => {}} />);
+ expect(screen.getByText("Test User")).toBeInTheDocument();
+ });
+
+ it("displays useWhen text", () => {
+ const profileWithUseWhen = {
+ ...mockProfile,
+ useWhen: "For testing purposes",
+ };
+ render(<ProfileCard profile={profileWithUseWhen} onLaunch={() => {}} />);
+ expect(screen.getByText("For testing purposes")).toBeInTheDocument();
+ });
+
+ it("shows Start button when stopped", () => {
+ render(<ProfileCard profile={mockProfile} onLaunch={() => {}} />);
+ expect(screen.getByRole("button", { name: "Start" })).toBeInTheDocument();
+ });
+
+ it("shows Stop button when running", () => {
render(
<ProfileCard
profile={mockProfile}
instance={mockRunningInstance}
onLaunch={() => {}}
onStop={() => {}}
- />
- )
- expect(screen.getByRole('button', { name: 'Stop' })).toBeInTheDocument()
- })
-
- it('calls onLaunch when Start clicked', async () => {
- const handleLaunch = vi.fn()
- render(<ProfileCard profile={mockProfile} onLaunch={handleLaunch} />)
-
- await userEvent.click(screen.getByRole('button', { name: 'Start' }))
- expect(handleLaunch).toHaveBeenCalledTimes(1)
- })
-
- it('calls onStop when Stop clicked', async () => {
- const handleStop = vi.fn()
+ />,
+ );
+ expect(screen.getByRole("button", { name: "Stop" })).toBeInTheDocument();
+ });
+
+ it("calls onLaunch when Start clicked", async () => {
+ const handleLaunch = vi.fn();
+ render(<ProfileCard profile={mockProfile} onLaunch={handleLaunch} />);
+
+ await userEvent.click(screen.getByRole("button", { name: "Start" }));
+ expect(handleLaunch).toHaveBeenCalledTimes(1);
+ });
+
+ it("calls onStop when Stop clicked", async () => {
+ const handleStop = vi.fn();
render(
<ProfileCard
profile={mockProfile}
instance={mockRunningInstance}
onLaunch={() => {}}
onStop={handleStop}
- />
- )
-
- await userEvent.click(screen.getByRole('button', { name: 'Stop' }))
- expect(handleStop).toHaveBeenCalledTimes(1)
- })
-
- it('shows Details button when onDetails provided', () => {
+ />,
+ );
+
+ await userEvent.click(screen.getByRole("button", { name: "Stop" }));
+ expect(handleStop).toHaveBeenCalledTimes(1);
+ });
+
+ it("shows Details button when onDetails provided", () => {
render(
<ProfileCard
profile={mockProfile}
onLaunch={() => {}}
onDetails={() => {}}
- />
- )
- expect(screen.getByRole('button', { name: 'Details' })).toBeInTheDocument()
- })
+ />,
+ );
+ expect(screen.getByRole("button", { name: "Details" })).toBeInTheDocument();
+ });
- it('calls onDetails when Details clicked', async () => {
- const handleDetails = vi.fn()
+ it("calls onDetails when Details clicked", async () => {
+ const handleDetails = vi.fn();
render(
<ProfileCard
profile={mockProfile}
onLaunch={() => {}}
onDetails={handleDetails}
- />
- )
-
- await userEvent.click(screen.getByRole('button', { name: 'Details' }))
- expect(handleDetails).toHaveBeenCalledTimes(1)
- })
-})
+ />,
+ );
+
+ await userEvent.click(screen.getByRole("button", { name: "Details" }));
+ expect(handleDetails).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/dashboard/src/components/molecules/ProfileCard.tsx b/dashboard/src/components/molecules/ProfileCard.tsx
index b66b8edb..0ad26ec3 100644
--- a/dashboard/src/components/molecules/ProfileCard.tsx
+++ b/dashboard/src/components/molecules/ProfileCard.tsx
@@ -1,12 +1,12 @@
-import { Card, Badge, Button } from '../atoms'
-import type { Profile, Instance } from '../../types'
+import { Card, Badge, Button } from "../atoms";
+import type { Profile, Instance } from "../../types";
interface Props {
- profile: Profile
- instance?: Instance
- onLaunch: () => void
- onStop?: () => void
- onDetails?: () => void
+ profile: Profile;
+ instance?: Instance;
+ onLaunch: () => void;
+ onStop?: () => void;
+ onDetails?: () => void;
}
function InfoRow({ label, value }: { label: string; value: string }) {
@@ -15,7 +15,7 @@ function InfoRow({ label, value }: { label: string; value: string }) {
<span className="text-text-muted">{label}</span>
<span className="text-text-secondary">{value}</span>
</div>
- )
+ );
}
export default function ProfileCard({
@@ -25,10 +25,10 @@ export default function ProfileCard({
onStop,
onDetails,
}: Props) {
- const isRunning = instance?.status === 'running'
- const isError = instance?.status === 'error'
- const accountText = profile.accountEmail || profile.accountName || '—'
- const sizeText = profile.sizeMB ? `${profile.sizeMB.toFixed(0)} MB` : '—'
+ const isRunning = instance?.status === "running";
+ const isError = instance?.status === "error";
+ const accountText = profile.accountEmail || profile.accountName || "—";
+ const sizeText = profile.sizeMB ? `${profile.sizeMB.toFixed(0)} MB` : "—";
return (
<Card hover className="flex flex-col">
@@ -81,5 +81,5 @@ export default function ProfileCard({
)}
</div>
</Card>
- )
+ );
}
diff --git a/dashboard/src/components/molecules/ProfileDetailsModal.tsx b/dashboard/src/components/molecules/ProfileDetailsModal.tsx
index 843352ff..2213f1c4 100644
--- a/dashboard/src/components/molecules/ProfileDetailsModal.tsx
+++ b/dashboard/src/components/molecules/ProfileDetailsModal.tsx
@@ -1,19 +1,24 @@
-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, Agent } from '../../generated/types'
-import * as api from '../../services/api'
+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,
+ Agent,
+} 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
+ profile: Profile | null;
+ instance?: Instance;
+ onClose: () => void;
+ onSave?: (name: string, useWhen: string) => void;
+ onDelete?: () => void;
}
-type TabId = 'profile' | 'live' | 'logs'
+type TabId = "profile" | "live" | "logs";
function InfoRow({ label, value }: { label: string; value: string }) {
return (
@@ -21,7 +26,7 @@ function InfoRow({ label, value }: { label: string; value: string }) {
<span className="text-text-muted">{label}</span>
<span className="text-text-primary">{value}</span>
</div>
- )
+ );
}
export default function ProfileDetailsModal({
@@ -31,74 +36,74 @@ export default function ProfileDetailsModal({
onSave,
onDelete,
}: Props) {
- const [activeTab, setActiveTab] = useState<TabId>('profile')
- const [name, setName] = useState('')
- const [useWhen, setUseWhen] = useState('')
- const [tabs, setTabs] = useState<InstanceTab[]>([])
- const [agents, setAgents] = useState<Agent[]>([])
- const [logs] = useState('') // TODO: fetch from /instances/{id}/logs
- const [copyFeedback, setCopyFeedback] = useState('')
+ const [activeTab, setActiveTab] = useState<TabId>("profile");
+ const [name, setName] = useState("");
+ const [useWhen, setUseWhen] = useState("");
+ const [tabs, setTabs] = useState<InstanceTab[]>([]);
+ const [agents, setAgents] = useState<Agent[]>([]);
+ const [logs] = useState(""); // TODO: fetch from /instances/{id}/logs
+ const [copyFeedback, setCopyFeedback] = useState("");
- const isRunning = instance?.status === 'running'
+ const isRunning = instance?.status === "running";
- // Initialize form values
+ // Initialize form values when profile changes
useEffect(() => {
if (profile) {
- setName(profile.name)
- setUseWhen(profile.useWhen || '')
+ setName(profile.name);
+ setUseWhen(profile.useWhen || "");
}
- }, [profile])
+ }, [profile]);
// Load live data when switching to live/logs tab
const loadLiveData = useCallback(async () => {
- if (!instance?.id) return
+ if (!instance?.id) return;
try {
const [allTabs, agentsData] = await Promise.all([
api.fetchAllTabs().catch(() => []),
api.fetchAgents().catch(() => []),
- ])
+ ]);
// Filter tabs for this instance
const instanceTabs = Array.isArray(allTabs)
? allTabs.filter((t) => t.instanceId === instance.id)
- : []
- setTabs(instanceTabs)
- setAgents(agentsData.filter((a) => a.name === profile?.name))
+ : [];
+ setTabs(instanceTabs);
+ setAgents(agentsData.filter((a) => a.name === profile?.name));
} catch (e) {
- console.error('Failed to load live data', e)
+ console.error("Failed to load live data", e);
}
- }, [instance?.id, profile?.name])
+ }, [instance, profile?.name]);
useEffect(() => {
- if (activeTab === 'live' || activeTab === 'logs') {
- loadLiveData()
+ if (activeTab === "live" || activeTab === "logs") {
+ loadLiveData();
}
- }, [activeTab, loadLiveData])
+ }, [activeTab, loadLiveData]);
const handleCopyId = async () => {
- if (!profile?.id) return
+ if (!profile?.id) return;
try {
- await navigator.clipboard.writeText(profile.id)
- setCopyFeedback('Copied!')
- setTimeout(() => setCopyFeedback(''), 2000)
+ await navigator.clipboard.writeText(profile.id);
+ setCopyFeedback("Copied!");
+ setTimeout(() => setCopyFeedback(""), 2000);
} catch {
- setCopyFeedback('Failed')
- setTimeout(() => setCopyFeedback(''), 2000)
+ setCopyFeedback("Failed");
+ setTimeout(() => setCopyFeedback(""), 2000);
}
- }
+ };
const handleSave = () => {
- onSave?.(name, useWhen)
- }
+ onSave?.(name, useWhen);
+ };
- if (!profile) return null
+ 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'
- }`
+ ? "border-primary text-text-primary"
+ : "border-transparent text-text-muted hover:text-text-secondary"
+ }`;
return (
<Modal
@@ -124,32 +129,43 @@ export default function ProfileDetailsModal({
>
{/* Tabs */}
<div className="-mx-4 -mt-2 mb-4 flex border-b border-border-subtle px-4">
- <button className={tabClasses('profile')} onClick={() => setActiveTab('profile')}>
+ <button
+ className={tabClasses("profile")}
+ onClick={() => setActiveTab("profile")}
+ >
Profile
</button>
- <button className={tabClasses('live')} onClick={() => setActiveTab('live')}>
+ <button
+ className={tabClasses("live")}
+ onClick={() => setActiveTab("live")}
+ >
Live
</button>
- <button className={tabClasses('logs')} onClick={() => setActiveTab('logs')}>
+ <button
+ className={tabClasses("logs")}
+ onClick={() => setActiveTab("logs")}
+ >
Logs
</button>
</div>
{/* Tab Content */}
<div className="min-h-[400px]">
- {activeTab === 'profile' && (
+ {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>
+ <label className="mb-1 block text-xs text-text-muted">
+ Profile ID
+ </label>
<div className="flex gap-2">
<input
readOnly
- value={profile.id || '—'}
+ 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'}
+ {copyFeedback || "Copy"}
</Button>
</div>
</div>
@@ -179,15 +195,23 @@ export default function ProfileDetailsModal({
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 || '—'} />
+ <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 || ''} />
+ <InfoRow
+ label="Account"
+ value={profile.accountEmail || profile.accountName || ""}
+ />
)}
</div>
</div>
@@ -198,21 +222,25 @@ export default function ProfileDetailsModal({
<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'}`}>
+ <code
+ className={`text-xs ${profile.pathExists ? "text-text-secondary" : "text-destructive"}`}
+ >
{profile.path}
- {!profile.pathExists && ' (not found)'}
+ {!profile.pathExists && " (not found)"}
</code>
</div>
)}
</div>
)}
- {activeTab === 'live' && (
+ {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>
+ <span className="text-sm text-text-muted">
+ {tabs.length} tab(s)
+ </span>
<Button size="sm" variant="secondary" onClick={loadLiveData}>
Refresh
</Button>
@@ -243,7 +271,7 @@ export default function ProfileDetailsModal({
</div>
)}
- {activeTab === 'logs' && (
+ {activeTab === "logs" && (
<div className="space-y-4">
{/* Tabs */}
<div>
@@ -252,7 +280,7 @@ export default function ProfileDetailsModal({
</h4>
{tabs.length === 0 ? (
<p className="text-sm text-text-muted">
- {isRunning ? 'No tabs open.' : 'Instance not running.'}
+ {isRunning ? "No tabs open." : "Instance not running."}
</p>
) : (
<div className="space-y-1">
@@ -291,13 +319,14 @@ export default function ProfileDetailsModal({
{logs}
</pre>
) : (
- <p className="text-sm text-text-muted">No instance logs available.</p>
+ <p className="text-sm text-text-muted">
+ No instance logs available.
+ </p>
)}
</div>
</div>
)}
</div>
-
</Modal>
- )
+ );
}
diff --git a/dashboard/src/components/molecules/ScreencastTile.tsx b/dashboard/src/components/molecules/ScreencastTile.tsx
index bd7907fd..65069575 100644
--- a/dashboard/src/components/molecules/ScreencastTile.tsx
+++ b/dashboard/src/components/molecules/ScreencastTile.tsx
@@ -1,16 +1,16 @@
-import { useEffect, useRef, useState } from 'react'
+import { useEffect, useRef, useState } from "react";
interface Props {
- instancePort: string
- tabId: string
- label: string
- url: string
- quality?: number
- maxWidth?: number
- fps?: number
+ instancePort: string;
+ tabId: string;
+ label: string;
+ url: string;
+ quality?: number;
+ maxWidth?: number;
+ fps?: number;
}
-type Status = 'connecting' | 'streaming' | 'error'
+type Status = "connecting" | "streaming" | "error";
export default function ScreencastTile({
instancePort,
@@ -21,75 +21,75 @@ export default function ScreencastTile({
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('—')
+ 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 canvas = canvasRef.current;
+ if (!canvas) return;
- const ctx = canvas.getContext('2d')
- if (!ctx) return
+ const ctx = canvas.getContext("2d");
+ if (!ctx) return;
// Connect directly to instance's screencast WebSocket
- const wsUrl = `ws://localhost:${instancePort}/screencast?tabId=${encodeURIComponent(tabId)}&quality=${quality}&maxWidth=${maxWidth}&fps=${fps}`
+ const wsUrl = `ws://localhost:${instancePort}/screencast?tabId=${encodeURIComponent(tabId)}&quality=${quality}&maxWidth=${maxWidth}&fps=${fps}`;
- const socket = new WebSocket(wsUrl)
- socket.binaryType = 'arraybuffer'
- socketRef.current = socket
+ const socket = new WebSocket(wsUrl);
+ socket.binaryType = "arraybuffer";
+ socketRef.current = socket;
- let frameCount = 0
- let lastFpsTime = Date.now()
+ let frameCount = 0;
+ let lastFpsTime = Date.now();
socket.onopen = () => {
- setStatus('streaming')
- }
+ setStatus("streaming");
+ };
socket.onmessage = (evt) => {
- const blob = new Blob([evt.data], { type: 'image/jpeg' })
- const imgUrl = URL.createObjectURL(blob)
- const img = new Image()
+ 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()
+ 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
+ setFpsDisplay(`${frameCount} fps`);
+ setSizeDisplay(`${(evt.data.byteLength / 1024).toFixed(0)} KB/frame`);
+ frameCount = 0;
+ lastFpsTime = now;
}
- }
+ };
socket.onerror = () => {
- setStatus('error')
- }
+ setStatus("error");
+ };
socket.onclose = () => {
- setStatus('error')
- }
+ setStatus("error");
+ };
return () => {
- socket.close()
- socketRef.current = null
- }
- }, [instancePort, tabId, quality, maxWidth, fps])
+ socket.close();
+ socketRef.current = null;
+ };
+ }, [instancePort, tabId, quality, maxWidth, fps]);
const statusColor =
- status === 'streaming'
- ? 'bg-success'
- : status === 'connecting'
- ? 'bg-warning'
- : 'bg-destructive'
+ status === "streaming"
+ ? "bg-success"
+ : status === "connecting"
+ ? "bg-warning"
+ : "bg-destructive";
return (
<div className="overflow-hidden rounded-lg border border-border-subtle bg-bg-elevated">
@@ -110,7 +110,7 @@ export default function ScreencastTile({
width={800}
height={600}
/>
- {status === 'error' && (
+ {status === "error" && (
<div className="absolute inset-0 flex items-center justify-center bg-black/80 text-sm text-text-muted">
Connection lost
</div>
@@ -123,5 +123,5 @@ export default function ScreencastTile({
<span>{sizeDisplay}</span>
</div>
</div>
- )
+ );
}
diff --git a/dashboard/src/components/molecules/TabItem.test.tsx b/dashboard/src/components/molecules/TabItem.test.tsx
index 417b8d46..44f7d255 100644
--- a/dashboard/src/components/molecules/TabItem.test.tsx
+++ b/dashboard/src/components/molecules/TabItem.test.tsx
@@ -1,45 +1,47 @@
-import { render, screen } from '@testing-library/react'
-import { describe, it, expect } from 'vitest'
-import TabItem from './TabItem'
-import type { InstanceTab } from '../../generated/types'
+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://example.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://example.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 compact variant', () => {
- render(<TabItem tab={mockTab} compact />)
-
- expect(screen.getByText('Example Page')).toBeInTheDocument()
+ id: "tab_123",
+ instanceId: "inst_456",
+ url: "https://example.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://example.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 compact variant", () => {
+ render(<TabItem tab={mockTab} compact />);
+
+ expect(screen.getByText("Example Page")).toBeInTheDocument();
// Compact uses border-b on the outer div
- const titleEl = screen.getByText('Example Page')
- const container = titleEl.parentElement
- expect(container).toHaveClass('border-b')
- })
-
- it('renders card variant by default', () => {
- render(<TabItem tab={mockTab} />)
-
+ const titleEl = screen.getByText("Example Page");
+ const container = titleEl.parentElement;
+ expect(container).toHaveClass("border-b");
+ });
+
+ it("renders card variant by default", () => {
+ render(<TabItem tab={mockTab} />);
+
// Default uses Card component which has rounded class
- const container = screen.getByText('Example Page').closest('div')?.parentElement
- expect(container).toHaveClass('rounded-lg')
- })
-})
+ const container = screen
+ .getByText("Example Page")
+ .closest("div")?.parentElement;
+ expect(container).toHaveClass("rounded-lg");
+ });
+});
diff --git a/dashboard/src/components/molecules/TabItem.tsx b/dashboard/src/components/molecules/TabItem.tsx
index e53c7ec0..2951fca0 100644
--- a/dashboard/src/components/molecules/TabItem.tsx
+++ b/dashboard/src/components/molecules/TabItem.tsx
@@ -1,9 +1,9 @@
-import { Card } from '../atoms'
-import type { InstanceTab } from '../../generated/types'
+import { Card } from "../atoms";
+import type { InstanceTab } from "../../generated/types";
interface Props {
- tab: InstanceTab
- compact?: boolean
+ tab: InstanceTab;
+ compact?: boolean;
}
export default function TabItem({ tab, compact }: Props) {
@@ -11,19 +11,19 @@ export default function TabItem({ tab, compact }: Props) {
return (
<div className="border-b border-border-subtle py-2">
<div className="truncate text-sm text-text-primary">
- {tab.title || 'Untitled'}
+ {tab.title || "Untitled"}
</div>
<div className="truncate text-xs text-text-muted">{tab.url}</div>
</div>
- )
+ );
}
return (
<Card className="p-2">
<div className="truncate text-sm text-text-primary">
- {tab.title || 'Untitled'}
+ {tab.title || "Untitled"}
</div>
<div className="truncate text-xs text-text-muted">{tab.url}</div>
</Card>
- )
+ );
}
diff --git a/dashboard/src/components/molecules/TabsChart.test.tsx b/dashboard/src/components/molecules/TabsChart.test.tsx
index 17e1abb8..31d49030 100644
--- a/dashboard/src/components/molecules/TabsChart.test.tsx
+++ b/dashboard/src/components/molecules/TabsChart.test.tsx
@@ -1,7 +1,7 @@
-import { render, screen } from '@testing-library/react'
-import { describe, it, expect, beforeAll } from 'vitest'
-import TabsChart from './TabsChart'
-import type { TabDataPoint } from '../../stores/useAppStore'
+import { render, screen } from "@testing-library/react";
+import { describe, it, expect, beforeAll } from "vitest";
+import TabsChart from "./TabsChart";
+import type { TabDataPoint } from "../../stores/useAppStore";
// Mock ResizeObserver for Recharts ResponsiveContainer
beforeAll(() => {
@@ -10,22 +10,22 @@ beforeAll(() => {
unobserve() {}
disconnect() {}
}
- window.ResizeObserver = ResizeObserverMock as any
-})
+ window.ResizeObserver = ResizeObserverMock as any;
+});
const mockInstances = [
- { id: 'inst_1', profileName: 'profile-1' },
- { id: 'inst_2', profileName: 'profile-2' },
-]
+ { 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('TabsChart', () => {
- describe('empty states', () => {
+describe("TabsChart", () => {
+ describe("empty states", () => {
it('shows "No running instances" when instances array is empty', () => {
render(
<TabsChart
@@ -33,10 +33,10 @@ describe('TabsChart', () => {
instances={[]}
selectedInstanceId={null}
onSelectInstance={() => {}}
- />
- )
- expect(screen.getByText('No running instances')).toBeInTheDocument()
- })
+ />,
+ );
+ expect(screen.getByText("No running instances")).toBeInTheDocument();
+ });
it('shows "Collecting data..." when data array is empty', () => {
render(
@@ -45,10 +45,10 @@ describe('TabsChart', () => {
instances={mockInstances}
selectedInstanceId={null}
onSelectInstance={() => {}}
- />
- )
- expect(screen.getByText('Collecting data...')).toBeInTheDocument()
- })
+ />,
+ );
+ expect(screen.getByText("Collecting data...")).toBeInTheDocument();
+ });
it('shows "No running instances" when both are empty (instances takes priority)', () => {
render(
@@ -57,24 +57,26 @@ describe('TabsChart', () => {
instances={[]}
selectedInstanceId={null}
onSelectInstance={() => {}}
- />
- )
- expect(screen.getByText('No running instances')).toBeInTheDocument()
- })
- })
+ />,
+ );
+ expect(screen.getByText("No running instances")).toBeInTheDocument();
+ });
+ });
- describe('chart rendering', () => {
- it('renders chart container when data and instances exist', () => {
+ describe("chart rendering", () => {
+ it("renders chart container when data and instances exist", () => {
const { container } = render(
<TabsChart
data={mockData}
instances={mockInstances}
selectedInstanceId={null}
onSelectInstance={() => {}}
- />
- )
+ />,
+ );
// Should render the chart container (not the empty state)
- expect(container.querySelector('.recharts-responsive-container')).toBeInTheDocument()
- })
- })
-})
+ expect(
+ container.querySelector(".recharts-responsive-container"),
+ ).toBeInTheDocument();
+ });
+ });
+});
diff --git a/dashboard/src/components/molecules/TabsChart.tsx b/dashboard/src/components/molecules/TabsChart.tsx
index 832110eb..e5b3f2b1 100644
--- a/dashboard/src/components/molecules/TabsChart.tsx
+++ b/dashboard/src/components/molecules/TabsChart.tsx
@@ -1,4 +1,4 @@
-import { useMemo } from 'react'
+import { useMemo } from "react";
import {
LineChart,
Line,
@@ -6,33 +6,33 @@ import {
YAxis,
Tooltip,
ResponsiveContainer,
-} from 'recharts'
-import type { TabDataPoint } from '../../stores/useAppStore'
+} from "recharts";
+import type { TabDataPoint } from "../../stores/useAppStore";
interface Props {
- data: TabDataPoint[]
- instances: { id: string; profileName: string }[]
- selectedInstanceId: string | null
- onSelectInstance: (id: string) => void
+ data: TabDataPoint[];
+ instances: { id: string; profileName: string }[];
+ selectedInstanceId: string | null;
+ onSelectInstance: (id: string) => void;
}
// Colors for different instances
const COLORS = [
- '#f97316', // orange (primary)
- '#3b82f6', // blue
- '#22c55e', // green
- '#eab308', // yellow
- '#ef4444', // red
- '#8b5cf6', // purple
- '#ec4899', // pink
- '#14b8a6', // teal
-]
+ "#f97316", // orange (primary)
+ "#3b82f6", // blue
+ "#22c55e", // green
+ "#eab308", // yellow
+ "#ef4444", // red
+ "#8b5cf6", // purple
+ "#ec4899", // pink
+ "#14b8a6", // teal
+];
function formatTime(timestamp: number): string {
- return new Date(timestamp).toLocaleTimeString('en-GB', {
- hour: '2-digit',
- minute: '2-digit',
- })
+ return new Date(timestamp).toLocaleTimeString("en-GB", {
+ hour: "2-digit",
+ minute: "2-digit",
+ });
}
export default function TabsChart({
@@ -42,27 +42,28 @@ export default function TabsChart({
onSelectInstance,
}: Props) {
const instanceColors = useMemo(() => {
- const colors: Record<string, string> = {}
+ const colors: Record<string, string> = {};
instances.forEach((inst, i) => {
- colors[inst.id] = COLORS[i % COLORS.length]
- })
- return colors
- }, [instances])
+ colors[inst.id] = COLORS[i % COLORS.length];
+ });
+ return colors;
+ }, [instances]);
if (data.length === 0 || instances.length === 0) {
return (
<div className="flex h-[200px] items-center justify-center rounded-lg border border-border-subtle bg-bg-surface text-sm text-text-muted">
- {instances.length === 0
- ? 'No running instances'
- : 'Collecting data...'}
+ {instances.length === 0 ? "No running instances" : "Collecting data..."}
</div>
- )
+ );
}
return (
<div className="rounded-lg border border-border-subtle bg-bg-surface">
<ResponsiveContainer width="100%" height={200}>
- <LineChart data={data} margin={{ top: 16, right: 16, bottom: 8, left: 8 }}>
+ <LineChart
+ data={data}
+ margin={{ top: 16, right: 16, bottom: 8, left: 8 }}
+ >
<XAxis
dataKey="timestamp"
tickFormatter={formatTime}
@@ -75,22 +76,22 @@ export default function TabsChart({
stroke="#666"
fontSize={11}
allowDecimals={false}
- domain={[0, 'auto']}
+ domain={[0, "auto"]}
tickLine={false}
axisLine={false}
width={30}
/>
<Tooltip
contentStyle={{
- background: '#1a1a1a',
- border: '1px solid #333',
- borderRadius: '6px',
- fontSize: '12px',
+ background: "#1a1a1a",
+ border: "1px solid #333",
+ borderRadius: "6px",
+ fontSize: "12px",
}}
labelFormatter={(label) => formatTime(label as number)}
formatter={(value, name) => {
- const inst = instances.find((i) => i.id === name)
- return [value ?? 0, inst?.profileName || name]
+ const inst = instances.find((i) => i.id === name);
+ return [value ?? 0, inst?.profileName || name];
}}
/>
{instances.map((inst) => (
@@ -108,12 +109,12 @@ export default function TabsChart({
activeDot={{
r: 4,
onClick: () => onSelectInstance(inst.id),
- style: { cursor: 'pointer' },
+ style: { cursor: "pointer" },
}}
/>
))}
</LineChart>
</ResponsiveContainer>
</div>
- )
+ );
}
diff --git a/dashboard/src/components/molecules/index.ts b/dashboard/src/components/molecules/index.ts
index 1ba40128..d0098673 100644
--- a/dashboard/src/components/molecules/index.ts
+++ b/dashboard/src/components/molecules/index.ts
@@ -1,10 +1,10 @@
-export { default as NavBar } from './NavBar'
-export { default as ProfileCard } from './ProfileCard'
-export { default as ProfileDetailsModal } from './ProfileDetailsModal'
-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 AgentItem } from './AgentItem'
-export { default as ActivityLine } from './ActivityLine'
-export { default as TabsChart } from './TabsChart'
+export { default as NavBar } from "./NavBar";
+export { default as ProfileCard } from "./ProfileCard";
+export { default as ProfileDetailsModal } from "./ProfileDetailsModal";
+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 AgentItem } from "./AgentItem";
+export { default as ActivityLine } from "./ActivityLine";
+export { default as TabsChart } from "./TabsChart";
diff --git a/dashboard/src/generated/types.ts b/dashboard/src/generated/types.ts
index 63219f63..29a77ae7 100644
--- a/dashboard/src/generated/types.ts
+++ b/dashboard/src/generated/types.ts
@@ -64,7 +64,7 @@ export interface ActivityEvent {
method: string;
path: string;
timestamp: string;
- details?: { [key: string]: any};
+ details?: { [key: string]: any };
}
/**
* ScreencastSettings configures live tab previews.
diff --git a/dashboard/src/index.css b/dashboard/src/index.css
index d31d605b..1c2f5af8 100644
--- a/dashboard/src/index.css
+++ b/dashboard/src/index.css
@@ -1,8 +1,8 @@
-@import 'tailwindcss';
+@import "tailwindcss";
@theme {
- --font-sans: 'Geist', ui-sans-serif, system-ui, sans-serif;
- --font-mono: 'Geist Mono', ui-monospace, monospace;
+ --font-sans: "Geist", ui-sans-serif, system-ui, sans-serif;
+ --font-mono: "Geist Mono", ui-monospace, monospace;
/* Colors - matching Poseidon dark theme */
--color-bg-app: #0a0a0a;
@@ -30,32 +30,36 @@
/* Geist font - load via CDN */
@font-face {
- font-family: 'Geist';
- src: url('https://cdn.jsdelivr.net/npm/[email protected]/dist/fonts/geist-sans/Geist-Regular.woff2') format('woff2');
+ font-family: "Geist";
+ src: url("https://cdn.jsdelivr.net/npm/[email protected]/dist/fonts/geist-sans/Geist-Regular.woff2")
+ format("woff2");
font-weight: 400;
font-style: normal;
font-display: swap;
}
@font-face {
- font-family: 'Geist';
- src: url('https://cdn.jsdelivr.net/npm/[email protected]/dist/fonts/geist-sans/Geist-Medium.woff2') format('woff2');
+ font-family: "Geist";
+ src: url("https://cdn.jsdelivr.net/npm/[email protected]/dist/fonts/geist-sans/Geist-Medium.woff2")
+ format("woff2");
font-weight: 500;
font-style: normal;
font-display: swap;
}
@font-face {
- font-family: 'Geist';
- src: url('https://cdn.jsdelivr.net/npm/[email protected]/dist/fonts/geist-sans/Geist-SemiBold.woff2') format('woff2');
+ font-family: "Geist";
+ src: url("https://cdn.jsdelivr.net/npm/[email protected]/dist/fonts/geist-sans/Geist-SemiBold.woff2")
+ format("woff2");
font-weight: 600;
font-style: normal;
font-display: swap;
}
@font-face {
- font-family: 'Geist Mono';
- src: url('https://cdn.jsdelivr.net/npm/[email protected]/dist/fonts/geist-mono/GeistMono-Regular.woff2') format('woff2');
+ font-family: "Geist Mono";
+ src: url("https://cdn.jsdelivr.net/npm/[email protected]/dist/fonts/geist-mono/GeistMono-Regular.woff2")
+ format("woff2");
font-weight: 400;
font-style: normal;
font-display: swap;
diff --git a/dashboard/src/main.tsx b/dashboard/src/main.tsx
index 520b5201..15753afa 100644
--- a/dashboard/src/main.tsx
+++ b/dashboard/src/main.tsx
@@ -1,10 +1,10 @@
-import { StrictMode } from 'react'
-import { createRoot } from 'react-dom/client'
-import './index.css'
-import App from './App'
+import { StrictMode } from "react";
+import { createRoot } from "react-dom/client";
+import "./index.css";
+import App from "./App";
-createRoot(document.getElementById('root')!).render(
+createRoot(document.getElementById("root")!).render(
<StrictMode>
<App />
- </StrictMode>
-)
+ </StrictMode>,
+);
diff --git a/dashboard/src/pages/AgentsPage.tsx b/dashboard/src/pages/AgentsPage.tsx
index 869da629..764977e0 100644
--- a/dashboard/src/pages/AgentsPage.tsx
+++ b/dashboard/src/pages/AgentsPage.tsx
@@ -1,15 +1,15 @@
-import { useEffect } from 'react'
-import { useAppStore } from '../stores/useAppStore'
-import { EmptyState } from '../components/atoms'
-import { AgentItem, ActivityLine } from '../components/molecules'
-import * as api from '../services/api'
+import { useEffect } from "react";
+import { useAppStore } from "../stores/useAppStore";
+import { EmptyState } from "../components/atoms";
+import { AgentItem, ActivityLine } from "../components/molecules";
+import * as api from "../services/api";
const filters = [
- { key: 'all', label: 'All' },
- { key: 'navigate', label: 'Navigate' },
- { key: 'snapshot', label: 'Snapshot' },
- { key: 'action', label: 'Actions' },
-]
+ { key: "all", label: "All" },
+ { key: "navigate", label: "Navigate" },
+ { key: "snapshot", label: "Snapshot" },
+ { key: "action", label: "Actions" },
+];
export default function AgentsPage() {
const {
@@ -20,30 +20,30 @@ export default function AgentsPage() {
setAgents,
setSelectedAgentId,
setEventFilter,
- } = useAppStore()
+ } = useAppStore();
const loadAgents = async () => {
try {
- const data = await api.fetchAgents()
- setAgents(data)
+ const data = await api.fetchAgents();
+ setAgents(data);
} catch (e) {
- console.error('Failed to load agents', e)
+ console.error("Failed to load agents", e);
}
- }
+ };
// Agents are loaded via SSE init event — only load if empty
useEffect(() => {
if (agents.length === 0) {
- loadAgents()
+ loadAgents();
}
- }, [])
+ }, []);
const filteredEvents = events.filter((e) => {
- if (selectedAgentId && e.agentId !== selectedAgentId) return false
- if (eventFilter === 'all') return true
- if (eventFilter === 'action') return e.type === 'action'
- return e.type === eventFilter
- })
+ if (selectedAgentId && e.agentId !== selectedAgentId) return false;
+ if (eventFilter === "all") return true;
+ if (eventFilter === "action") return e.type === "action";
+ return e.type === eventFilter;
+ });
return (
<div className="flex flex-1">
@@ -58,7 +58,8 @@ export default function AgentsPage() {
<div className="mb-2 text-2xl">🦀</div>
No agents connected yet
<div className="mt-1 text-xs">
- Make an API call with <code className="text-primary">X-Agent-Id</code> header
+ Make an API call with{" "}
+ <code className="text-primary">X-Agent-Id</code> header
</div>
</div>
) : (
@@ -66,8 +67,8 @@ export default function AgentsPage() {
<button
className={`rounded-lg px-3 py-2 text-left text-sm transition-all ${
!selectedAgentId
- ? 'bg-primary/10 text-primary'
- : 'text-text-muted hover:bg-bg-elevated'
+ ? "bg-primary/10 text-primary"
+ : "text-text-muted hover:bg-bg-elevated"
}`}
onClick={() => setSelectedAgentId(null)}
>
@@ -89,15 +90,17 @@ export default function AgentsPage() {
{/* Activity feed */}
<div className="flex flex-1 flex-col">
<div className="flex items-center justify-between border-b border-border-subtle bg-bg-surface px-4 py-2">
- <h2 className="text-sm font-semibold text-text-secondary">Activity Feed</h2>
+ <h2 className="text-sm font-semibold text-text-secondary">
+ Activity Feed
+ </h2>
<div className="flex gap-1">
{filters.map((f) => (
<button
key={f.key}
className={`rounded px-2 py-1 text-xs font-medium transition-all ${
eventFilter === f.key
- ? 'bg-primary/10 text-primary'
- : 'text-text-muted hover:bg-bg-elevated hover:text-text-secondary'
+ ? "bg-primary/10 text-primary"
+ : "text-text-muted hover:bg-bg-elevated hover:text-text-secondary"
}`}
onClick={() => setEventFilter(f.key)}
>
@@ -118,5 +121,5 @@ export default function AgentsPage() {
</div>
</div>
</div>
- )
+ );
}
diff --git a/dashboard/src/pages/MonitoringPage.tsx b/dashboard/src/pages/MonitoringPage.tsx
index 81eddbb6..426449c9 100644
--- a/dashboard/src/pages/MonitoringPage.tsx
+++ b/dashboard/src/pages/MonitoringPage.tsx
@@ -1,11 +1,11 @@
-import { useEffect, useState, useCallback, useRef } from 'react'
-import { useAppStore } from '../stores/useAppStore'
-import { EmptyState, Button } from '../components/atoms'
-import { TabsChart, InstanceListItem, TabItem } from '../components/molecules'
-import type { InstanceTab } from '../generated/types'
-import * as api from '../services/api'
+import { useEffect, useState, useCallback, useRef } from "react";
+import { useAppStore } from "../stores/useAppStore";
+import { EmptyState, Button } from "../components/atoms";
+import { TabsChart, InstanceListItem, TabItem } from "../components/molecules";
+import type { InstanceTab } from "../generated/types";
+import * as api from "../services/api";
-const POLL_INTERVAL = 30000 // 30 seconds
+const POLL_INTERVAL = 30000; // 30 seconds
export default function MonitoringPage() {
const {
@@ -16,92 +16,92 @@ export default function MonitoringPage() {
currentTabs,
addChartDataPoint,
setCurrentTabs,
- } = useAppStore()
- const [selectedId, setSelectedId] = useState<string | null>(null)
- const pollRef = useRef<ReturnType<typeof setInterval> | null>(null)
+ } = useAppStore();
+ const [selectedId, setSelectedId] = useState<string | null>(null);
+ const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
const loadInstances = async () => {
- setInstancesLoading(true)
+ setInstancesLoading(true);
try {
- const data = await api.fetchInstances()
- setInstances(data)
+ const data = await api.fetchInstances();
+ setInstances(data);
} catch (e) {
- console.error('Failed to load instances', e)
+ console.error("Failed to load instances", e);
} finally {
- setInstancesLoading(false)
+ setInstancesLoading(false);
}
- }
+ };
// Fetch tabs for all running instances
const fetchAllInstanceTabs = useCallback(async () => {
- const runningInstances = instances.filter((i) => i.status === 'running')
- if (runningInstances.length === 0) return
+ const runningInstances = instances.filter((i) => i.status === "running");
+ if (runningInstances.length === 0) return;
try {
// Use aggregated endpoint that returns proper format
- const allTabs = await api.fetchAllTabs()
- const tabsArray = Array.isArray(allTabs) ? allTabs : []
+ const allTabs = await api.fetchAllTabs();
+ const tabsArray = Array.isArray(allTabs) ? allTabs : [];
- const timestamp = Date.now()
- const dataPoint: Record<string, number> = { timestamp }
- const tabsByInstance: Record<string, InstanceTab[]> = {}
+ const timestamp = Date.now();
+ const dataPoint: Record<string, number> = { timestamp };
+ const tabsByInstance: Record<string, InstanceTab[]> = {};
// Group tabs by instance
for (const inst of runningInstances) {
- const instTabs = tabsArray.filter((t) => t.instanceId === inst.id)
- dataPoint[inst.id] = instTabs.length
- tabsByInstance[inst.id] = instTabs
+ const instTabs = tabsArray.filter((t) => t.instanceId === inst.id);
+ dataPoint[inst.id] = instTabs.length;
+ tabsByInstance[inst.id] = instTabs;
}
- addChartDataPoint(dataPoint as any)
- setCurrentTabs(tabsByInstance)
+ addChartDataPoint(dataPoint as any);
+ setCurrentTabs(tabsByInstance);
} catch (e) {
- console.error('Failed to fetch tabs:', e)
+ console.error("Failed to fetch tabs:", e);
}
- }, [instances, addChartDataPoint, setCurrentTabs])
+ }, [instances, addChartDataPoint, setCurrentTabs]);
// Initial load
useEffect(() => {
if (instances.length === 0) {
- loadInstances()
+ loadInstances();
}
- }, [])
+ }, []);
// Poll tabs
useEffect(() => {
- fetchAllInstanceTabs()
- pollRef.current = setInterval(fetchAllInstanceTabs, POLL_INTERVAL)
+ fetchAllInstanceTabs();
+ pollRef.current = setInterval(fetchAllInstanceTabs, POLL_INTERVAL);
return () => {
- if (pollRef.current) clearInterval(pollRef.current)
- }
- }, [fetchAllInstanceTabs])
+ if (pollRef.current) clearInterval(pollRef.current);
+ };
+ }, [fetchAllInstanceTabs]);
// Auto-select first running instance
useEffect(() => {
if (!selectedId) {
- const firstRunning = instances.find((i) => i.status === 'running')
- if (firstRunning) setSelectedId(firstRunning.id)
+ const firstRunning = instances.find((i) => i.status === "running");
+ if (firstRunning) setSelectedId(firstRunning.id);
}
- }, [instances, selectedId])
+ }, [instances, selectedId]);
const handleStop = async (id: string) => {
try {
- await api.stopInstance(id)
+ await api.stopInstance(id);
} catch (e) {
- console.error('Failed to stop instance', e)
+ console.error("Failed to stop instance", e);
}
- }
+ };
- const selectedInstance = instances.find((i) => i.id === selectedId)
- const selectedTabs = selectedId ? currentTabs[selectedId] || [] : []
- const runningInstances = instances.filter((i) => i.status === 'running')
+ const selectedInstance = instances.find((i) => i.id === selectedId);
+ const selectedTabs = selectedId ? currentTabs[selectedId] || [] : [];
+ const runningInstances = instances.filter((i) => i.status === "running");
if (instances.length === 0) {
return (
<div className="flex flex-1 items-center justify-center p-4">
<EmptyState title="Waiting for instances..." icon="📡" />
</div>
- )
+ );
}
return (
@@ -149,11 +149,11 @@ export default function MonitoringPage() {
{selectedInstance.profileName}
</h3>
<div className="text-xs text-text-muted">
- Port {selectedInstance.port} ·{' '}
- {selectedInstance.headless ? 'Headless' : 'Headed'}
+ Port {selectedInstance.port} ·{" "}
+ {selectedInstance.headless ? "Headless" : "Headed"}
</div>
</div>
- {selectedInstance.status === 'running' && (
+ {selectedInstance.status === "running" && (
<Button
size="sm"
variant="danger"
@@ -190,5 +190,5 @@ export default function MonitoringPage() {
</div>
</div>
</div>
- )
+ );
}
diff --git a/dashboard/src/pages/ProfilesPage.tsx b/dashboard/src/pages/ProfilesPage.tsx
index 078ad2f1..de42c820 100644
--- a/dashboard/src/pages/ProfilesPage.tsx
+++ b/dashboard/src/pages/ProfilesPage.tsx
@@ -1,9 +1,9 @@
-import { useEffect, useState, useMemo } from 'react'
-import { useAppStore } from '../stores/useAppStore'
-import { Toolbar, EmptyState, Button, Modal, Input } from '../components/atoms'
-import { ProfileCard, ProfileDetailsModal } from '../components/molecules'
-import * as api from '../services/api'
-import type { Profile } from '../generated/types'
+import { useEffect, useState, useMemo } from "react";
+import { useAppStore } from "../stores/useAppStore";
+import { Toolbar, EmptyState, Button, Modal, Input } from "../components/atoms";
+import { ProfileCard, ProfileDetailsModal } from "../components/molecules";
+import * as api from "../services/api";
+import type { Profile } from "../generated/types";
export default function ProfilesPage() {
const {
@@ -13,130 +13,130 @@ export default function ProfilesPage() {
setProfiles,
setProfilesLoading,
setInstances,
- } = useAppStore()
- const [showCreate, setShowCreate] = useState(false)
- const [showLaunch, setShowLaunch] = useState<string | null>(null)
- const [showDetails, setShowDetails] = useState<Profile | null>(null)
+ } = useAppStore();
+ const [showCreate, setShowCreate] = useState(false);
+ const [showLaunch, setShowLaunch] = useState<string | null>(null);
+ const [showDetails, setShowDetails] = useState<Profile | null>(null);
// Create form
- const [createName, setCreateName] = useState('')
- const [createUseWhen, setCreateUseWhen] = useState('')
- const [createSource, setCreateSource] = useState('')
+ const [createName, setCreateName] = useState("");
+ const [createUseWhen, setCreateUseWhen] = useState("");
+ const [createSource, setCreateSource] = useState("");
// Launch form
- const [launchPort, setLaunchPort] = useState('9868')
- const [launchHeadless, setLaunchHeadless] = useState(false)
- const [copyFeedback, setCopyFeedback] = useState('')
+ const [launchPort, setLaunchPort] = useState("9868");
+ const [launchHeadless, setLaunchHeadless] = useState(false);
+ const [copyFeedback, setCopyFeedback] = useState("");
const loadProfiles = async () => {
- setProfilesLoading(true)
+ setProfilesLoading(true);
try {
- const data = await api.fetchProfiles()
- setProfiles(data)
+ const data = await api.fetchProfiles();
+ setProfiles(data);
} catch (e) {
- console.error('Failed to load profiles', e)
+ console.error("Failed to load profiles", e);
} finally {
- setProfilesLoading(false)
+ setProfilesLoading(false);
}
- }
+ };
// Only load on mount if empty — SSE handles updates
useEffect(() => {
if (profiles.length === 0) {
- loadProfiles()
+ loadProfiles();
}
- }, [])
+ }, []);
const handleCreate = async () => {
- if (!createName.trim()) return
+ if (!createName.trim()) return;
try {
await api.createProfile({
name: createName.trim(),
useWhen: createUseWhen.trim() || undefined,
- })
- setShowCreate(false)
- setCreateName('')
- setCreateUseWhen('')
- setCreateSource('')
- loadProfiles()
+ });
+ setShowCreate(false);
+ setCreateName("");
+ setCreateUseWhen("");
+ setCreateSource("");
+ loadProfiles();
} catch (e) {
- console.error('Failed to create profile', e)
+ console.error("Failed to create profile", e);
}
- }
+ };
const handleLaunch = async () => {
- if (!showLaunch) return
+ if (!showLaunch) return;
try {
await api.launchInstance({
name: showLaunch,
- port: launchPort || '9868',
- mode: launchHeadless ? '' : 'headed',
- })
- setShowLaunch(null)
- setLaunchPort('9868')
- setLaunchHeadless(false)
+ port: launchPort || "9868",
+ mode: launchHeadless ? "" : "headed",
+ });
+ setShowLaunch(null);
+ setLaunchPort("9868");
+ setLaunchHeadless(false);
} catch (e) {
- console.error('Failed to launch instance', e)
+ console.error("Failed to launch instance", e);
}
- }
+ };
const handleStop = async (profileName: string) => {
- const inst = instanceByProfile.get(profileName)
- if (!inst) return
+ const inst = instanceByProfile.get(profileName);
+ if (!inst) return;
try {
- await api.stopInstance(inst.id)
- const updated = await api.fetchInstances()
- setInstances(updated)
+ await api.stopInstance(inst.id);
+ const updated = await api.fetchInstances();
+ setInstances(updated);
} catch (e) {
- console.error('Failed to stop instance', e)
+ console.error("Failed to stop instance", e);
}
- }
+ };
const handleDelete = async () => {
- if (!showDetails?.id) return
+ if (!showDetails?.id) return;
try {
- await api.deleteProfile(showDetails.id)
- setShowDetails(null)
- loadProfiles()
+ await api.deleteProfile(showDetails.id);
+ setShowDetails(null);
+ loadProfiles();
} catch (e) {
- console.error('Failed to delete profile', e)
+ console.error("Failed to delete profile", e);
}
- }
+ };
// Generate launch command
const launchCommand = useMemo(() => {
- if (!showLaunch) return ''
- const profile = profiles.find((p) => p.name === showLaunch)
- const profileId = profile?.id || showLaunch
- const mode = launchHeadless ? 'headless' : 'headed'
- const port = launchPort || 'auto'
- return `curl -X POST http://localhost:9867/instances/start -H "Content-Type: application/json" -d '{"profileId":"${profileId}","mode":"${mode}","port":"${port}"}'`
- }, [showLaunch, launchHeadless, launchPort, profiles])
+ if (!showLaunch) return "";
+ const profile = profiles.find((p) => p.name === showLaunch);
+ const profileId = profile?.id || showLaunch;
+ const mode = launchHeadless ? "headless" : "headed";
+ const port = launchPort || "auto";
+ return `curl -X POST http://localhost:9867/instances/start -H "Content-Type: application/json" -d '{"profileId":"${profileId}","mode":"${mode}","port":"${port}"}'`;
+ }, [showLaunch, launchHeadless, launchPort, profiles]);
const handleCopyCommand = async () => {
try {
- await navigator.clipboard.writeText(launchCommand)
- setCopyFeedback('Copied!')
- setTimeout(() => setCopyFeedback(''), 2000)
+ await navigator.clipboard.writeText(launchCommand);
+ setCopyFeedback("Copied!");
+ setTimeout(() => setCopyFeedback(""), 2000);
} catch {
- setCopyFeedback('Failed to copy')
- setTimeout(() => setCopyFeedback(''), 2000)
+ setCopyFeedback("Failed to copy");
+ setTimeout(() => setCopyFeedback(""), 2000);
}
- }
+ };
- const instanceByProfile = new Map(instances.map((i) => [i.profileName, i]))
+ const instanceByProfile = new Map(instances.map((i) => [i.profileName, i]));
return (
<div className="flex flex-1 flex-col">
<Toolbar
actions={[
{
- key: 'new',
- label: '+ New Profile',
+ key: "new",
+ label: "+ New Profile",
onClick: () => setShowCreate(true),
- variant: 'primary',
+ variant: "primary",
},
- { key: 'refresh', label: 'Refresh', onClick: loadProfiles },
+ { key: "refresh", label: "Refresh", onClick: loadProfiles },
]}
/>
@@ -272,10 +272,12 @@ export default function ProfilesPage() {
{/* Profile Details Modal */}
<ProfileDetailsModal
profile={showDetails}
- instance={showDetails ? instanceByProfile.get(showDetails.name) : undefined}
+ instance={
+ showDetails ? instanceByProfile.get(showDetails.name) : undefined
+ }
onClose={() => setShowDetails(null)}
onDelete={handleDelete}
/>
</div>
- )
+ );
}
diff --git a/dashboard/src/pages/SettingsPage.tsx b/dashboard/src/pages/SettingsPage.tsx
index 360fd39c..1ec0e919 100644
--- a/dashboard/src/pages/SettingsPage.tsx
+++ b/dashboard/src/pages/SettingsPage.tsx
@@ -1,41 +1,44 @@
-import { useEffect, useState } from 'react'
-import { useAppStore } from '../stores/useAppStore'
-import { Button, Card } from '../components/atoms'
-import * as api from '../services/api'
-import type { Settings } from '../types'
+import { useEffect, useState } from "react";
+import { useAppStore } from "../stores/useAppStore";
+import { Button, Card } from "../components/atoms";
+import * as api from "../services/api";
+import type { Settings } from "../types";
export default function SettingsPage() {
- const { settings, serverInfo, setSettings, setServerInfo } = useAppStore()
- const [local, setLocal] = useState<Settings>(settings)
- const [saving, setSaving] = useState(false)
+ const { settings, serverInfo, setSettings, setServerInfo } = useAppStore();
+ const [local, setLocal] = useState<Settings>(settings);
+ const [saving, setSaving] = useState(false);
useEffect(() => {
const load = async () => {
try {
- const [s, h] = await Promise.all([api.fetchSettings(), api.fetchHealth()])
- setSettings(s)
- setLocal(s)
- setServerInfo(h)
+ const [s, h] = await Promise.all([
+ api.fetchSettings(),
+ api.fetchHealth(),
+ ]);
+ setSettings(s);
+ setLocal(s);
+ setServerInfo(h);
} catch (e) {
- console.error('Failed to load settings', e)
+ console.error("Failed to load settings", e);
}
- }
- load()
- }, [])
+ };
+ load();
+ }, []);
const handleSave = async () => {
- setSaving(true)
+ setSaving(true);
try {
- const updated = await api.updateSettings(local)
- setSettings(updated)
+ const updated = await api.updateSettings(local);
+ setSettings(updated);
} catch (e) {
- console.error('Failed to save settings', e)
+ console.error("Failed to save settings", e);
} finally {
- setSaving(false)
+ setSaving(false);
}
- }
+ };
- const handleReset = () => setLocal(settings)
+ const handleReset = () => setLocal(settings);
return (
<div className="flex flex-1 flex-col overflow-auto">
@@ -44,14 +47,16 @@ export default function SettingsPage() {
Reset
</Button>
<Button variant="primary" onClick={handleSave} disabled={saving}>
- {saving ? 'Saving...' : 'Apply Settings'}
+ {saving ? "Saving..." : "Apply Settings"}
</Button>
</div>
<div className="mx-auto w-full max-w-2xl space-y-6 p-6">
{/* Screencast */}
<Card className="p-4">
- <h3 className="mb-4 text-sm font-semibold text-text-primary">📺 Screencast</h3>
+ <h3 className="mb-4 text-sm font-semibold text-text-primary">
+ 📺 Screencast
+ </h3>
<div className="space-y-4">
<div className="flex items-center justify-between">
<label className="text-sm text-text-secondary">Frame Rate</label>
@@ -85,7 +90,10 @@ export default function SettingsPage() {
onChange={(e) =>
setLocal({
...local,
- screencast: { ...local.screencast, quality: +e.target.value },
+ screencast: {
+ ...local.screencast,
+ quality: +e.target.value,
+ },
})
}
className="w-32"
@@ -102,7 +110,10 @@ export default function SettingsPage() {
onChange={(e) =>
setLocal({
...local,
- screencast: { ...local.screencast, maxWidth: +e.target.value },
+ screencast: {
+ ...local.screencast,
+ maxWidth: +e.target.value,
+ },
})
}
className="rounded border border-border-default bg-bg-elevated px-2 py-1 text-sm text-text-primary"
@@ -119,12 +130,19 @@ export default function SettingsPage() {
{/* Stealth */}
<Card className="p-4">
- <h3 className="mb-4 text-sm font-semibold text-text-primary">🛡️ Stealth</h3>
+ <h3 className="mb-4 text-sm font-semibold text-text-primary">
+ 🛡️ Stealth
+ </h3>
<div className="flex items-center justify-between">
<label className="text-sm text-text-secondary">Level</label>
<select
value={local.stealth}
- onChange={(e) => setLocal({ ...local, stealth: e.target.value as 'light' | 'full' })}
+ onChange={(e) =>
+ setLocal({
+ ...local,
+ stealth: e.target.value as "light" | "full",
+ })
+ }
className="rounded border border-border-default bg-bg-elevated px-2 py-1 text-sm text-text-primary"
>
<option value="light">Light (default)</option>
@@ -135,12 +153,14 @@ export default function SettingsPage() {
{/* Browser */}
<Card className="p-4">
- <h3 className="mb-4 text-sm font-semibold text-text-primary">🌐 Browser</h3>
+ <h3 className="mb-4 text-sm font-semibold text-text-primary">
+ 🌐 Browser
+ </h3>
<div className="space-y-3">
{[
- { key: 'blockImages', label: 'Block Images' },
- { key: 'blockMedia', label: 'Block Media' },
- { key: 'noAnimations', label: 'No Animations' },
+ { key: "blockImages", label: "Block Images" },
+ { key: "blockMedia", label: "Block Media" },
+ { key: "noAnimations", label: "No Animations" },
].map(({ key, label }) => (
<label key={key} className="flex items-center justify-between">
<span className="text-sm text-text-secondary">{label}</span>
@@ -163,7 +183,9 @@ export default function SettingsPage() {
{/* Server Info */}
{serverInfo && (
<Card className="p-4">
- <h3 className="mb-4 text-sm font-semibold text-text-primary">📊 Server Info</h3>
+ <h3 className="mb-4 text-sm font-semibold text-text-primary">
+ 📊 Server Info
+ </h3>
<div className="grid grid-cols-2 gap-2 text-sm">
<div className="text-text-muted">Version</div>
<div className="text-text-secondary">{serverInfo.version}</div>
@@ -178,5 +200,5 @@ export default function SettingsPage() {
)}
</div>
</div>
- )
+ );
}
diff --git a/dashboard/src/pages/index.ts b/dashboard/src/pages/index.ts
index ed74329d..26911708 100644
--- a/dashboard/src/pages/index.ts
+++ b/dashboard/src/pages/index.ts
@@ -1,4 +1,4 @@
-export { default as MonitoringPage } from './MonitoringPage'
-export { default as ProfilesPage } from './ProfilesPage'
-export { default as AgentsPage } from './AgentsPage'
-export { default as SettingsPage } from './SettingsPage'
+export { default as MonitoringPage } from "./MonitoringPage";
+export { default as ProfilesPage } from "./ProfilesPage";
+export { default as AgentsPage } from "./AgentsPage";
+export { default as SettingsPage } from "./SettingsPage";
diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.ts
index ba6e4ab9..25cee471 100644
--- a/dashboard/src/services/api.ts
+++ b/dashboard/src/services/api.ts
@@ -8,136 +8,140 @@ import type {
CreateProfileRequest,
CreateProfileResponse,
LaunchInstanceRequest,
-} from '../generated/types'
+} from "../generated/types";
-const BASE = '' // Uses proxy in dev
+const BASE = ""; // Uses proxy in dev
async function request<T>(url: string, options?: RequestInit): Promise<T> {
- const res = await fetch(BASE + url, options)
+ const res = await fetch(BASE + url, options);
if (!res.ok) {
- const err = await res.json().catch(() => ({ error: res.statusText }))
- throw new Error(err.error || 'Request failed')
+ const err = await res.json().catch(() => ({ error: res.statusText }));
+ throw new Error(err.error || "Request failed");
}
- return res.json()
+ return res.json();
}
// Profiles — endpoint is /profiles (no /api prefix)
export async function fetchProfiles(): Promise<Profile[]> {
- return request<Profile[]>('/profiles')
+ return request<Profile[]>("/profiles");
}
-export async function createProfile(data: CreateProfileRequest): Promise<CreateProfileResponse> {
- return request<CreateProfileResponse>('/profiles', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
+export async function createProfile(
+ data: CreateProfileRequest,
+): Promise<CreateProfileResponse> {
+ return request<CreateProfileResponse>("/profiles", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
- })
+ });
}
export async function deleteProfile(id: string): Promise<void> {
await request<void>(`/profiles/${encodeURIComponent(id)}`, {
- method: 'DELETE',
- })
+ method: "DELETE",
+ });
}
// Instances — endpoint is /instances (no /api prefix)
export async function fetchInstances(): Promise<Instance[]> {
- return request<Instance[]>('/instances')
+ return request<Instance[]>("/instances");
}
-export async function launchInstance(data: LaunchInstanceRequest): Promise<Instance> {
- return request<Instance>('/instances/launch', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
+export async function launchInstance(
+ data: LaunchInstanceRequest,
+): Promise<Instance> {
+ return request<Instance>("/instances/launch", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
- })
+ });
}
export async function stopInstance(id: string): Promise<void> {
await request<void>(`/instances/${encodeURIComponent(id)}/stop`, {
- method: 'POST',
- })
+ method: "POST",
+ });
}
export async function fetchInstanceTabs(id: string): Promise<InstanceTab[]> {
- return request<InstanceTab[]>(`/instances/${encodeURIComponent(id)}/tabs`)
+ return request<InstanceTab[]>(`/instances/${encodeURIComponent(id)}/tabs`);
}
export async function fetchAllTabs(): Promise<InstanceTab[]> {
- return request<InstanceTab[]>('/instances/tabs')
+ return request<InstanceTab[]>("/instances/tabs");
}
// Agents — endpoint is /api/agents (dashboard API)
export async function fetchAgents(): Promise<Agent[]> {
- return request<Agent[]>('/api/agents')
+ return request<Agent[]>("/api/agents");
}
// Settings — TODO: check if endpoint exists
export async function fetchSettings(): Promise<Settings> {
- return request<Settings>('/api/settings')
+ return request<Settings>("/api/settings");
}
export async function updateSettings(settings: Settings): Promise<Settings> {
- return request<Settings>('/api/settings', {
- method: 'PUT',
- headers: { 'Content-Type': 'application/json' },
+ return request<Settings>("/api/settings", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
body: JSON.stringify(settings),
- })
+ });
}
// Health
export async function fetchHealth(): Promise<ServerInfo> {
- return request<ServerInfo>('/health')
+ return request<ServerInfo>("/health");
}
// SSE Events — endpoint is /api/events
export interface SystemEvent {
- type: 'instance.started' | 'instance.stopped' | 'instance.error'
- instance?: Instance
+ type: "instance.started" | "instance.stopped" | "instance.error";
+ instance?: Instance;
}
export interface AgentEvent {
- agentId: string
- action: string
- url?: string
- timestamp: string
+ agentId: string;
+ action: string;
+ url?: string;
+ timestamp: string;
}
export type EventHandler = {
- onSystem?: (event: SystemEvent) => void
- onAgent?: (event: AgentEvent) => void
- onInit?: (agents: Agent[]) => void
-}
+ onSystem?: (event: SystemEvent) => void;
+ onAgent?: (event: AgentEvent) => void;
+ onInit?: (agents: Agent[]) => void;
+};
export function subscribeToEvents(handlers: EventHandler): () => void {
- const es = new EventSource('/api/events')
+ const es = new EventSource("/api/events");
- es.addEventListener('init', (e) => {
+ es.addEventListener("init", (e) => {
try {
- const agents = JSON.parse(e.data) as Agent[]
- handlers.onInit?.(agents)
+ const agents = JSON.parse(e.data) as Agent[];
+ handlers.onInit?.(agents);
} catch {
// ignore
}
- })
+ });
- es.addEventListener('system', (e) => {
+ es.addEventListener("system", (e) => {
try {
- const event = JSON.parse(e.data) as SystemEvent
- handlers.onSystem?.(event)
+ const event = JSON.parse(e.data) as SystemEvent;
+ handlers.onSystem?.(event);
} catch {
// ignore
}
- })
+ });
- es.addEventListener('action', (e) => {
+ es.addEventListener("action", (e) => {
try {
- const event = JSON.parse(e.data) as AgentEvent
- handlers.onAgent?.(event)
+ const event = JSON.parse(e.data) as AgentEvent;
+ handlers.onAgent?.(event);
} catch {
// ignore
}
- })
+ });
- return () => es.close()
+ return () => es.close();
}
diff --git a/dashboard/src/stores/useAppStore.test.ts b/dashboard/src/stores/useAppStore.test.ts
index 81133782..dbefa58d 100644
--- a/dashboard/src/stores/useAppStore.test.ts
+++ b/dashboard/src/stores/useAppStore.test.ts
@@ -1,7 +1,7 @@
-import { describe, it, expect, beforeEach } from 'vitest'
-import { useAppStore } from './useAppStore'
+import { describe, it, expect, beforeEach } from "vitest";
+import { useAppStore } from "./useAppStore";
-describe('useAppStore', () => {
+describe("useAppStore", () => {
beforeEach(() => {
// Reset store between tests
useAppStore.setState({
@@ -14,131 +14,133 @@ describe('useAppStore', () => {
agents: [],
selectedAgentId: null,
events: [],
- eventFilter: 'all',
+ eventFilter: "all",
serverInfo: null,
- })
- })
-
- describe('profiles', () => {
- it('sets profiles', () => {
- const profiles = [{ name: 'test', id: 'prof_123' }] as any
- useAppStore.getState().setProfiles(profiles)
- expect(useAppStore.getState().profiles).toEqual(profiles)
- })
-
- it('sets profiles loading state', () => {
- useAppStore.getState().setProfilesLoading(true)
- expect(useAppStore.getState().profilesLoading).toBe(true)
- })
- })
-
- describe('instances', () => {
- it('sets instances', () => {
- const instances = [{ id: 'inst_123', profileName: 'test' }] as any
- useAppStore.getState().setInstances(instances)
- expect(useAppStore.getState().instances).toEqual(instances)
- })
- })
-
- describe('chart data', () => {
- it('adds chart data point', () => {
- const point = { timestamp: Date.now(), inst_123: 5 }
- useAppStore.getState().addChartDataPoint(point)
- expect(useAppStore.getState().tabsChartData).toHaveLength(1)
- expect(useAppStore.getState().tabsChartData[0]).toEqual(point)
- })
-
- it('keeps only last 60 data points', () => {
+ });
+ });
+
+ describe("profiles", () => {
+ it("sets profiles", () => {
+ const profiles = [{ name: "test", id: "prof_123" }] as any;
+ useAppStore.getState().setProfiles(profiles);
+ expect(useAppStore.getState().profiles).toEqual(profiles);
+ });
+
+ it("sets profiles loading state", () => {
+ useAppStore.getState().setProfilesLoading(true);
+ expect(useAppStore.getState().profilesLoading).toBe(true);
+ });
+ });
+
+ describe("instances", () => {
+ it("sets instances", () => {
+ const instances = [{ id: "inst_123", profileName: "test" }] as any;
+ useAppStore.getState().setInstances(instances);
+ expect(useAppStore.getState().instances).toEqual(instances);
+ });
+ });
+
+ describe("chart data", () => {
+ it("adds chart data point", () => {
+ const point = { timestamp: Date.now(), inst_123: 5 };
+ useAppStore.getState().addChartDataPoint(point);
+ expect(useAppStore.getState().tabsChartData).toHaveLength(1);
+ expect(useAppStore.getState().tabsChartData[0]).toEqual(point);
+ });
+
+ it("keeps only last 60 data points", () => {
// Add 65 points
for (let i = 0; i < 65; i++) {
- useAppStore.getState().addChartDataPoint({ timestamp: i, inst_123: i })
+ useAppStore.getState().addChartDataPoint({ timestamp: i, inst_123: i });
}
-
- const data = useAppStore.getState().tabsChartData
- expect(data).toHaveLength(60)
+
+ const data = useAppStore.getState().tabsChartData;
+ expect(data).toHaveLength(60);
// Should have points 5-64 (the last 60)
- expect(data[0].timestamp).toBe(5)
- expect(data[59].timestamp).toBe(64)
- })
-
- it('sets current tabs', () => {
- const tabs = { inst_123: [{ id: 'tab_1', url: 'https://example.com' }] } as any
- useAppStore.getState().setCurrentTabs(tabs)
- expect(useAppStore.getState().currentTabs).toEqual(tabs)
- })
- })
-
- describe('events', () => {
- it('adds event to beginning of list', () => {
- const event1 = { type: 'action', timestamp: '2024-01-01' } as any
- const event2 = { type: 'action', timestamp: '2024-01-02' } as any
-
- useAppStore.getState().addEvent(event1)
- useAppStore.getState().addEvent(event2)
-
- const events = useAppStore.getState().events
- expect(events[0]).toEqual(event2) // Most recent first
- expect(events[1]).toEqual(event1)
- })
-
- it('limits events to 100', () => {
+ expect(data[0].timestamp).toBe(5);
+ expect(data[59].timestamp).toBe(64);
+ });
+
+ it("sets current tabs", () => {
+ const tabs = {
+ inst_123: [{ id: "tab_1", url: "https://example.com" }],
+ } as any;
+ useAppStore.getState().setCurrentTabs(tabs);
+ expect(useAppStore.getState().currentTabs).toEqual(tabs);
+ });
+ });
+
+ describe("events", () => {
+ it("adds event to beginning of list", () => {
+ const event1 = { type: "action", timestamp: "2024-01-01" } as any;
+ const event2 = { type: "action", timestamp: "2024-01-02" } as any;
+
+ useAppStore.getState().addEvent(event1);
+ useAppStore.getState().addEvent(event2);
+
+ const events = useAppStore.getState().events;
+ expect(events[0]).toEqual(event2); // Most recent first
+ expect(events[1]).toEqual(event1);
+ });
+
+ it("limits events to 100", () => {
// Add 105 events
for (let i = 0; i < 105; i++) {
- useAppStore.getState().addEvent({ type: 'action', id: i } as any)
+ useAppStore.getState().addEvent({ type: "action", id: i } as any);
}
-
- const events = useAppStore.getState().events
- expect(events).toHaveLength(100)
+
+ const events = useAppStore.getState().events;
+ expect(events).toHaveLength(100);
// Most recent should be id: 104
- expect(events[0].id).toBe(104)
- })
-
- it('clears events', () => {
- useAppStore.getState().addEvent({ type: 'action' } as any)
- useAppStore.getState().clearEvents()
- expect(useAppStore.getState().events).toHaveLength(0)
- })
-
- it('sets event filter', () => {
- useAppStore.getState().setEventFilter('errors')
- expect(useAppStore.getState().eventFilter).toBe('errors')
- })
- })
-
- describe('agents', () => {
- it('sets agents', () => {
- const agents = [{ id: 'agent_1', name: 'Test Agent' }] as any
- useAppStore.getState().setAgents(agents)
- expect(useAppStore.getState().agents).toEqual(agents)
- })
-
- it('sets selected agent id', () => {
- useAppStore.getState().setSelectedAgentId('agent_1')
- expect(useAppStore.getState().selectedAgentId).toBe('agent_1')
- })
-
- it('clears selected agent id', () => {
- useAppStore.getState().setSelectedAgentId('agent_1')
- useAppStore.getState().setSelectedAgentId(null)
- expect(useAppStore.getState().selectedAgentId).toBeNull()
- })
- })
-
- describe('settings', () => {
- it('has default settings', () => {
- const settings = useAppStore.getState().settings
- expect(settings.stealth).toBe('light')
- expect(settings.screencast?.fps).toBe(1)
- })
-
- it('updates settings', () => {
+ expect(events[0].id).toBe(104);
+ });
+
+ it("clears events", () => {
+ useAppStore.getState().addEvent({ type: "action" } as any);
+ useAppStore.getState().clearEvents();
+ expect(useAppStore.getState().events).toHaveLength(0);
+ });
+
+ it("sets event filter", () => {
+ useAppStore.getState().setEventFilter("errors");
+ expect(useAppStore.getState().eventFilter).toBe("errors");
+ });
+ });
+
+ describe("agents", () => {
+ it("sets agents", () => {
+ const agents = [{ id: "agent_1", name: "Test Agent" }] as any;
+ useAppStore.getState().setAgents(agents);
+ expect(useAppStore.getState().agents).toEqual(agents);
+ });
+
+ it("sets selected agent id", () => {
+ useAppStore.getState().setSelectedAgentId("agent_1");
+ expect(useAppStore.getState().selectedAgentId).toBe("agent_1");
+ });
+
+ it("clears selected agent id", () => {
+ useAppStore.getState().setSelectedAgentId("agent_1");
+ useAppStore.getState().setSelectedAgentId(null);
+ expect(useAppStore.getState().selectedAgentId).toBeNull();
+ });
+ });
+
+ describe("settings", () => {
+ it("has default settings", () => {
+ const settings = useAppStore.getState().settings;
+ expect(settings.stealth).toBe("light");
+ expect(settings.screencast?.fps).toBe(1);
+ });
+
+ it("updates settings", () => {
const newSettings = {
screencast: { fps: 5, quality: 50, maxWidth: 1024 },
- stealth: 'strict' as const,
+ stealth: "strict" as const,
browser: { blockImages: true, blockMedia: true, noAnimations: true },
- }
- useAppStore.getState().setSettings(newSettings)
- expect(useAppStore.getState().settings).toEqual(newSettings)
- })
- })
-})
+ };
+ useAppStore.getState().setSettings(newSettings);
+ expect(useAppStore.getState().settings).toEqual(newSettings);
+ });
+ });
+});
diff --git a/dashboard/src/stores/useAppStore.ts b/dashboard/src/stores/useAppStore.ts
index d0d53416..33ea57f0 100644
--- a/dashboard/src/stores/useAppStore.ts
+++ b/dashboard/src/stores/useAppStore.ts
@@ -1,4 +1,4 @@
-import { create } from 'zustand'
+import { create } from "zustand";
import type {
Profile,
Instance,
@@ -7,59 +7,59 @@ import type {
ActivityEvent,
Settings,
ServerInfo,
-} from '../generated/types'
+} from "../generated/types";
export interface TabDataPoint {
- timestamp: number
- [instanceId: string]: number
+ timestamp: number;
+ [instanceId: string]: number;
}
interface AppState {
// Profiles
- profiles: Profile[]
- profilesLoading: boolean
- setProfiles: (profiles: Profile[]) => void
- setProfilesLoading: (loading: boolean) => void
+ profiles: Profile[];
+ profilesLoading: boolean;
+ setProfiles: (profiles: Profile[]) => void;
+ setProfilesLoading: (loading: boolean) => void;
// Instances
- instances: Instance[]
- instancesLoading: boolean
- setInstances: (instances: Instance[]) => void
- setInstancesLoading: (loading: boolean) => void
+ instances: Instance[];
+ instancesLoading: boolean;
+ setInstances: (instances: Instance[]) => void;
+ setInstancesLoading: (loading: boolean) => void;
// Chart data (persists across navigation)
- tabsChartData: TabDataPoint[]
- currentTabs: Record<string, InstanceTab[]>
- addChartDataPoint: (point: TabDataPoint) => void
- setCurrentTabs: (tabs: Record<string, InstanceTab[]>) => void
+ tabsChartData: TabDataPoint[];
+ currentTabs: Record<string, InstanceTab[]>;
+ addChartDataPoint: (point: TabDataPoint) => void;
+ setCurrentTabs: (tabs: Record<string, InstanceTab[]>) => void;
// Agents
- agents: Agent[]
- selectedAgentId: string | null
- setAgents: (agents: Agent[]) => void
- setSelectedAgentId: (id: string | null) => void
+ agents: Agent[];
+ selectedAgentId: string | null;
+ setAgents: (agents: Agent[]) => void;
+ setSelectedAgentId: (id: string | null) => void;
// Activity feed
- events: ActivityEvent[]
- eventFilter: string
- addEvent: (event: ActivityEvent) => void
- setEventFilter: (filter: string) => void
- clearEvents: () => void
+ events: ActivityEvent[];
+ eventFilter: string;
+ addEvent: (event: ActivityEvent) => void;
+ setEventFilter: (filter: string) => void;
+ clearEvents: () => void;
// Settings
- settings: Settings
- setSettings: (settings: Settings) => void
+ settings: Settings;
+ setSettings: (settings: Settings) => void;
// Server info
- serverInfo: ServerInfo | null
- setServerInfo: (info: ServerInfo | null) => void
+ serverInfo: ServerInfo | null;
+ setServerInfo: (info: ServerInfo | null) => void;
}
const defaultSettings: Settings = {
screencast: { fps: 1, quality: 30, maxWidth: 800 },
- stealth: 'light',
+ stealth: "light",
browser: { blockImages: false, blockMedia: false, noAnimations: false },
-}
+};
export const useAppStore = create<AppState>((set) => ({
// Profiles
@@ -91,7 +91,7 @@ export const useAppStore = create<AppState>((set) => ({
// Activity feed
events: [],
- eventFilter: 'all',
+ eventFilter: "all",
addEvent: (event) =>
set((state) => ({ events: [event, ...state.events].slice(0, 100) })),
setEventFilter: (eventFilter) => set({ eventFilter }),
@@ -104,4 +104,4 @@ export const useAppStore = create<AppState>((set) => ({
// Server info
serverInfo: null,
setServerInfo: (serverInfo) => set({ serverInfo }),
-}))
+}));
diff --git a/dashboard/src/test/setup.ts b/dashboard/src/test/setup.ts
index a9d0dd31..f149f27a 100644
--- a/dashboard/src/test/setup.ts
+++ b/dashboard/src/test/setup.ts
@@ -1 +1 @@
-import '@testing-library/jest-dom/vitest'
+import "@testing-library/jest-dom/vitest";
diff --git a/dashboard/src/types/index.ts b/dashboard/src/types/index.ts
index 63ed5a90..7ac3a3f7 100644
--- a/dashboard/src/types/index.ts
+++ b/dashboard/src/types/index.ts
@@ -10,4 +10,4 @@ export type {
ServerInfo,
CreateProfileRequest,
LaunchInstanceRequest,
-} from '../generated/types'
+} from "../generated/types";
diff --git a/scripts/pre-commit b/scripts/pre-commit
index fd505cf1..994a6416 100755
--- a/scripts/pre-commit
+++ b/scripts/pre-commit
@@ -1,33 +1,90 @@
#!/usr/bin/env bash
set -euo pipefail
-# Pre-commit hook: gofmt + golangci-lint on staged Go files
+# Pre-commit hook: Go + Dashboard checks
-staged=$(git diff --cached --name-only --diff-filter=ACM | grep '\.go$' || true)
-if [ -z "$staged" ]; then
- exit 0
-fi
+echo "🔍 Running pre-commit checks..."
+
+# ============================================
+# Go checks (gofmt + golangci-lint)
+# ============================================
+staged_go=$(git diff --cached --name-only --diff-filter=ACM | grep '\.go$' || true)
+if [ -n "$staged_go" ]; then
+ echo "📦 Checking Go files..."
+
+ # gofmt check
+ unformatted=$(gofmt -l $staged_go 2>/dev/null || true)
+ if [ -n "$unformatted" ]; then
+ echo "❌ gofmt: files not formatted:"
+ echo "$unformatted"
+ echo "Run: gofmt -w $unformatted"
+ exit 1
+ fi
-# 1. gofmt check
-unformatted=$(gofmt -l $staged 2>/dev/null || true)
-if [ -n "$unformatted" ]; then
- echo "❌ gofmt: files not formatted:"
- echo "$unformatted"
- echo "Run: gofmt -w $unformatted"
- exit 1
+ # golangci-lint (if available)
+ if command -v golangci-lint &>/dev/null; then
+ dirs=$(echo "$staged_go" | xargs -n1 dirname | sort -u | sed 's|$|/...|')
+ if ! golangci-lint run --timeout=5m $dirs; then
+ echo "❌ golangci-lint: issues found"
+ exit 1
+ fi
+ else
+ echo "⚠️ golangci-lint not found, skipping Go lint"
+ fi
+
+ echo "✅ Go checks passed"
fi
-# 2. golangci-lint (if available)
-if command -v golangci-lint &>/dev/null; then
- # Get unique directories of staged files
- dirs=$(echo "$staged" | xargs -n1 dirname | sort -u | sed 's|$|/...|')
- golangci-lint run --timeout=5m $dirs
- if [ $? -ne 0 ]; then
- echo "❌ golangci-lint: issues found"
- exit 1
+# ============================================
+# Dashboard checks (TypeScript + ESLint + Prettier)
+# ============================================
+staged_web=$(git diff --cached --name-only --diff-filter=ACM | grep '^dashboard/.*\.\(ts\|tsx\|js\|jsx\|css\)$' || true)
+if [ -n "$staged_web" ]; then
+ echo "🌐 Checking dashboard files..."
+
+ cd dashboard
+
+ # Check if bun is available
+ if ! command -v bun &>/dev/null; then
+ echo "⚠️ bun not found, skipping dashboard checks"
+ cd ..
+ else
+ # TypeScript check
+ echo " → TypeScript..."
+ if ! bun run tsc --noEmit 2>/dev/null; then
+ echo "❌ TypeScript: type errors found"
+ cd ..
+ exit 1
+ fi
+
+ # ESLint check
+ echo " → ESLint..."
+ if ! bun run lint 2>/dev/null; then
+ echo "❌ ESLint: issues found"
+ cd ..
+ exit 1
+ fi
+
+ # Prettier check (on staged files only)
+ echo " → Prettier..."
+ staged_rel=$(echo "$staged_web" | sed 's|^dashboard/||')
+ if ! echo "$staged_rel" | xargs bunx prettier --check 2>/dev/null; then
+ echo "❌ Prettier: files not formatted"
+ echo "Run: cd dashboard && bun run format"
+ cd ..
+ exit 1
+ fi
+
+ cd ..
+ echo "✅ Dashboard checks passed"
fi
-else
- echo "⚠️ golangci-lint not found, skipping lint check"
fi
-echo "✅ pre-commit checks passed"
+# ============================================
+# Summary
+# ============================================
+if [ -z "$staged_go" ] && [ -z "$staged_web" ]; then
+ echo "⏭️ No Go or dashboard files staged, skipping checks"
+fi
+
+echo "✅ All pre-commit checks passed"