High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat: activity tracking and monitoring (#300)
pinchtabdeve4a482da0680
diff --git a/TESTING.md b/TESTING.mdindex 263ce4f3..4a4bad9e 100644--- a/TESTING.md+++ b/TESTING.md@@ -39,7 +39,7 @@ End-to-end tests launch a real pinchtab server with Chrome and run e2e-level tes./dev e2e curl```-Runs 183 HTTP-level tests using curl against the server. Tests the REST API, navigation, snapshots, and other HTTP endpoints.+Runs 184 HTTP-level tests using curl against the server. Tests the REST API, navigation, snapshots, activity logging, and other HTTP endpoints.### CLI Tests@@ -47,7 +47,7 @@ Runs 183 HTTP-level tests using curl against the server. Tests the REST API, nav./dev e2e cli```-Runs CLI e2e tests. Tests the command-line interface directly.+Runs CLI e2e tests. Tests the command-line interface directly, including activity queries.### Both E2E Test Suites@@ -55,7 +55,7 @@ Runs CLI e2e tests. Tests the command-line interface directly../dev e2e```-Runs all E2E tests (curl + CLI, 224 tests total).+Runs all E2E tests (curl + CLI, 226 tests total).### Orchestrator E2E Suite@@ -88,7 +88,7 @@ Everything is cleaned up automatically when tests finish.E2E tests are organized in two directories:-- **`tests/e2e/scenarios/*.sh`** — HTTP curl-based tests (183 tests)+- **`tests/e2e/scenarios/*.sh`** — HTTP curl-based tests (184 tests)- Test the REST API directly- Use Docker Compose: `tests/e2e/docker-compose.yml`@@ -96,7 +96,7 @@ E2E tests are organized in two directories:- Test multi-instance flows and remote bridge attachment- Use Docker Compose: `tests/e2e/docker-compose-orchestrator.yml`-- **`tests/e2e/scenarios-cli/*.sh`** — CLI e2e tests (41 tests)+- **`tests/e2e/scenarios-cli/*.sh`** — CLI e2e tests (42 tests)- Test the command-line interface- Use Docker Compose: `tests/e2e/docker-compose.cli.yml`diff --git a/cmd/pinchtab/cmd_cli.go b/cmd/pinchtab/cmd_cli.goindex dbe1fec7..f55455ef 100644--- a/cmd/pinchtab/cmd_cli.go+++ b/cmd/pinchtab/cmd_cli.go@@ -302,6 +302,17 @@ var profilesCmd = &cobra.Command{},}+var activityCmd = &cobra.Command{+ Use: "activity",+ Short: "List recorded activity events",+ Run: func(cmd *cobra.Command, args []string) {+ cfg := config.Load()+ runCLIWith(cfg, func(client *http.Client, base, token string) {+ browseractions.Activity(client, base, token, cmd)+ })+ },+}+var instanceCmd = &cobra.Command{Use: "instance",Short: "Manage browser instances",@@ -376,6 +387,7 @@ func init() {pdfCmd.GroupID = "browser"textCmd.GroupID = "browser"profilesCmd.GroupID = "management"+ activityCmd.GroupID = "management"downloadCmd.GroupID = "browser"uploadCmd.GroupID = "browser"findCmd.GroupID = "browser"@@ -506,6 +518,7 @@ func init() {rootCmd.AddCommand(pdfCmd)rootCmd.AddCommand(textCmd)rootCmd.AddCommand(profilesCmd)+ rootCmd.AddCommand(activityCmd)rootCmd.AddCommand(downloadCmd)rootCmd.AddCommand(uploadCmd)rootCmd.AddCommand(findCmd)@@ -566,6 +579,21 @@ func init() {},})rootCmd.AddCommand(instanceCmd)++ activityCmd.AddCommand(&cobra.Command{+ Use: "tab <id>",+ Short: "List recorded activity events for a tab",+ Args: cobra.ExactArgs(1),+ Run: func(cmd *cobra.Command, args []string) {+ cfg := config.Load()+ runCLIWith(cfg, func(client *http.Client, base, token string) {+ browseractions.ActivityTab(client, base, token, args[0], cmd)+ })+ },+ })++ activityCmd.PersistentFlags().Int("limit", 200, "Maximum number of events to return")+ activityCmd.PersistentFlags().Int("age-sec", 0, "Only include events from the last N seconds")}func runCLIWith(cfg *config.RuntimeConfig, fn func(client *http.Client, base, token string)) {diff --git a/dashboard/src/App.tsx b/dashboard/src/App.tsxindex 2b490399..8e2ef36d 100644--- a/dashboard/src/App.tsx+++ b/dashboard/src/App.tsx@@ -7,6 +7,7 @@ import {useLocation,useNavigate,} from "react-router-dom";+import { ActivityPage } from "./activities";import { useAppStore } from "./stores/useAppStore";import { NavBar } from "./components/molecules";import { LoginPage, MonitoringPage, ProfilesPage, SettingsPage } from "./pages";@@ -274,10 +275,11 @@ function AppContent() {element={<Navigate to="/dashboard/monitoring" replace />}/><Route path="/dashboard/monitoring" element={<MonitoringPage />} />+ <Route path="/dashboard/activity" element={<ActivityPage />} /><Route path="/dashboard/profiles" element={<ProfilesPage />} /><Routepath="/dashboard/agents"- element={<Navigate to="/dashboard/monitoring" replace />}+ element={<Navigate to="/dashboard/activity" replace />}/><Route path="/dashboard/settings" element={<SettingsPage />} /><Routediff --git a/dashboard/src/activities/ActivityExplorer.tsx b/dashboard/src/activities/ActivityExplorer.tsxnew file mode 100644index 00000000..4db349af--- /dev/null+++ b/dashboard/src/activities/ActivityExplorer.tsx@@ -0,0 +1,233 @@+import { useDeferredValue, useEffect, useMemo, useState } from "react";+import { useAppStore } from "../stores/useAppStore";+import * as api from "../services/api";+import type { InstanceTab } from "../types";+import { fetchActivity } from "./api";+import ActivityFilterMenu from "./ActivityFilterMenu";+import ActivityTimeline from "./ActivityTimeline";+import {+ applyLockedFilters,+ buildActivityQuery,+ defaultActivityFilters,+ sameActivityFilters,+} from "./helpers";+import type { ActivityFilters, DashboardActivityEvent } from "./types";++interface Props {+ initialFilters?: Partial<ActivityFilters>;+ lockedFilters?: Partial<ActivityFilters>;+ showFilterMenu?: boolean;+ title?: string;+ summaryLabel?: string;+ embedded?: boolean;+}++export default function ActivityExplorer({+ initialFilters,+ lockedFilters,+ showFilterMenu = true,+ title = "Request timeline",+ summaryLabel = "Activity",+ embedded = false,+}: Props) {+ const { instances, profiles } = useAppStore();+ const [filters, setFilters] = useState<ActivityFilters>({+ ...defaultActivityFilters,+ ...initialFilters,+ ...lockedFilters,+ });+ const [events, setEvents] = useState<DashboardActivityEvent[]>([]);+ const [tabs, setTabs] = useState<InstanceTab[]>([]);+ const [count, setCount] = useState(0);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState("");++ const deferredFilters = useDeferredValue(filters);+ const effectiveFilters = useMemo(+ () => applyLockedFilters(deferredFilters, lockedFilters),+ [deferredFilters, lockedFilters],+ );+ const query = useMemo(+ () => buildActivityQuery(effectiveFilters),+ [effectiveFilters],+ );++ useEffect(() => {+ setFilters((current) => {+ const next = {+ ...current,+ ...initialFilters,+ ...lockedFilters,+ };+ return sameActivityFilters(current, next) ? current : next;+ });+ }, [initialFilters, lockedFilters]);++ useEffect(() => {+ let cancelled = false;+ void api+ .fetchAllTabs()+ .then((response) => {+ if (!cancelled) {+ setTabs(response);+ }+ })+ .catch(() => {+ if (!cancelled) {+ setTabs([]);+ }+ });+ return () => {+ cancelled = true;+ };+ }, []);++ useEffect(() => {+ let cancelled = false;+ const load = async () => {+ setLoading(true);+ setError("");+ try {+ const response = await fetchActivity(query);+ if (cancelled) return;+ setEvents(response.events);+ setCount(response.count);+ } catch (err) {+ if (cancelled) return;+ setError(+ err instanceof Error ? err.message : "Failed to load activity",+ );+ } finally {+ if (!cancelled) {+ setLoading(false);+ }+ }+ };+ void load();+ return () => {+ cancelled = true;+ };+ }, [query]);++ const stats = useMemo(() => {+ const agents = new Set(+ events.map((event) => event.agentId).filter(Boolean),+ );+ const tabsSeen = new Set(+ events.map((event) => event.tabId).filter(Boolean),+ );+ const instancesSeen = new Set(+ events.map((event) => event.instanceId).filter(Boolean),+ );+ return {+ agents: agents.size,+ tabs: tabsSeen.size,+ instances: instancesSeen.size,+ };+ }, [events]);++ const filteredInstances = useMemo(+ () =>+ effectiveFilters.profileName === ""+ ? instances+ : instances.filter(+ (instance) => instance.profileName === effectiveFilters.profileName,+ ),+ [effectiveFilters.profileName, instances],+ );++ const visibleTabs = useMemo(+ () =>+ effectiveFilters.instanceId === ""+ ? tabs+ : tabs.filter((tab) => tab.instanceId === effectiveFilters.instanceId),+ [effectiveFilters.instanceId, tabs],+ );++ const summary = useMemo(+ () =>+ `${count} events • ${stats.agents} agents • ${stats.tabs} tabs • ${stats.instances} instances`,+ [count, stats.agents, stats.instances, stats.tabs],+ );++ const updateFilter = (key: keyof ActivityFilters, value: string) => {+ if (lockedFilters?.[key] !== undefined) {+ return;+ }+ setFilters((current) => ({ ...current, [key]: value }));+ };++ const handleProfileChange = (value: string) => {+ if (lockedFilters?.profileName !== undefined) {+ return;+ }+ setFilters((current) => ({+ ...current,+ profileName: value,+ instanceId:+ value === "" ||+ filteredInstances.some((instance) => instance.id === current.instanceId)+ ? current.instanceId+ : "",+ tabId: value === "" ? current.tabId : "",+ }));+ };++ const handleInstanceChange = (value: string) => {+ if (lockedFilters?.instanceId !== undefined) {+ return;+ }+ setFilters((current) => ({+ ...current,+ instanceId: value,+ tabId:+ value === "" || visibleTabs.some((tab) => tab.id === current.tabId)+ ? current.tabId+ : "",+ }));+ };++ const clearFilters = () =>+ setFilters({+ ...defaultActivityFilters,+ ...lockedFilters,+ });++ const layoutClass = embedded+ ? "flex h-full min-h-0 flex-col overflow-hidden"+ : "flex h-full min-h-0 flex-col gap-4 overflow-hidden p-4 xl:flex-row";++ return (+ <div className={layoutClass}>+ {showFilterMenu && (+ <aside className="dashboard-panel flex w-full shrink-0 flex-col overflow-hidden xl:w-80">+ <div className="border-b border-border-subtle px-4 py-4">+ <div className="dashboard-section-label mb-1">{summaryLabel}</div>+ <h1 className="text-lg font-semibold text-text-primary">{title}</h1>+ <p className="mt-2 text-xs leading-5 text-text-muted">{summary}</p>+ </div>+ <ActivityFilterMenu+ filters={effectiveFilters}+ profileOptions={profiles}+ instanceOptions={filteredInstances}+ tabOptions={visibleTabs}+ loading={loading}+ onClear={clearFilters}+ onRefresh={() => setFilters((current) => ({ ...current }))}+ onFilterChange={updateFilter}+ onProfileChange={handleProfileChange}+ onInstanceChange={handleInstanceChange}+ />+ </aside>+ )}++ <ActivityTimeline+ events={events}+ loading={loading}+ error={error}+ summary={summary}+ onFilterChange={updateFilter}+ />+ </div>+ );+}diff --git a/dashboard/src/activities/ActivityFilterMenu.tsx b/dashboard/src/activities/ActivityFilterMenu.tsxnew file mode 100644index 00000000..3c3a7011--- /dev/null+++ b/dashboard/src/activities/ActivityFilterMenu.tsx@@ -0,0 +1,216 @@+import { useState, type ChangeEvent } from "react";+import { Button, Input } from "../components/atoms";+import type { Profile, Instance, InstanceTab } from "../types";+import type { ActivityFilters } from "./types";+import { actionOptions, sourceOptions } from "./helpers";++interface Props {+ filters: ActivityFilters;+ profileOptions: Profile[];+ instanceOptions: Instance[];+ tabOptions: InstanceTab[];+ loading: boolean;+ onClear: () => void;+ onRefresh: () => void;+ onFilterChange: (key: keyof ActivityFilters, value: string) => void;+ onProfileChange: (value: string) => void;+ onInstanceChange: (value: string) => void;+}++function FilterSelect({+ label,+ value,+ options,+ onChange,+}: {+ label: string;+ value: string;+ options: Array<{ value: string; label: string }>;+ onChange: (event: ChangeEvent<HTMLSelectElement>) => void;+}) {+ return (+ <label className="flex flex-col gap-1.5">+ <span className="dashboard-section-title text-[0.68rem]">{label}</span>+ <select+ aria-label={label}+ value={value}+ onChange={onChange}+ className="rounded-sm border border-border-subtle bg-[rgb(var(--brand-surface-code-rgb)/0.72)] px-3 py-2 text-sm text-text-primary transition-all duration-150 focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20"+ >+ {options.map((option) => (+ <option key={option.value || "all"} value={option.value}>+ {option.label}+ </option>+ ))}+ </select>+ </label>+ );+}++export default function ActivityFilterMenu({+ filters,+ profileOptions,+ instanceOptions,+ tabOptions,+ loading,+ onClear,+ onRefresh,+ onFilterChange,+ onProfileChange,+ onInstanceChange,+}: Props) {+ const [showAdvanced, setShowAdvanced] = useState(false);++ return (+ <>+ <div className="flex-1 space-y-4 overflow-auto p-4">+ <div className="space-y-3">+ <FilterSelect+ label="Profile"+ value={filters.profileName}+ options={[+ { value: "", label: "Any profile" },+ ...profileOptions.map((profile) => ({+ value: profile.name,+ label: profile.name,+ })),+ ]}+ onChange={(event) => onProfileChange(event.target.value)}+ />+ <FilterSelect+ label="Tab"+ value={filters.tabId}+ options={[+ { value: "", label: "Any tab" },+ ...tabOptions.map((tab) => ({+ value: tab.id,+ label: `${tab.title || tab.url || tab.id} · ${tab.id}`,+ })),+ ]}+ onChange={(event) => onFilterChange("tabId", event.target.value)}+ />+ </div>++ <div className="space-y-3 border-t border-border-subtle pt-4">+ <Input+ label="Agent"+ placeholder="cli, mcp, custom"+ value={filters.agentId}+ onChange={(event) => onFilterChange("agentId", event.target.value)}+ />+ <FilterSelect+ label="Action"+ value={filters.action}+ options={[+ { value: "", label: "Any action" },+ ...actionOptions+ .filter(Boolean)+ .map((option) => ({ value: option, label: option })),+ ]}+ onChange={(event) => onFilterChange("action", event.target.value)}+ />+ </div>++ <div className="border-t border-border-subtle pt-4">+ <button+ type="button"+ className="flex w-full items-center justify-between text-left"+ onClick={() => setShowAdvanced((current) => !current)}+ aria-expanded={showAdvanced}+ aria-controls="activity-advanced-filters"+ >+ <span className="dashboard-section-title text-[0.68rem]">+ Advanced filters+ </span>+ <span className="text-[0.68rem] uppercase tracking-[0.16em] text-text-muted">+ {showAdvanced ? "Hide" : "Show"}+ </span>+ </button>++ {showAdvanced && (+ <div id="activity-advanced-filters" className="mt-3 space-y-3">+ <FilterSelect+ label="Instance"+ value={filters.instanceId}+ options={[+ { value: "", label: "Any instance" },+ ...instanceOptions.map((instance) => ({+ value: instance.id,+ label: `${instance.profileName} · ${instance.id}`,+ })),+ ]}+ onChange={(event) => onInstanceChange(event.target.value)}+ />+ <Input+ label="Session"+ placeholder="session_xxx"+ value={filters.sessionId}+ onChange={(event) =>+ onFilterChange("sessionId", event.target.value)+ }+ />+ <FilterSelect+ label="Source"+ value={filters.source}+ options={[+ { value: "", label: "Any source" },+ ...sourceOptions+ .filter(Boolean)+ .map((option) => ({ value: option, label: option })),+ ]}+ onChange={(event) =>+ onFilterChange("source", event.target.value)+ }+ />+ <Input+ label="Path prefix"+ placeholder="/tabs/ or /instances/"+ value={filters.pathPrefix}+ onChange={(event) =>+ onFilterChange("pathPrefix", event.target.value)+ }+ />+ <Input+ label="Age (seconds)"+ placeholder="3600"+ value={filters.ageSec}+ onChange={(event) =>+ onFilterChange("ageSec", event.target.value)+ }+ />+ <Input+ label="Limit"+ placeholder="200"+ value={filters.limit}+ onChange={(event) =>+ onFilterChange("limit", event.target.value)+ }+ />+ </div>+ )}+ </div>+ </div>++ <div className="flex gap-2 border-t border-border-subtle p-4">+ <Button+ variant="secondary"+ size="sm"+ onClick={onClear}+ disabled={loading}+ className="flex-1"+ >+ Clear+ </Button>+ <Button+ variant="primary"+ size="sm"+ onClick={onRefresh}+ loading={loading}+ className="flex-1"+ >+ Refresh+ </Button>+ </div>+ </>+ );+}diff --git a/dashboard/src/components/molecules/ActivityLine.tsx b/dashboard/src/activities/ActivityLine.tsxsimilarity index 87%rename from dashboard/src/components/molecules/ActivityLine.tsxrename to dashboard/src/activities/ActivityLine.tsxindex 1b876b80..05925fd0 100644--- a/dashboard/src/components/molecules/ActivityLine.tsx+++ b/dashboard/src/activities/ActivityLine.tsx@@ -1,5 +1,5 @@-import { Badge } from "../atoms";-import type { ActivityEvent } from "../../types";+import { Badge } from "../components/atoms";+import type { ActivityEvent } from "../types";interface Props {event: ActivityEvent;@@ -31,9 +31,9 @@ function formatTime(ts: string): string {export default function ActivityLine({ event }: Props) {return (- <div className="flex items-center gap-3 border-b border-border-subtle/70 px-4 py-3 text-sm transition-colors hover:bg-white/[0.02]">+ <div className="flex items-center gap-3 border-b border-border-subtle/70 px-4 py-3 text-sm transition-colors hover:bg-white/2"><span className="text-lg">{typeIcons[event.type] || "📝"}</span>- <span className="dashboard-mono w-[4.5rem] shrink-0 text-xs text-text-muted">+ <span className="dashboard-mono w-18 shrink-0 text-xs text-text-muted">{formatTime(event.timestamp)}</span><Badge variant={typeColors[event.type] || "default"}>diff --git a/dashboard/src/activities/ActivityPage.test.tsx b/dashboard/src/activities/ActivityPage.test.tsxnew file mode 100644index 00000000..58fecd8b--- /dev/null+++ b/dashboard/src/activities/ActivityPage.test.tsx@@ -0,0 +1,207 @@+import { render, screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { MemoryRouter } from "react-router-dom";+import ActivityPage from "./ActivityPage";+import { useAppStore } from "../stores/useAppStore";++vi.mock("./api", () => ({+ fetchActivity: vi.fn(),+}));++vi.mock("../services/api", () => ({+ fetchAllTabs: vi.fn(),+}));++import { fetchActivity } from "./api";+import { fetchAllTabs } from "../services/api";++describe("ActivityPage", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ useAppStore.setState({+ profiles: [+ {+ id: "prof_default",+ name: "default",+ created: "2026-03-16T08:00:00Z",+ lastUsed: "2026-03-16T08:10:00Z",+ diskUsage: 1024,+ running: false,+ },+ ],+ instances: [+ {+ id: "inst_123",+ profileId: "prof_default",+ profileName: "default",+ port: "9988",+ headless: true,+ status: "running",+ startTime: "2026-03-16T08:00:00Z",+ attached: false,+ },+ ],+ currentTabs: {+ inst_123: [+ {+ id: "tab_123",+ instanceId: "inst_123",+ url: "https://example.com",+ title: "Example",+ },+ ],+ },+ });+ vi.mocked(fetchAllTabs).mockResolvedValue([+ {+ id: "tab_123",+ instanceId: "inst_123",+ url: "https://example.com",+ title: "Example",+ },+ ]);+ vi.mocked(fetchActivity).mockResolvedValue({+ count: 1,+ events: [+ {+ timestamp: "2026-03-16T09:00:00Z",+ source: "cli",+ requestId: "req_123",+ agentId: "cli",+ method: "POST",+ path: "/tabs/tab_123/action",+ status: 200,+ durationMs: 87,+ tabId: "tab_123",+ action: "click",+ },+ ],+ });+ });++ it("loads and renders activity records", async () => {+ render(+ <MemoryRouter>+ <ActivityPage />+ </MemoryRouter>,+ );++ await waitFor(() => {+ expect(fetchActivity).toHaveBeenCalled();+ });++ expect(screen.getByText("Request timeline")).toBeInTheDocument();+ expect(screen.getByText("/tabs/tab_123/action")).toBeInTheDocument();+ expect(screen.getByText("agent:cli")).toBeInTheDocument();+ expect(screen.getByText("tab:tab_123")).toBeInTheDocument();+ });++ it("defaults to the current running profile and tab", async () => {+ render(+ <MemoryRouter>+ <ActivityPage />+ </MemoryRouter>,+ );++ await waitFor(() => {+ expect(fetchActivity).toHaveBeenCalledWith(+ expect.objectContaining({+ profileName: "default",+ instanceId: "inst_123",+ tabId: "tab_123",+ }),+ );+ });+ });++ it("clears back to default filters instead of reapplying landing context", async () => {+ render(+ <MemoryRouter>+ <ActivityPage />+ </MemoryRouter>,+ );++ await waitFor(() => {+ expect(fetchActivity).toHaveBeenCalledWith(+ expect.objectContaining({+ profileName: "default",+ instanceId: "inst_123",+ tabId: "tab_123",+ }),+ );+ });++ await userEvent.click(screen.getByRole("button", { name: "Clear" }));++ await waitFor(() => {+ expect(fetchActivity).toHaveBeenLastCalledWith(+ expect.objectContaining({+ ageSec: 3600,+ limit: 200,+ }),+ );+ });++ expect(vi.mocked(fetchActivity).mock.lastCall?.[0]).not.toEqual(+ expect.objectContaining({+ profileName: "default",+ instanceId: "inst_123",+ tabId: "tab_123",+ }),+ );+ });++ it("applies the tab filter from the dropdown filter panel", async () => {+ render(+ <MemoryRouter>+ <ActivityPage />+ </MemoryRouter>,+ );++ await waitFor(() => {+ expect(fetchActivity).toHaveBeenCalledTimes(1);+ });++ await userEvent.click(+ screen.getByRole("button", { name: /advanced filters/i }),+ );+ await userEvent.selectOptions(+ screen.getByLabelText("Instance"),+ "inst_123",+ );+ await userEvent.selectOptions(screen.getByLabelText("Tab"), "tab_123");++ await waitFor(() => {+ expect(fetchActivity).toHaveBeenLastCalledWith(+ expect.objectContaining({ instanceId: "inst_123", tabId: "tab_123" }),+ );+ });+ });++ it("keeps the primary filters visible and reveals the rest under advanced", async () => {+ render(+ <MemoryRouter>+ <ActivityPage />+ </MemoryRouter>,+ );++ await waitFor(() => {+ expect(fetchActivity).toHaveBeenCalled();+ });++ expect(screen.getByLabelText("Profile")).toBeInTheDocument();+ expect(screen.getByLabelText("Tab")).toBeInTheDocument();+ expect(screen.getByLabelText("Agent")).toBeInTheDocument();+ expect(screen.getByLabelText("Action")).toBeInTheDocument();+ expect(screen.queryByLabelText("Instance")).not.toBeInTheDocument();++ await userEvent.click(+ screen.getByRole("button", { name: /advanced filters/i }),+ );++ expect(screen.getByLabelText("Instance")).toBeInTheDocument();+ expect(screen.getByLabelText("Session")).toBeInTheDocument();+ expect(screen.getByLabelText("Source")).toBeInTheDocument();+ });+});diff --git a/dashboard/src/activities/ActivityPage.tsx b/dashboard/src/activities/ActivityPage.tsxnew file mode 100644index 00000000..8cef888c--- /dev/null+++ b/dashboard/src/activities/ActivityPage.tsx@@ -0,0 +1,132 @@+import { useEffect, useMemo, useRef, useState } from "react";+import { useLocation } from "react-router-dom";+import { useAppStore } from "../stores/useAppStore";+import type { ActivityFilters } from "./types";+import ActivityExplorer from "./ActivityExplorer";++interface ActivityPageLocationState {+ profileName?: string;+ instanceId?: string;+ tabId?: string;+}++function hasInitialSelection(filters: Partial<ActivityFilters>): boolean {+ return Boolean(filters.profileName || filters.instanceId || filters.tabId);+}++export default function ActivityPage() {+ const location = useLocation();+ const { profiles, instances, currentTabs } = useAppStore();+ const routeState = location.state as ActivityPageLocationState | null;+ const locationKeyRef = useRef(location.key);++ const routeInitialFilters = useMemo<Partial<ActivityFilters>>(+ () => ({+ profileName: routeState?.profileName ?? "",+ instanceId: routeState?.instanceId ?? "",+ tabId: routeState?.tabId ?? "",+ }),+ [routeState],+ );++ const derivedInitialFilters = useMemo<Partial<ActivityFilters>>(() => {+ let profileName = routeInitialFilters.profileName ?? "";+ let instanceId = routeInitialFilters.instanceId ?? "";+ let tabId = routeInitialFilters.tabId ?? "";++ const runningInstances = instances.filter(+ (instance) => instance.status === "running",+ );++ let selectedInstance =+ (instanceId+ ? instances.find((instance) => instance.id === instanceId)+ : undefined) ?? null;++ if (!selectedInstance) {+ const candidateInstances = profileName+ ? runningInstances.filter(+ (instance) => instance.profileName === profileName,+ )+ : runningInstances;+ if (candidateInstances.length === 1) {+ selectedInstance = candidateInstances[0];+ }+ }++ if (!profileName) {+ if (selectedInstance) {+ profileName = selectedInstance.profileName;+ } else if (profiles.length === 1) {+ profileName = profiles[0].name;+ }+ }++ if (!selectedInstance && profileName) {+ const matchingInstances = runningInstances.filter(+ (instance) => instance.profileName === profileName,+ );+ if (matchingInstances.length === 1) {+ selectedInstance = matchingInstances[0];+ }+ }++ if (selectedInstance && !instanceId) {+ instanceId = selectedInstance.id;+ }++ if (!tabId && selectedInstance) {+ const activeTabs = currentTabs[selectedInstance.id] ?? [];+ if (activeTabs.length > 0) {+ tabId = activeTabs[0].id;+ }+ }++ return {+ profileName,+ instanceId,+ tabId,+ };+ }, [currentTabs, instances, profiles, routeInitialFilters]);++ const [initialFilters, setInitialFilters] = useState<+ Partial<ActivityFilters>+ >(() =>+ hasInitialSelection(routeInitialFilters)+ ? routeInitialFilters+ : derivedInitialFilters,+ );+ const [didAutoSelect, setDidAutoSelect] = useState<boolean>(+ () =>+ hasInitialSelection(routeInitialFilters) ||+ hasInitialSelection(derivedInitialFilters),+ );++ useEffect(() => {+ if (locationKeyRef.current === location.key) {+ return;+ }+ locationKeyRef.current = location.key;+ const nextInitialFilters = hasInitialSelection(routeInitialFilters)+ ? routeInitialFilters+ : derivedInitialFilters;+ setInitialFilters(nextInitialFilters);+ setDidAutoSelect(hasInitialSelection(nextInitialFilters));+ }, [derivedInitialFilters, location.key, routeInitialFilters]);++ useEffect(() => {+ if (didAutoSelect || !hasInitialSelection(derivedInitialFilters)) {+ return;+ }+ setInitialFilters(derivedInitialFilters);+ setDidAutoSelect(true);+ }, [derivedInitialFilters, didAutoSelect]);++ return (+ <ActivityExplorer+ title="Request timeline"+ summaryLabel="Activity"+ initialFilters={initialFilters}+ />+ );+}diff --git a/dashboard/src/activities/ActivityTimeline.tsx b/dashboard/src/activities/ActivityTimeline.tsxnew file mode 100644index 00000000..59be7b26--- /dev/null+++ b/dashboard/src/activities/ActivityTimeline.tsx@@ -0,0 +1,164 @@+import { Badge, EmptyState } from "../components/atoms";+import type { DashboardActivityEvent, ActivityFilters } from "./types";+import {+ activityMethodVariant,+ activityStatusVariant,+ formatActivityTimestamp,+} from "./helpers";++interface Props {+ events: DashboardActivityEvent[];+ loading: boolean;+ error: string;+ summary: string;+ onFilterChange: (key: keyof ActivityFilters, value: string) => void;+}++function FilterChip({+ label,+ onClick,+ className = "",+}: {+ label: string;+ onClick: () => void;+ className?: string;+}) {+ return (+ <button+ type="button"+ className={`rounded-sm border border-border-subtle bg-white/3 px-1.5 py-0.5 text-[0.62rem] font-semibold tracking-[0.08em] text-text-secondary transition-all hover:border-primary/30 hover:bg-primary/10 hover:text-primary ${className}`}+ onClick={onClick}+ title={label}+ >+ <span className="block truncate">{label}</span>+ </button>+ );+}++export default function ActivityTimeline({+ events,+ loading,+ error,+ summary,+ onFilterChange,+}: Props) {+ return (+ <section className="dashboard-panel flex min-h-0 flex-1 flex-col overflow-hidden">+ <div className="flex items-center justify-between border-b border-border-subtle px-4 py-3">+ <div>+ <div className="dashboard-section-label mb-1">Timeline</div>+ <h2 className="text-sm font-semibold text-text-secondary">+ Recent events+ </h2>+ </div>+ <div className="dashboard-mono text-[0.72rem] text-text-muted">+ {summary}+ </div>+ </div>++ {error && (+ <div className="border-b border-destructive/30 bg-destructive/10 px-4 py-2 text-xs text-destructive">+ {error}+ </div>+ )}++ <div className="min-h-0 flex-1 overflow-auto">+ {!loading && events.length === 0 ? (+ <EmptyState+ icon="📜"+ title="No matching activity"+ description="Adjust the filters or generate some traffic from the CLI, MCP, or dashboard."+ />+ ) : (+ <div className="divide-y divide-border-subtle/70">+ {events.map((event, index) => (+ <div+ key={`${event.requestId || event.timestamp}-${index}`}+ className="px-4 py-2 transition-colors hover:bg-white/2"+ >+ <div className="flex flex-wrap items-center gap-1.5">+ <span className="dashboard-mono text-[0.68rem] text-text-muted">+ {formatActivityTimestamp(event.timestamp)}+ </span>+ <Badge variant={activityMethodVariant(event.method)}>+ {event.method}+ </Badge>+ <Badge variant={activityStatusVariant(event.status)}>+ {event.status}+ </Badge>+ {event.source && <Badge>{event.source}</Badge>}+ {event.action && (+ <Badge variant="warning">{event.action}</Badge>+ )}+ {event.engine && <Badge variant="info">{event.engine}</Badge>}+ <span className="ml-auto dashboard-mono text-[0.68rem] text-text-muted">+ {event.durationMs} ms+ </span>+ </div>++ <div className="mt-1 grid grid-cols-1 gap-1.5 xl:grid-cols-[minmax(0,1fr)_20rem] xl:items-start">+ <div className="min-w-0">+ <div className="dashboard-mono break-all text-[0.82rem] text-text-primary">+ {event.path}+ </div>+ {event.tabId && (+ <div className="mt-1">+ <FilterChip+ label={`tab:${event.tabId}`}+ className="max-w-full xl:max-w-[18rem]"+ onClick={() =>+ onFilterChange("tabId", event.tabId || "")+ }+ />+ </div>+ )}+ {event.url && (+ <div className="dashboard-mono mt-0.5 break-all text-[0.68rem] text-text-muted">+ {event.url}+ </div>+ )}+ </div>+ <div className="dashboard-mono flex flex-wrap gap-1 text-[0.68rem] text-text-muted xl:justify-end">+ {event.agentId && (+ <FilterChip+ label={`agent:${event.agentId}`}+ onClick={() =>+ onFilterChange("agentId", event.agentId || "")+ }+ />+ )}+ {event.profileName && (+ <FilterChip+ label={`profile:${event.profileName}`}+ onClick={() =>+ onFilterChange("profileName", event.profileName || "")+ }+ />+ )}+ </div>+ </div>++ <div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-[0.68rem] text-text-muted">+ {event.requestId && (+ <span className="dashboard-mono">{event.requestId}</span>+ )}+ {event.ref && (+ <span className="dashboard-mono">ref:{event.ref}</span>+ )}+ {event.actorId && (+ <span className="dashboard-mono">+ actor:{event.actorId}+ </span>+ )}+ {event.remoteAddr && (+ <span className="dashboard-mono">{event.remoteAddr}</span>+ )}+ </div>+ </div>+ ))}+ </div>+ )}+ </div>+ </section>+ );+}diff --git a/dashboard/src/pages/AgentsPage.tsx b/dashboard/src/activities/AgentsPage.tsxsimilarity index 96%rename from dashboard/src/pages/AgentsPage.tsxrename to dashboard/src/activities/AgentsPage.tsxindex 6bc68130..6513535e 100644--- a/dashboard/src/pages/AgentsPage.tsx+++ b/dashboard/src/activities/AgentsPage.tsx@@ -1,6 +1,7 @@-import { useAppStore } from "../stores/useAppStore";import { EmptyState } from "../components/atoms";-import { AgentItem, ActivityLine } from "../components/molecules";+import { AgentItem } from "../components/molecules";+import { useAppStore } from "../stores/useAppStore";+import ActivityLine from "./ActivityLine";const filters = [{ key: "all", label: "All" },@@ -28,7 +29,6 @@ export default function AgentsPage() {return (<div className="flex h-full flex-col sm:flex-row">- {/* Mobile: Agents carousel (horizontal scroll) */}<div className="shrink-0 border-b border-border-subtle bg-bg-surface sm:hidden"><div className="flex items-center gap-2 overflow-x-auto px-4 py-3"><button@@ -57,7 +57,6 @@ export default function AgentsPage() {</div></div>- {/* Desktop: Agents sidebar */}<div className="hidden w-72 shrink-0 border-r border-border-subtle bg-bg-surface sm:block"><div className="border-b border-border-subtle px-4 py-3"><div className="dashboard-section-label mb-1">Agents</div>@@ -94,7 +93,6 @@ export default function AgentsPage() {</div></div>- {/* Activity feed */}<div className="flex flex-1 flex-col overflow-hidden"><div className="flex items-center justify-between border-b border-border-subtle bg-bg-surface px-4 py-3"><div>diff --git a/dashboard/src/activities/api.ts b/dashboard/src/activities/api.tsnew file mode 100644index 00000000..14a56beb--- /dev/null+++ b/dashboard/src/activities/api.ts@@ -0,0 +1,3 @@+import { fetchActivity as fetchActivityRequest } from "../services/api";++export const fetchActivity = fetchActivityRequest;diff --git a/dashboard/src/activities/helpers.ts b/dashboard/src/activities/helpers.tsnew file mode 100644index 00000000..e7a45013--- /dev/null+++ b/dashboard/src/activities/helpers.ts@@ -0,0 +1,121 @@+import type { ActivityFilters, ActivityQuery } from "./types";++export const defaultActivityFilters: ActivityFilters = {+ agentId: "",+ tabId: "",+ instanceId: "",+ profileName: "",+ sessionId: "",+ action: "",+ source: "",+ pathPrefix: "",+ ageSec: "3600",+ limit: "200",+};++export const actionOptions = [+ "",+ "navigate",+ "click",+ "dblclick",+ "type",+ "hover",+];+export const sourceOptions = [+ "",+ "server",+ "bridge",+ "scheduler",+ "mcp",+ "cli",+];++export function buildActivityQuery(filters: ActivityFilters): ActivityQuery {+ const query: ActivityQuery = {};+ if (filters.agentId.trim()) query.agentId = filters.agentId.trim();+ if (filters.tabId.trim()) query.tabId = filters.tabId.trim();+ if (filters.instanceId.trim()) query.instanceId = filters.instanceId.trim();+ if (filters.profileName.trim()) {+ query.profileName = filters.profileName.trim();+ }+ if (filters.sessionId.trim()) query.sessionId = filters.sessionId.trim();+ if (filters.action.trim()) query.action = filters.action.trim();+ if (filters.source.trim()) query.source = filters.source.trim();+ if (filters.pathPrefix.trim()) query.pathPrefix = filters.pathPrefix.trim();+ if (filters.ageSec.trim()) {+ const ageSec = Number(filters.ageSec);+ if (Number.isFinite(ageSec) && ageSec >= 0) {+ query.ageSec = ageSec;+ }+ }+ if (filters.limit.trim()) {+ const limit = Number(filters.limit);+ if (Number.isFinite(limit) && limit > 0) {+ query.limit = limit;+ }+ }+ return query;+}++export function applyLockedFilters(+ filters: ActivityFilters,+ lockedFilters?: Partial<ActivityFilters>,+): ActivityFilters {+ if (!lockedFilters) {+ return filters;+ }+ return { ...filters, ...lockedFilters };+}++export function sameActivityFilters(+ left: ActivityFilters,+ right: ActivityFilters,+): boolean {+ return (+ left.agentId === right.agentId &&+ left.tabId === right.tabId &&+ left.instanceId === right.instanceId &&+ left.profileName === right.profileName &&+ left.sessionId === right.sessionId &&+ left.action === right.action &&+ left.source === right.source &&+ left.pathPrefix === right.pathPrefix &&+ left.ageSec === right.ageSec &&+ left.limit === right.limit+ );+}++export function formatActivityTimestamp(timestamp: string): string {+ return new Date(timestamp).toLocaleString("en-GB", {+ year: "numeric",+ month: "short",+ day: "2-digit",+ hour: "2-digit",+ minute: "2-digit",+ second: "2-digit",+ });+}++export function activityMethodVariant(+ method: string,+): "default" | "info" | "success" | "warning" {+ switch (method.toUpperCase()) {+ case "GET":+ return "info";+ case "POST":+ return "success";+ case "DELETE":+ return "warning";+ default:+ return "default";+ }+}++export function activityStatusVariant(+ status: number,+): "default" | "success" | "warning" | "danger" {+ if (status >= 500) return "danger";+ if (status >= 400) return "warning";+ if (status >= 200) return "success";+ return "default";+}diff --git a/dashboard/src/activities/index.ts b/dashboard/src/activities/index.tsnew file mode 100644index 00000000..ad03894e--- /dev/null+++ b/dashboard/src/activities/index.ts@@ -0,0 +1,5 @@+export { default as ActivityExplorer } from "./ActivityExplorer";+export { default as ActivityPage } from "./ActivityPage";+export { default as AgentsPage } from "./AgentsPage";+export { default as ActivityLine } from "./ActivityLine";+export type { ActivityQuery, DashboardActivityEvent } from "./types";diff --git a/dashboard/src/activities/types.ts b/dashboard/src/activities/types.tsnew file mode 100644index 00000000..66f8ba1e--- /dev/null+++ b/dashboard/src/activities/types.ts@@ -0,0 +1,36 @@+import type { ActivityLogEvent, ActivityLogResponse } from "../generated/types";++export type DashboardActivityEvent = ActivityLogEvent;+export type DashboardActivityResponse = ActivityLogResponse;++export interface ActivityFilters {+ agentId: string;+ tabId: string;+ instanceId: string;+ profileName: string;+ sessionId: string;+ action: string;+ source: string;+ pathPrefix: string;+ ageSec: string;+ limit: string;+}++export interface ActivityQuery {+ source?: string;+ requestId?: string;+ sessionId?: string;+ actorId?: string;+ agentId?: string;+ instanceId?: string;+ profileId?: string;+ profileName?: string;+ tabId?: string;+ action?: string;+ engine?: string;+ pathPrefix?: string;+ since?: string;+ until?: string;+ ageSec?: number;+ limit?: number;+}diff --git a/dashboard/src/components/atoms/Input.tsx b/dashboard/src/components/atoms/Input.tsxindex 86cb7037..4f722bc0 100644--- a/dashboard/src/components/atoms/Input.tsx+++ b/dashboard/src/components/atoms/Input.tsx@@ -1,5 +1,5 @@import type { InputHTMLAttributes } from "react";-import { forwardRef } from "react";+import { forwardRef, useId } from "react";interface Props extends InputHTMLAttributes<HTMLInputElement> {label?: string;@@ -8,14 +8,21 @@ interface Props extends InputHTMLAttributes<HTMLInputElement> {const Input = forwardRef<HTMLInputElement, Props>(({ label, hint, className = "", ...props }, ref) => {+ const generatedId = useId();+ const inputId = props.id || generatedId;+return (<div className="flex flex-col gap-1.5">{label && (- <label className="dashboard-section-title text-[0.68rem]">+ <label+ htmlFor={inputId}+ className="dashboard-section-title text-[0.68rem]"+ >{label}</label>)}<input+ id={inputId}ref={ref}className={`rounded-sm border border-border-subtle bg-[rgb(var(--brand-surface-code-rgb)/0.72)] px-3 py-2 text-sm text-text-primary placeholder:text-text-muted transition-all duration-150 focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20 ${className}`}{...props}diff --git a/dashboard/src/components/instances/InstanceListItem.test.tsx b/dashboard/src/components/instances/InstanceListItem.test.tsxindex 852b31e9..60fb218a 100644--- a/dashboard/src/components/instances/InstanceListItem.test.tsx+++ b/dashboard/src/components/instances/InstanceListItem.test.tsx@@ -31,7 +31,7 @@ describe("InstanceListItem", () => {});it("shows running status badge", () => {- render(+ const { container } = render(<InstanceListIteminstance={mockInstance}tabCount={0}@@ -40,12 +40,12 @@ describe("InstanceListItem", () => {/>,);- expect(screen.getByText("running")).toBeInTheDocument();+ expect(container.querySelector(".bg-success")).toBeInTheDocument();});it("shows error status for errored instances", () => {const errorInstance = { ...mockInstance, status: "error" };- render(+ const { container } = render(<InstanceListIteminstance={errorInstance}tabCount={0}@@ -54,7 +54,7 @@ describe("InstanceListItem", () => {/>,);- expect(screen.getByText("error")).toBeInTheDocument();+ expect(container.querySelector(".bg-destructive")).toBeInTheDocument();});it("applies selected styles when selected", () => {diff --git a/dashboard/src/components/instances/InstanceListItem.tsx b/dashboard/src/components/instances/InstanceListItem.tsxindex d4d42f70..330c0bbd 100644--- a/dashboard/src/components/instances/InstanceListItem.tsx+++ b/dashboard/src/components/instances/InstanceListItem.tsx@@ -1,4 +1,3 @@-import { Badge } from "../atoms";import type { Instance } from "../../generated/types";interface Props {@@ -23,13 +22,6 @@ export default function InstanceListItem({? "bg-destructive": "bg-text-muted";- const badgeVariant =- instance.status === "running"- ? "success"- : instance.status === "error"- ? "danger"- : "default";-return (<buttononClick={onClick}@@ -49,7 +41,6 @@ export default function InstanceListItem({{memoryMB !== undefined && ` · ${memoryMB.toFixed(0)}MB`}</div></div>- <Badge variant={badgeVariant}>{instance.status}</Badge></button>);}diff --git a/dashboard/src/components/molecules/NavBar.tsx b/dashboard/src/components/molecules/NavBar.tsxindex a7bb8968..5927d6cb 100644--- a/dashboard/src/components/molecules/NavBar.tsx+++ b/dashboard/src/components/molecules/NavBar.tsx@@ -12,6 +12,7 @@ interface Tab {const tabs: Tab[] = [{ id: "monitoring", path: "/dashboard/monitoring", label: "Monitoring" },+ { id: "activity", path: "/dashboard/activity", label: "Activity" },{ id: "profiles", path: "/dashboard/profiles", label: "Profiles" },{ id: "settings", path: "/dashboard/settings", label: "Settings" },];diff --git a/dashboard/src/components/molecules/TabsChart.tsx b/dashboard/src/components/molecules/TabsChart.tsxindex a27f2abc..acf7c996 100644--- a/dashboard/src/components/molecules/TabsChart.tsx+++ b/dashboard/src/components/molecules/TabsChart.tsx@@ -1,4 +1,4 @@-import { useMemo, useCallback } from "react";+import { useMemo } from "react";import {AreaChart,Area,@@ -8,6 +8,7 @@ import {CartesianGrid,ResponsiveContainer,} from "recharts";+import type { TooltipContentProps } from "recharts";import type {TabDataPoint,MemoryDataPoint,@@ -55,9 +56,9 @@ function GlassTooltip({label,instances,}: {- active?: boolean;- payload?: readonly { dataKey: string; value: number; color: string }[];- label?: string | number;+ active?: TooltipContentProps<number, string>["active"];+ payload?: TooltipContentProps<number, string>["payload"];+ label?: TooltipContentProps<number, string>["label"];instances: { id: string; profileName: string }[];}) {if (!active || !payload?.length) return null;@@ -267,10 +268,8 @@ export default function TabsChart({return vals;}, [mergedData, instances, instanceColors]);- // eslint-disable-next-line @typescript-eslint/no-explicit-any- const tooltipContent = useCallback(- (props: any) => <GlassTooltip {...props} instances={instances} />,- [instances],+ const tooltipContent = (props: TooltipContentProps<number, string>) => (+ <GlassTooltip {...props} instances={instances} />);if (mergedData.length < 2) {diff --git a/dashboard/src/components/molecules/index.ts b/dashboard/src/components/molecules/index.tsindex ab4e203a..08d952a3 100644--- a/dashboard/src/components/molecules/index.ts+++ b/dashboard/src/components/molecules/index.ts@@ -8,6 +8,6 @@ export { default as StartInstanceModal } from "./StartInstanceModal";export { default as ScreencastTile } from "../screencast/ScreencastTile";export { InstanceTabsPanel, TabItem } from "../tabs";export { default as AgentItem } from "./AgentItem";-export { default as ActivityLine } from "./ActivityLine";+export { default as ActivityLine } from "../../activities/ActivityLine";export { default as TabsChart } from "./TabsChart";export { default as ServerSummary } from "./ServerSummary";diff --git a/dashboard/src/components/tabs/SelectedTabPanel.tsx b/dashboard/src/components/tabs/SelectedTabPanel.tsxindex 23ee371e..a5f5476c 100644--- a/dashboard/src/components/tabs/SelectedTabPanel.tsx+++ b/dashboard/src/components/tabs/SelectedTabPanel.tsx@@ -1,4 +1,5 @@import { useState } from "react";+import { ActivityExplorer } from "../../activities";import type { InstanceTab } from "../../generated/types";import IdBadge from "./IdBadge";import { TabsLayout, EmptyView } from "../molecules";@@ -51,7 +52,21 @@ export default function SelectedTabPanel({ selectedTab, instanceId }: Props) {onChange={(id) => setActiveSubTab(id)}>{activeSubTab === "actions" && (- <EmptyView message="No actions available for this tab yet." />+ <div className="h-full p-3">+ <ActivityExplorer+ embedded+ showFilterMenu={false}+ title="Tab activity"+ summaryLabel="Actions"+ initialFilters={{+ instanceId: instanceId || "",+ tabId: selectedTab.id,+ }}+ lockedFilters={{+ tabId: selectedTab.id,+ }}+ />+ </div>)}{activeSubTab === "live" && (<div className="h-full">diff --git a/dashboard/src/generated/types.ts b/dashboard/src/generated/types.tsindex 40cd696a..2125d24b 100644--- a/dashboard/src/generated/types.ts+++ b/dashboard/src/generated/types.ts@@ -70,6 +70,37 @@ export interface ActivityEvent {timestamp: string;details?: { [key: string]: any };}+/**+ * ActivityLogEvent represents a queryable backend activity record.+ */+export interface ActivityLogEvent {+ timestamp: string;+ source: string;+ requestId?: string;+ sessionId?: string;+ actorId?: string;+ agentId?: string;+ method: string;+ path: string;+ status: number /* int */;+ durationMs: number /* int64 */;+ remoteAddr?: string;+ instanceId?: string;+ profileId?: string;+ profileName?: string;+ tabId?: string;+ url?: string;+ action?: string;+ engine?: string;+ ref?: string;+}+/**+ * ActivityLogResponse is returned by the /api/activity endpoint.+ */+export interface ActivityLogResponse {+ events: ActivityLogEvent[];+ count: number /* int */;+}/*** ScreencastSettings configures live tab previews.*/diff --git a/dashboard/src/pages/MonitoringPage.test.tsx b/dashboard/src/pages/MonitoringPage.test.tsxindex 17331852..0cc6ae24 100644--- a/dashboard/src/pages/MonitoringPage.test.tsx+++ b/dashboard/src/pages/MonitoringPage.test.tsx@@ -8,6 +8,8 @@ import type { Instance } from "../generated/types";vi.mock("../services/api", () => ({stopInstance: vi.fn(),+ fetchActivity: vi.fn(),+ fetchAllTabs: vi.fn(),}));vi.mock("../components/molecules", () => ({diff --git a/dashboard/src/pages/MonitoringPage.tsx b/dashboard/src/pages/MonitoringPage.tsxindex 349dc781..def8fc5e 100644--- a/dashboard/src/pages/MonitoringPage.tsx+++ b/dashboard/src/pages/MonitoringPage.tsx@@ -45,7 +45,6 @@ export default function MonitoringPage() {return (<ErrorBoundary><div className="flex h-full flex-col gap-4 overflow-hidden p-4">- {/* Chart - always show, even with no instances (displays server metrics) */}<ErrorBoundaryfallback={<div className="flex h-50 items-center justify-center rounded-lg border border-destructive/50 bg-bg-surface text-sm text-destructive">@@ -76,17 +75,9 @@ export default function MonitoringPage() {</div>)}- {/* Bottom section - only show when instances exist */}{instances.length > 0 && (<div className="flex flex-1 gap-4 overflow-hidden">- {/* Instance list */}<div className="dashboard-panel w-64 shrink-0 overflow-auto">- <div className="border-b border-border-subtle px-4 py-3">- <div className="dashboard-section-label mb-1">Monitoring</div>- <h3 className="text-sm font-semibold text-text-secondary">- Instances ({instances.length})- </h3>- </div><div className="p-2">{instances.map((inst) => (<InstanceListItemdiff --git a/dashboard/src/pages/ProfilesPage.test.tsx b/dashboard/src/pages/ProfilesPage.test.tsxindex 69b69f1b..64323523 100644--- a/dashboard/src/pages/ProfilesPage.test.tsx+++ b/dashboard/src/pages/ProfilesPage.test.tsx@@ -16,6 +16,8 @@ vi.mock("../services/api", () => ({stopInstance: vi.fn(),fetchInstanceTabs: vi.fn(),fetchInstanceLogs: vi.fn(),+ fetchActivity: vi.fn(),+ fetchAllTabs: vi.fn(),}));const profiles: Profile[] = [diff --git a/dashboard/src/pages/index.ts b/dashboard/src/pages/index.tsindex b0578278..33f7764e 100644--- a/dashboard/src/pages/index.ts+++ b/dashboard/src/pages/index.ts@@ -1,5 +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 LoginPage } from "./LoginPage";diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex df127dd0..eb0de6b0 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -15,6 +15,10 @@ import type {MonitoringServerMetrics,MonitoringSnapshot,} from "../types";+import type {+ ActivityQuery,+ DashboardActivityResponse,+} from "../activities/types";import {normalizeBackendConfigState,normalizeDashboardServerInfo,@@ -260,6 +264,22 @@ export async function fetchHealth(): Promise<DashboardServerInfo> {);}+export async function fetchActivity(+ query?: ActivityQuery,+): Promise<DashboardActivityResponse> {+ const params = new URLSearchParams();+ if (query) {+ for (const [key, value] of Object.entries(query)) {+ if (value === undefined || value === null || value === "") {+ continue;+ }+ params.set(key, String(value));+ }+ }+ const suffix = params.size > 0 ? `?${params.toString()}` : "";+ return request<DashboardActivityResponse>(`/api/activity${suffix}`);+}+export async function probeBackendAuth(): Promise<{requiresAuth: boolean;health?: DashboardServerInfo;diff --git a/docs/architecture/system-charts.md b/docs/architecture/system-charts.mdindex 387b4ff8..0e260b18 100644--- a/docs/architecture/system-charts.md+++ b/docs/architecture/system-charts.md@@ -37,13 +37,13 @@ This is the default system shape today:```mermaidflowchart LR- I["Install PinchTab"] --> R["Run: pinchtab"]+ I["Install PinchTab"] --> R["Run: pinchtab server"]R --> L["Local server on localhost:9867"]L --> A["Agent / CLI sends HTTP requests"]A --> W["Browser work happens through PinchTab"]```-This is the normal mental model for users. Most users should think about `pinchtab`, not `pinchtab bridge`.+This is the normal mental model for users. Most users should think about `pinchtab server`, not `pinchtab bridge`.## Chart 3: Runtime Shapesdiff --git a/docs/guides/data-storage.md b/docs/guides/data-storage.mdindex d2c3ffb2..d45a4ead 100644--- a/docs/guides/data-storage.md+++ b/docs/guides/data-storage.md@@ -10,6 +10,7 @@ PinchTab stores configuration, profiles, session state, and usage logs on local| `profiles/<profile>/` | Chrome user data for each profile | `profiles.baseDir` || `action_logs.json` | Profile activity log used by profile analytics | not currently configurable || `sessions.json` | Saved tab/session state for a bridge instance | `server.stateDir` |+| `activity/events-YYYY-MM-DD.jsonl` | Daily request/activity logs for `/api/activity`, CLI activity, and dashboard activity views | `server.stateDir`, `observability.activity.retentionDays` || `<profile>/.pinchtab-state/config.json` | Child instance config written by the orchestrator | generated automatically for managed instances |## Default Storage Location@@ -28,6 +29,8 @@ Typical layout:pinchtab/├── config.json├── action_logs.json+├── activity/+│ └── events-2026-03-16.jsonl├── sessions.json└── profiles/└── default/@@ -96,6 +99,29 @@ Bridge session restore data is stored as:This file is used for tab/session restoration when restore behavior is enabled.+## Activity Logs++Request activity is stored as one JSONL file per UTC day:++```text+<server.stateDir>/activity/events-YYYY-MM-DD.jsonl+```++By default PinchTab keeps one day of activity data and prunes older daily files when new activity is recorded. You can change that with:++```json+{+ "observability": {+ "activity": {+ "retentionDays": 1,+ "sessionIdleSec": 1800+ }+ }+}+```++`retentionDays` controls on-disk retention for activity logs. `sessionIdleSec` controls session grouping only.+In orchestrator mode, child instances get their own state directory under the profile:```text@@ -106,13 +132,13 @@ PinchTab writes a child `config.json` there so the launched instance can inherit## Action Logs-PinchTab stores profile activity in:+PinchTab also stores profile-level analytics data in:```text<user-config-dir>/action_logs.json```-This powers profile analytics endpoints. It is separate from the per-instance session restore state.+This powers profile analytics endpoints. It is separate from the request/activity JSONL files and from per-instance session restore state.## Customizing Storagediff --git a/internal/activity/activity.go b/internal/activity/activity.gonew file mode 100644index 00000000..07537f4f--- /dev/null+++ b/internal/activity/activity.go@@ -0,0 +1,391 @@+package activity++import (+ "bufio"+ "crypto/rand"+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "fmt"+ "os"+ "path/filepath"+ "sort"+ "strings"+ "sync"+ "time"+)++const (+ defaultSessionIdleTimeout = 30 * time.Minute+ defaultQueryLimit = 200+ defaultRetentionDays = 1+)++type Config struct {+ Enabled bool+ SessionIdle time.Duration+ RetentionDays int+}++type Event struct {+ Timestamp time.Time `json:"timestamp"`+ Source string `json:"source"`+ RequestID string `json:"requestId,omitempty"`+ SessionID string `json:"sessionId,omitempty"`+ ActorID string `json:"actorId,omitempty"`+ AgentID string `json:"agentId,omitempty"`+ Method string `json:"method"`+ Path string `json:"path"`+ Status int `json:"status"`+ DurationMs int64 `json:"durationMs"`+ RemoteAddr string `json:"remoteAddr,omitempty"`+ InstanceID string `json:"instanceId,omitempty"`+ ProfileID string `json:"profileId,omitempty"`+ ProfileName string `json:"profileName,omitempty"`+ TabID string `json:"tabId,omitempty"`+ URL string `json:"url,omitempty"`+ Action string `json:"action,omitempty"`+ Engine string `json:"engine,omitempty"`+ Ref string `json:"ref,omitempty"`+}++type Filter struct {+ Source string+ RequestID string+ SessionID string+ ActorID string+ AgentID string+ InstanceID string+ ProfileID string+ ProfileName string+ TabID string+ Action string+ Engine string+ PathPrefix string+ Since time.Time+ Until time.Time+ Limit int+}++type sessionState struct {+ SessionID string+ LastSeen time.Time+}++type Recorder interface {+ Enabled() bool+ Record(Event) error+ Query(Filter) ([]Event, error)+}++type Store struct {+ dir string+ sessionIdleLimit time.Duration+ retentionDays int++ mu sync.Mutex+ sessions map[string]sessionState+}++type noopRecorder struct{}++func NewRecorder(cfg Config, stateDir string) (Recorder, error) {+ if !cfg.Enabled {+ return noopRecorder{}, nil+ }+ if cfg.SessionIdle <= 0 {+ cfg.SessionIdle = defaultSessionIdleTimeout+ }+ return NewStore(stateDir, cfg.SessionIdle, cfg.RetentionDays)+}++func NewStore(stateDir string, sessionIdle time.Duration, retentionDays int) (*Store, error) {+ activityDir := filepath.Join(stateDir, "activity")+ if err := os.MkdirAll(activityDir, 0750); err != nil {+ return nil, fmt.Errorf("create activity dir: %w", err)+ }+ if sessionIdle <= 0 {+ sessionIdle = defaultSessionIdleTimeout+ }+ if retentionDays < 0 {+ retentionDays = 0+ }+ if retentionDays == 0 {+ retentionDays = defaultRetentionDays+ }++ return &Store{+ dir: activityDir,+ sessionIdleLimit: sessionIdle,+ retentionDays: retentionDays,+ sessions: make(map[string]sessionState),+ }, nil+}++func (s *Store) Enabled() bool {+ return s != nil+}++func (s *Store) Record(evt Event) error {+ if s == nil {+ return nil+ }++ s.mu.Lock()+ defer s.mu.Unlock()++ if evt.Timestamp.IsZero() {+ evt.Timestamp = time.Now().UTC()+ } else {+ evt.Timestamp = evt.Timestamp.UTC()+ }+ if evt.SessionID == "" {+ evt.SessionID = s.sessionIDLocked(evt)+ }++ if err := s.pruneExpiredFilesLocked(evt.Timestamp); err != nil {+ return err+ }++ f, err := os.OpenFile(s.filePathFor(evt.Timestamp), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)+ if err != nil {+ return fmt.Errorf("open activity log: %w", err)+ }+ defer func() { _ = f.Close() }()++ line, err := json.Marshal(evt)+ if err != nil {+ return fmt.Errorf("marshal activity event: %w", err)+ }+ if _, err := f.Write(append(line, '\n')); err != nil {+ return fmt.Errorf("write activity event: %w", err)+ }+ return nil+}++func (s *Store) Query(filter Filter) ([]Event, error) {+ if s == nil {+ return nil, nil+ }++ limit := filter.Limit+ if limit <= 0 {+ limit = defaultQueryLimit+ }++ var events []Event+ for _, path := range s.queryFiles() {+ f, err := os.Open(path)+ if err != nil {+ if os.IsNotExist(err) {+ continue+ }+ return nil, fmt.Errorf("open activity log: %w", err)+ }++ scanner := bufio.NewScanner(f)+ scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)+ for scanner.Scan() {+ var evt Event+ if err := json.Unmarshal(scanner.Bytes(), &evt); err != nil {+ continue+ }+ if !filter.matches(evt) {+ continue+ }+ if len(events) < limit {+ events = append(events, evt)+ continue+ }+ copy(events, events[1:])+ events[len(events)-1] = evt+ }+ closeErr := f.Close()+ if err := scanner.Err(); err != nil {+ return nil, fmt.Errorf("scan activity log: %w", err)+ }+ if closeErr != nil {+ return nil, fmt.Errorf("close activity log: %w", closeErr)+ }+ }+ return events, nil+}++func (noopRecorder) Enabled() bool {+ return false+}++func (noopRecorder) Record(Event) error {+ return nil+}++func (noopRecorder) Query(Filter) ([]Event, error) {+ return []Event{}, nil+}++func (f Filter) matches(evt Event) bool {+ if f.Source != "" && evt.Source != f.Source {+ return false+ }+ if f.RequestID != "" && evt.RequestID != f.RequestID {+ return false+ }+ if f.SessionID != "" && evt.SessionID != f.SessionID {+ return false+ }+ if f.ActorID != "" && evt.ActorID != f.ActorID {+ return false+ }+ if f.AgentID != "" && evt.AgentID != f.AgentID {+ return false+ }+ if f.InstanceID != "" && evt.InstanceID != f.InstanceID {+ return false+ }+ if f.ProfileID != "" && evt.ProfileID != f.ProfileID {+ return false+ }+ if f.ProfileName != "" && evt.ProfileName != f.ProfileName {+ return false+ }+ if f.TabID != "" && evt.TabID != f.TabID {+ return false+ }+ if f.Action != "" && evt.Action != f.Action {+ return false+ }+ if f.Engine != "" && evt.Engine != f.Engine {+ return false+ }+ if f.PathPrefix != "" && !strings.HasPrefix(evt.Path, f.PathPrefix) {+ return false+ }+ if !f.Since.IsZero() && evt.Timestamp.Before(f.Since) {+ return false+ }+ if !f.Until.IsZero() && evt.Timestamp.After(f.Until) {+ return false+ }+ return true+}++func (s *Store) sessionIDLocked(evt Event) string {+ key := evt.ActorID+ if key == "" {+ key = "agent:" + evt.AgentID+ }+ if key == "" || key == "agent:" {+ return ""+ }++ now := evt.Timestamp+ prev, ok := s.sessions[key]+ if ok && now.Sub(prev.LastSeen) <= s.sessionIdleLimit {+ prev.LastSeen = now+ s.sessions[key] = prev+ return prev.SessionID+ }++ sessionID := randomID("ses_")+ s.sessions[key] = sessionState{+ SessionID: sessionID,+ LastSeen: now,+ }+ return sessionID+}++func FingerprintToken(token string) string {+ token = strings.TrimSpace(token)+ if token == "" {+ return ""+ }+ sum := sha256.Sum256([]byte(token))+ return "tok_" + hex.EncodeToString(sum[:6])+}++func (s *Store) filePathFor(ts time.Time) string {+ return filepath.Join(s.dir, fmt.Sprintf("events-%s.jsonl", ts.UTC().Format(time.DateOnly)))+}++func (s *Store) queryFiles() []string {+ s.mu.Lock()+ defer s.mu.Unlock()++ now := time.Now().UTC()+ _ = s.pruneExpiredFilesLocked(now)++ entries, err := os.ReadDir(s.dir)+ if err != nil {+ return nil+ }++ files := make([]string, 0, len(entries)+1)+ legacyPath := filepath.Join(s.dir, "events.jsonl")+ if _, err := os.Stat(legacyPath); err == nil {+ files = append(files, legacyPath)+ }++ for _, entry := range entries {+ if entry.IsDir() {+ continue+ }+ name := entry.Name()+ if !strings.HasPrefix(name, "events-") || !strings.HasSuffix(name, ".jsonl") {+ continue+ }+ files = append(files, filepath.Join(s.dir, name))+ }++ sort.Strings(files)+ return files+}++func (s *Store) pruneExpiredFilesLocked(now time.Time) error {+ if s.retentionDays <= 0 {+ return nil+ }++ entries, err := os.ReadDir(s.dir)+ if err != nil {+ return fmt.Errorf("read activity dir: %w", err)+ }++ keepFrom := now.UTC().AddDate(0, 0, -(s.retentionDays - 1)).Format(time.DateOnly)+ for _, entry := range entries {+ if entry.IsDir() {+ continue+ }+ name := entry.Name()+ if name == "events.jsonl" {+ info, err := entry.Info()+ if err == nil && info.ModTime().UTC().Format(time.DateOnly) < keepFrom {+ if err := os.Remove(filepath.Join(s.dir, name)); err != nil && !os.IsNotExist(err) {+ return fmt.Errorf("remove expired legacy activity log: %w", err)+ }+ }+ continue+ }+ if !strings.HasPrefix(name, "events-") || !strings.HasSuffix(name, ".jsonl") {+ continue+ }+ day := strings.TrimSuffix(strings.TrimPrefix(name, "events-"), ".jsonl")+ if len(day) != len(time.DateOnly) {+ continue+ }+ if day < keepFrom {+ if err := os.Remove(filepath.Join(s.dir, name)); err != nil && !os.IsNotExist(err) {+ return fmt.Errorf("remove expired activity log: %w", err)+ }+ }+ }++ return nil+}++func randomID(prefix string) string {+ b := make([]byte, 4)+ if _, err := rand.Read(b); err != nil {+ return fmt.Sprintf("%s%x", prefix, time.Now().UnixNano()&0xffffffff)+ }+ return prefix + hex.EncodeToString(b)+}diff --git a/internal/activity/activity_test.go b/internal/activity/activity_test.gonew file mode 100644index 00000000..6046e3b6--- /dev/null+++ b/internal/activity/activity_test.go@@ -0,0 +1,103 @@+package activity++import (+ "os"+ "path/filepath"+ "testing"+ "time"+)++func TestStoreRecordAndQuery(t *testing.T) {+ store, err := NewStore(t.TempDir(), 30*time.Minute, 1)+ if err != nil {+ t.Fatalf("NewStore: %v", err)+ }++ now := time.Now().UTC()+ events := []Event{+ {Timestamp: now.Add(-2 * time.Minute), Source: "server", AgentID: "cli", TabID: "tab-1", Path: "/tabs/tab-1/text", Method: "GET", Status: 200},+ {Timestamp: now.Add(-1 * time.Minute), Source: "bridge", AgentID: "mcp", TabID: "tab-2", Path: "/tabs/tab-2/action", Method: "POST", Status: 200},+ }+ for _, evt := range events {+ if err := store.Record(evt); err != nil {+ t.Fatalf("Record: %v", err)+ }+ }++ got, err := store.Query(Filter{TabID: "tab-2", Limit: 10})+ if err != nil {+ t.Fatalf("Query: %v", err)+ }+ if len(got) != 1 {+ t.Fatalf("len(got) = %d, want 1", len(got))+ }+ if got[0].AgentID != "mcp" {+ t.Fatalf("AgentID = %q, want mcp", got[0].AgentID)+ }+}++func TestStoreWritesJSONLFile(t *testing.T) {+ root := t.TempDir()+ store, err := NewStore(root, 30*time.Minute, 1)+ if err != nil {+ t.Fatalf("NewStore: %v", err)+ }+ now := time.Now().UTC()+ if err := store.Record(Event{+ Timestamp: now,+ Source: "server",+ Method: "GET",+ Path: "/health",+ Status: 200,+ }); err != nil {+ t.Fatalf("Record: %v", err)+ }++ path := filepath.Join(root, "activity", "events-"+now.Format(time.DateOnly)+".jsonl")+ if _, err := os.Stat(path); err != nil {+ t.Fatalf("activity log missing: %v", err)+ }+}++func TestStorePrunesExpiredDailyFiles(t *testing.T) {+ root := t.TempDir()+ store, err := NewStore(root, 30*time.Minute, 1)+ if err != nil {+ t.Fatalf("NewStore: %v", err)+ }++ oldDay := time.Now().UTC().AddDate(0, 0, -1)+ if err := store.Record(Event{+ Timestamp: oldDay,+ Source: "server",+ Method: "GET",+ Path: "/old",+ Status: 200,+ }); err != nil {+ t.Fatalf("Record old: %v", err)+ }+ if err := store.Record(Event{+ Timestamp: time.Now().UTC(),+ Source: "server",+ Method: "GET",+ Path: "/new",+ Status: 200,+ }); err != nil {+ t.Fatalf("Record new: %v", err)+ }++ oldPath := filepath.Join(root, "activity", "events-"+oldDay.Format(time.DateOnly)+".jsonl")+ if _, err := os.Stat(oldPath); !os.IsNotExist(err) {+ t.Fatalf("expected old activity file to be pruned, stat err = %v", err)+ }+}++func TestNewRecorderDisabledReturnsNoop(t *testing.T) {+ rec, err := NewRecorder(Config{}, t.TempDir())+ if err != nil {+ t.Fatalf("NewRecorder: %v", err)+ }+ if rec.Enabled() {+ t.Fatal("expected disabled recorder")+ }+}diff --git a/internal/activity/api.go b/internal/activity/api.gonew file mode 100644index 00000000..c0f57562--- /dev/null+++ b/internal/activity/api.go@@ -0,0 +1,119 @@+package activity++import (+ "net/http"+ "strconv"+ "strings"+ "time"++ apiTypes "github.com/pinchtab/pinchtab/internal/api/types"+ "github.com/pinchtab/pinchtab/internal/web"+)++func RegisterHandlers(mux *http.ServeMux, rec Recorder) {+ if mux == nil || rec == nil || !rec.Enabled() {+ return+ }++ mux.HandleFunc("GET /api/activity", func(w http.ResponseWriter, r *http.Request) {+ filter, err := filterFromRequest(r)+ if err != nil {+ web.ErrorCode(w, http.StatusBadRequest, "bad_filter", err.Error(), false, nil)+ return+ }++ events, err := rec.Query(filter)+ if err != nil {+ web.Error(w, http.StatusInternalServerError, err)+ return+ }++ resp := apiTypes.ActivityLogResponse{+ Events: make([]apiTypes.ActivityLogEvent, 0, len(events)),+ Count: len(events),+ }+ for _, event := range events {+ resp.Events = append(resp.Events, apiTypes.ActivityLogEvent{+ Timestamp: event.Timestamp,+ Source: event.Source,+ RequestID: event.RequestID,+ SessionID: event.SessionID,+ ActorID: event.ActorID,+ AgentID: event.AgentID,+ Method: event.Method,+ Path: event.Path,+ Status: event.Status,+ DurationMs: event.DurationMs,+ RemoteAddr: event.RemoteAddr,+ InstanceID: event.InstanceID,+ ProfileID: event.ProfileID,+ ProfileName: event.ProfileName,+ TabID: event.TabID,+ URL: event.URL,+ Action: event.Action,+ Engine: event.Engine,+ Ref: event.Ref,+ })+ }++ web.JSON(w, http.StatusOK, resp)+ })+}++func filterFromRequest(r *http.Request) (Filter, error) {+ q := r.URL.Query()+ filter := Filter{+ Source: strings.TrimSpace(q.Get("source")),+ RequestID: strings.TrimSpace(q.Get("requestId")),+ SessionID: strings.TrimSpace(q.Get("sessionId")),+ ActorID: strings.TrimSpace(q.Get("actorId")),+ AgentID: strings.TrimSpace(q.Get("agentId")),+ InstanceID: strings.TrimSpace(q.Get("instanceId")),+ ProfileID: strings.TrimSpace(q.Get("profileId")),+ ProfileName: strings.TrimSpace(q.Get("profileName")),+ TabID: strings.TrimSpace(q.Get("tabId")),+ Action: strings.TrimSpace(q.Get("action")),+ Engine: strings.TrimSpace(q.Get("engine")),+ PathPrefix: strings.TrimSpace(q.Get("pathPrefix")),+ }++ if limit := strings.TrimSpace(q.Get("limit")); limit != "" {+ n, err := strconv.Atoi(limit)+ if err != nil || n <= 0 {+ return Filter{}, errInvalidQuery("limit")+ }+ filter.Limit = n+ }+ if ageSec := strings.TrimSpace(q.Get("ageSec")); ageSec != "" {+ n, err := strconv.Atoi(ageSec)+ if err != nil || n < 0 {+ return Filter{}, errInvalidQuery("ageSec")+ }+ filter.Since = time.Now().UTC().Add(-time.Duration(n) * time.Second)+ }+ if since := strings.TrimSpace(q.Get("since")); since != "" {+ t, err := time.Parse(time.RFC3339, since)+ if err != nil {+ return Filter{}, errInvalidQuery("since")+ }+ filter.Since = t.UTC()+ }+ if until := strings.TrimSpace(q.Get("until")); until != "" {+ t, err := time.Parse(time.RFC3339, until)+ if err != nil {+ return Filter{}, errInvalidQuery("until")+ }+ filter.Until = t.UTC()+ }+ return filter, nil+}++type invalidQuery string++func (e invalidQuery) Error() string {+ return "invalid query parameter: " + string(e)+}++func errInvalidQuery(name string) error {+ return invalidQuery(name)+}diff --git a/internal/activity/context.go b/internal/activity/context.gonew file mode 100644index 00000000..f5f8d9bb--- /dev/null+++ b/internal/activity/context.go@@ -0,0 +1,279 @@+package activity++import (+ "context"+ "net"+ "net/http"+ "strings"+ "sync"+ "time"++ "github.com/pinchtab/pinchtab/internal/web"+)++const (+ HeaderAgentID = "X-Agent-Id"+ HeaderPTAgentID = "X-PinchTab-Agent-Id"+ HeaderPTActorID = "X-PinchTab-Actor-Id"+ HeaderPTSessionID = "X-PinchTab-Session-Id"+ HeaderPTSource = "X-PinchTab-Source"+ HeaderPTInstance = "X-PinchTab-Instance-Id"+ HeaderPTProfileID = "X-PinchTab-Profile-Id"+ HeaderPTProfile = "X-PinchTab-Profile-Name"+ HeaderPTTabID = "X-PinchTab-Tab-Id"+)++type requestStateKey struct{}++type requestState struct {+ mu sync.Mutex+ event Event+}++type Update struct {+ RequestID string+ SessionID string+ ActorID string+ AgentID string+ InstanceID string+ ProfileID string+ ProfileName string+ TabID string+ URL string+ Action string+ Engine string+ Ref string+}++func Middleware(rec Recorder, source string, next http.Handler) http.Handler {+ if rec == nil || !rec.Enabled() {+ return next+ }++ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ start := time.Now()+ sw := &web.StatusWriter{ResponseWriter: w, Code: 200}+ state := &requestState{+ event: Event{+ Timestamp: start.UTC(),+ Source: source,+ RequestID: requestIDFor(r, w),+ ActorID: actorIDFor(r),+ AgentID: agentIDFor(r),+ SessionID: strings.TrimSpace(r.Header.Get(HeaderPTSessionID)),+ Method: r.Method,+ Path: r.URL.Path,+ RemoteAddr: remoteAddrFor(r),+ InstanceID: strings.TrimSpace(r.Header.Get(HeaderPTInstance)),+ ProfileID: strings.TrimSpace(r.Header.Get(HeaderPTProfileID)),+ ProfileName: strings.TrimSpace(+ r.Header.Get(HeaderPTProfile),+ ),+ TabID: initialTabID(r),+ Action: initialAction(r),+ URL: initialURL(r),+ },+ }++ next.ServeHTTP(sw, r.WithContext(context.WithValue(r.Context(), requestStateKey{}, state)))++ evt := state.snapshot()+ evt.Status = sw.Code+ evt.DurationMs = time.Since(start).Milliseconds()+ if evt.RequestID == "" {+ evt.RequestID = requestIDFor(r, sw)+ }+ if evt.AgentID == "" {+ evt.AgentID = agentIDFor(r)+ }+ if evt.ActorID == "" {+ evt.ActorID = actorIDFor(r)+ }+ if evt.Path == "" {+ evt.Path = r.URL.Path+ }+ if evt.Method == "" {+ evt.Method = r.Method+ }+ _ = rec.Record(evt)+ })+}++func EnrichRequest(r *http.Request, update Update) {+ if r == nil {+ return+ }+ state, _ := r.Context().Value(requestStateKey{}).(*requestState)+ if state == nil {+ return+ }++ state.mu.Lock()+ defer state.mu.Unlock()++ if update.RequestID != "" {+ state.event.RequestID = update.RequestID+ }+ if update.SessionID != "" {+ state.event.SessionID = update.SessionID+ }+ if update.ActorID != "" {+ state.event.ActorID = update.ActorID+ }+ if update.AgentID != "" {+ state.event.AgentID = update.AgentID+ }+ if update.InstanceID != "" {+ state.event.InstanceID = update.InstanceID+ }+ if update.ProfileID != "" {+ state.event.ProfileID = update.ProfileID+ }+ if update.ProfileName != "" {+ state.event.ProfileName = update.ProfileName+ }+ if update.TabID != "" {+ state.event.TabID = update.TabID+ }+ if update.URL != "" {+ state.event.URL = update.URL+ }+ if update.Action != "" {+ state.event.Action = update.Action+ }+ if update.Engine != "" {+ state.event.Engine = update.Engine+ }+ if update.Ref != "" {+ state.event.Ref = update.Ref+ }+}++func PropagateHeaders(ctx context.Context, req *http.Request) {+ if req == nil {+ return+ }+ state, _ := ctx.Value(requestStateKey{}).(*requestState)+ if state == nil {+ return+ }++ evt := state.snapshot()+ if evt.RequestID != "" {+ req.Header.Set("X-Request-Id", evt.RequestID)+ }+ if evt.ActorID != "" {+ req.Header.Set(HeaderPTActorID, evt.ActorID)+ }+ if evt.AgentID != "" {+ req.Header.Set(HeaderPTAgentID, evt.AgentID)+ }+ if evt.SessionID != "" {+ req.Header.Set(HeaderPTSessionID, evt.SessionID)+ }+ if evt.InstanceID != "" {+ req.Header.Set(HeaderPTInstance, evt.InstanceID)+ }+ if evt.ProfileID != "" {+ req.Header.Set(HeaderPTProfileID, evt.ProfileID)+ }+ if evt.ProfileName != "" {+ req.Header.Set(HeaderPTProfile, evt.ProfileName)+ }+ if evt.TabID != "" {+ req.Header.Set(HeaderPTTabID, evt.TabID)+ }+ if evt.Source != "" {+ req.Header.Set(HeaderPTSource, evt.Source)+ }+}++func requestIDFor(r *http.Request, w http.ResponseWriter) string {+ if w != nil {+ if rid := strings.TrimSpace(w.Header().Get("X-Request-Id")); rid != "" {+ return rid+ }+ }+ return strings.TrimSpace(r.Header.Get("X-Request-Id"))+}++func actorIDFor(r *http.Request) string {+ if actorID := strings.TrimSpace(r.Header.Get(HeaderPTActorID)); actorID != "" {+ return actorID+ }+ token := strings.TrimSpace(r.URL.Query().Get("token"))+ if token == "" {+ auth := strings.TrimSpace(r.Header.Get("Authorization"))+ if strings.HasPrefix(strings.ToLower(auth), "bearer ") {+ token = strings.TrimSpace(auth[7:])+ } else {+ token = auth+ }+ }+ return FingerprintToken(token)+}++func agentIDFor(r *http.Request) string {+ for _, header := range []string{HeaderPTAgentID, HeaderAgentID, "X-Agent-ID"} {+ if value := strings.TrimSpace(r.Header.Get(header)); value != "" {+ return value+ }+ }+ return ""+}++func remoteAddrFor(r *http.Request) string {+ if xff := strings.TrimSpace(r.Header.Get("X-Forwarded-For")); xff != "" {+ return strings.TrimSpace(strings.Split(xff, ",")[0])+ }+ host, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr))+ if err == nil && host != "" {+ return host+ }+ return strings.TrimSpace(r.RemoteAddr)+}++func (s *requestState) snapshot() Event {+ s.mu.Lock()+ defer s.mu.Unlock()+ return s.event+}++func initialTabID(r *http.Request) string {+ if tabID := strings.TrimSpace(r.Header.Get(HeaderPTTabID)); tabID != "" {+ return tabID+ }+ if tabID := strings.TrimSpace(r.URL.Query().Get("tabId")); tabID != "" {+ return tabID+ }+ path := strings.Trim(r.URL.Path, "/")+ parts := strings.Split(path, "/")+ if len(parts) >= 2 && parts[0] == "tabs" {+ return strings.TrimSpace(parts[1])+ }+ return ""+}++func initialAction(r *http.Request) string {+ if action := strings.TrimSpace(r.URL.Query().Get("kind")); action != "" {+ return action+ }+ switch {+ case r.URL.Path == "/navigate" || strings.HasSuffix(r.URL.Path, "/navigate"):+ return "navigate"+ case r.URL.Path == "/snapshot" || strings.HasSuffix(r.URL.Path, "/snapshot"):+ return "snapshot"+ case r.URL.Path == "/text" || strings.HasSuffix(r.URL.Path, "/text"):+ return "text"+ case r.URL.Path == "/pdf" || strings.HasSuffix(r.URL.Path, "/pdf"):+ return "pdf"+ }+ return ""+}++func initialURL(r *http.Request) string {+ if u := strings.TrimSpace(r.URL.Query().Get("url")); u != "" {+ return u+ }+ return ""+}diff --git a/internal/api/types/types.go b/internal/api/types/types.goindex 9fddadd2..ae4d7a18 100644--- a/internal/api/types/types.go+++ b/internal/api/types/types.go@@ -63,6 +63,35 @@ type ActivityEvent struct {Details map[string]interface{} `json:"details,omitempty"`}+// ActivityLogEvent represents a queryable backend activity record.+type ActivityLogEvent struct {+ Timestamp time.Time `json:"timestamp"`+ Source string `json:"source"`+ RequestID string `json:"requestId,omitempty"`+ SessionID string `json:"sessionId,omitempty"`+ ActorID string `json:"actorId,omitempty"`+ AgentID string `json:"agentId,omitempty"`+ Method string `json:"method"`+ Path string `json:"path"`+ Status int `json:"status"`+ DurationMs int64 `json:"durationMs"`+ RemoteAddr string `json:"remoteAddr,omitempty"`+ InstanceID string `json:"instanceId,omitempty"`+ ProfileID string `json:"profileId,omitempty"`+ ProfileName string `json:"profileName,omitempty"`+ TabID string `json:"tabId,omitempty"`+ URL string `json:"url,omitempty"`+ Action string `json:"action,omitempty"`+ Engine string `json:"engine,omitempty"`+ Ref string `json:"ref,omitempty"`+}++// ActivityLogResponse is returned by the /api/activity endpoint.+type ActivityLogResponse struct {+ Events []ActivityLogEvent `json:"events"`+ Count int `json:"count"`+}+// ScreencastSettings configures live tab previews.type ScreencastSettings struct {FPS int `json:"fps"`diff --git a/internal/cli/actions/actions_activity.go b/internal/cli/actions/actions_activity.gonew file mode 100644index 00000000..addac592--- /dev/null+++ b/internal/cli/actions/actions_activity.go@@ -0,0 +1,34 @@+package actions++import (+ "net/http"+ "net/url"+ "strconv"++ "github.com/pinchtab/pinchtab/internal/cli/apiclient"+ "github.com/spf13/cobra"+)++// Activity lists recorded activity events.+func Activity(client *http.Client, base, token string, cmd *cobra.Command) {+ apiclient.DoGet(client, base, token, "/api/activity", activityParams(cmd, ""))+}++// ActivityTab lists recorded activity events for a specific tab.+func ActivityTab(client *http.Client, base, token, tabID string, cmd *cobra.Command) {+ apiclient.DoGet(client, base, token, "/api/activity", activityParams(cmd, tabID))+}++func activityParams(cmd *cobra.Command, tabID string) url.Values {+ params := url.Values{}+ if tabID != "" {+ params.Set("tabId", tabID)+ }+ if limit, _ := cmd.Flags().GetInt("limit"); limit > 0 {+ params.Set("limit", strconv.Itoa(limit))+ }+ if ageSec, _ := cmd.Flags().GetInt("age-sec"); ageSec > 0 {+ params.Set("ageSec", strconv.Itoa(ageSec))+ }+ return params+}diff --git a/internal/cli/actions/actions_activity_test.go b/internal/cli/actions/actions_activity_test.gonew file mode 100644index 00000000..9f314a9a--- /dev/null+++ b/internal/cli/actions/actions_activity_test.go@@ -0,0 +1,41 @@+package actions++import (+ "testing"++ "github.com/spf13/cobra"+)++func newActivityCmd() *cobra.Command {+ cmd := &cobra.Command{}+ cmd.Flags().Int("limit", 0, "")+ cmd.Flags().Int("age-sec", 0, "")+ return cmd+}++func TestActivityParams(t *testing.T) {+ cmd := newActivityCmd()+ if err := cmd.Flags().Set("limit", "50"); err != nil {+ t.Fatal(err)+ }+ if err := cmd.Flags().Set("age-sec", "300"); err != nil {+ t.Fatal(err)+ }++ got := activityParams(cmd, "").Encode()+ if got != "ageSec=300&limit=50" {+ t.Fatalf("expected ageSec and limit query, got %q", got)+ }+}++func TestActivityTabParams(t *testing.T) {+ cmd := newActivityCmd()+ if err := cmd.Flags().Set("limit", "25"); err != nil {+ t.Fatal(err)+ }++ got := activityParams(cmd, "tab_123").Encode()+ if got != "limit=25&tabId=tab_123" {+ t.Fatalf("expected limit and tabId query, got %q", got)+ }+}diff --git a/internal/cli/apiclient/client.go b/internal/cli/apiclient/client.goindex e583cd50..a82c2d99 100644--- a/internal/cli/apiclient/client.go+++ b/internal/cli/apiclient/client.go@@ -10,6 +10,8 @@ import ("net/url""os""time"++ "github.com/pinchtab/pinchtab/internal/activity")func DoGet(client *http.Client, base, token, path string, params url.Values) map[string]any {@@ -21,6 +23,7 @@ func DoGet(client *http.Client, base, token, path string, params url.Values) mapif token != "" {req.Header.Set("Authorization", "Bearer "+token)}+ req.Header.Set(activity.HeaderAgentID, "cli")resp, err := client.Do(req)if err != nil {fatal("Request failed: %v", err)@@ -58,6 +61,7 @@ func DoGetRaw(client *http.Client, base, token, path string, params url.Values)if token != "" {req.Header.Set("Authorization", "Bearer "+token)}+ req.Header.Set(activity.HeaderAgentID, "cli")resp, err := client.Do(req)if err != nil {fatal("Request failed: %v", err)@@ -79,6 +83,7 @@ func DoPost(client *http.Client, base, token, path string, body map[string]any)if token != "" {req.Header.Set("Authorization", "Bearer "+token)}+ req.Header.Set(activity.HeaderAgentID, "cli")resp, err := client.Do(req)if err != nil {fatal("Request failed: %v", err)diff --git a/internal/config/config_file.go b/internal/config/config_file.goindex 527d0e14..6bf936f3 100644--- a/internal/config/config_file.go+++ b/internal/config/config_file.go@@ -26,6 +26,9 @@ func DefaultFileConfig() FileConfig {allowUpload := falsemaxRedirects := -1attachEnabled := true+ activityEnabled := true+ activitySessionIdleSec := 1800+ activityRetentionDays := 1return FileConfig{ConfigVersion: CurrentConfigVersion,Server: ServerConfig{@@ -85,19 +88,27 @@ func DefaultFileConfig() FileConfig {ShutdownSec: 10,WaitNavMs: 1000,},+ Observability: ObservabilityFileConfig{+ Activity: ActivityFileConfig{+ Enabled: &activityEnabled,+ SessionIdleSec: &activitySessionIdleSec,+ RetentionDays: &activityRetentionDays,+ },+ },}}type fileConfigJSON struct {- ConfigVersion string `json:"configVersion,omitempty"`- Server serverConfigJSON `json:"server"`- Browser browserConfigJSON `json:"browser"`- InstanceDefaults instanceDefaultsConfigJSON `json:"instanceDefaults"`- Security securityConfigJSON `json:"security"`- Profiles profilesConfigJSON `json:"profiles"`- MultiInstance multiInstanceConfigJSON `json:"multiInstance"`- Timeouts timeoutsConfigJSON `json:"timeouts"`- Scheduler schedulerFileConfigJSON `json:"scheduler"`+ ConfigVersion string `json:"configVersion,omitempty"`+ Server serverConfigJSON `json:"server"`+ Browser browserConfigJSON `json:"browser"`+ InstanceDefaults instanceDefaultsConfigJSON `json:"instanceDefaults"`+ Security securityConfigJSON `json:"security"`+ Profiles profilesConfigJSON `json:"profiles"`+ MultiInstance multiInstanceConfigJSON `json:"multiInstance"`+ Timeouts timeoutsConfigJSON `json:"timeouts"`+ Scheduler schedulerFileConfigJSON `json:"scheduler"`+ Observability observabilityFileConfigJSON `json:"observability"`}type serverConfigJSON struct {@@ -195,6 +206,16 @@ type schedulerFileConfigJSON struct {WorkerCount *int `json:"workerCount"`}+type observabilityFileConfigJSON struct {+ Activity activityConfigJSON `json:"activity"`+}++type activityConfigJSON struct {+ Enabled *bool `json:"enabled"`+ SessionIdleSec *int `json:"sessionIdleSec"`+ RetentionDays *int `json:"retentionDays"`+}+func copyStringSlice(items []string) []string {if items == nil {return []string{}@@ -289,6 +310,13 @@ func (fc FileConfig) MarshalJSON() ([]byte, error) {ResultTTLSec: fc.Scheduler.ResultTTLSec,WorkerCount: fc.Scheduler.WorkerCount,},+ Observability: observabilityFileConfigJSON{+ Activity: activityConfigJSON{+ Enabled: fc.Observability.Activity.Enabled,+ SessionIdleSec: fc.Observability.Activity.SessionIdleSec,+ RetentionDays: fc.Observability.Activity.RetentionDays,+ },+ },})}@@ -319,6 +347,9 @@ func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {restartInitBackoffSec := int(cfg.RestartInitBackoff / time.Second)restartMaxBackoffSec := int(cfg.RestartMaxBackoff / time.Second)restartStableAfterSec := int(cfg.RestartStableAfter / time.Second)+ activityEnabled := cfg.Observability.Activity.Enabled+ activitySessionIdleSec := cfg.Observability.Activity.SessionIdleSec+ activityRetentionDays := cfg.Observability.Activity.RetentionDaysmode := "headless"if !cfg.Headless {@@ -389,6 +420,13 @@ func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {ShutdownSec: int(cfg.ShutdownTimeout / time.Second),WaitNavMs: int(cfg.WaitNavDelay / time.Millisecond),},+ Observability: ObservabilityFileConfig{+ Activity: ActivityFileConfig{+ Enabled: &activityEnabled,+ SessionIdleSec: &activitySessionIdleSec,+ RetentionDays: &activityRetentionDays,+ },+ },}return fcdiff --git a/internal/config/config_load.go b/internal/config/config_load.goindex aa7899ea..e3028beb 100644--- a/internal/config/config_load.go+++ b/internal/config/config_load.go@@ -80,6 +80,15 @@ func Load() *RuntimeConfig {// Engine default (set via config.json only)Engine: "chrome",++ // Observability defaults+ Observability: ObservabilityConfig{+ Activity: ActivityConfig{+ Enabled: true,+ SessionIdleSec: 1800,+ RetentionDays: 1,+ },+ },}finalizeProfileConfig(cfg)@@ -197,6 +206,15 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {}// IDPI – copy the whole struct; individual fields have safe zero-value defaults.cfg.IDPI = fc.Security.IDPI+ if fc.Observability.Activity.Enabled != nil {+ cfg.Observability.Activity.Enabled = *fc.Observability.Activity.Enabled+ }+ if fc.Observability.Activity.SessionIdleSec != nil {+ cfg.Observability.Activity.SessionIdleSec = *fc.Observability.Activity.SessionIdleSec+ }+ if fc.Observability.Activity.RetentionDays != nil {+ cfg.Observability.Activity.RetentionDays = *fc.Observability.Activity.RetentionDays+ }// Browserif fc.Browser.ChromeVersion != "" {diff --git a/internal/config/config_types.go b/internal/config/config_types.goindex 63127ec4..9e46d3ac 100644--- a/internal/config/config_types.go+++ b/internal/config/config_types.go@@ -69,6 +69,9 @@ type RuntimeConfig struct {// Scheduler settings (dashboard mode only)Scheduler SchedulerConfig++ // Observability settings+ Observability ObservabilityConfig}// IDPIConfig holds the configuration for the Indirect Prompt Injection (IDPI)@@ -95,17 +98,28 @@ type SchedulerConfig struct {WorkerCount int `json:"workerCount,omitempty"`}+type ObservabilityConfig struct {+ Activity ActivityConfig `json:"activity,omitempty"`+}++type ActivityConfig struct {+ Enabled bool `json:"enabled,omitempty"`+ SessionIdleSec int `json:"sessionIdleSec,omitempty"`+ RetentionDays int `json:"retentionDays,omitempty"`+}+// FileConfig is the persistent configuration written to disk.type FileConfig struct {- ConfigVersion string `json:"configVersion,omitempty"`- Server ServerConfig `json:"server,omitempty"`- Browser BrowserConfig `json:"browser,omitempty"`- InstanceDefaults InstanceDefaultsConfig `json:"instanceDefaults,omitempty"`- Security SecurityConfig `json:"security,omitempty"`- Profiles ProfilesConfig `json:"profiles,omitempty"`- MultiInstance MultiInstanceConfig `json:"multiInstance,omitempty"`- Timeouts TimeoutsConfig `json:"timeouts,omitempty"`- Scheduler SchedulerFileConfig `json:"scheduler,omitempty"`+ ConfigVersion string `json:"configVersion,omitempty"`+ Server ServerConfig `json:"server,omitempty"`+ Browser BrowserConfig `json:"browser,omitempty"`+ InstanceDefaults InstanceDefaultsConfig `json:"instanceDefaults,omitempty"`+ Security SecurityConfig `json:"security,omitempty"`+ Profiles ProfilesConfig `json:"profiles,omitempty"`+ MultiInstance MultiInstanceConfig `json:"multiInstance,omitempty"`+ Timeouts TimeoutsConfig `json:"timeouts,omitempty"`+ Scheduler SchedulerFileConfig `json:"scheduler,omitempty"`+ Observability ObservabilityFileConfig `json:"observability,omitempty"`}type ServerConfig struct {@@ -193,3 +207,13 @@ type SchedulerFileConfig struct {ResultTTLSec *int `json:"resultTTLSec,omitempty"`WorkerCount *int `json:"workerCount,omitempty"`}++type ObservabilityFileConfig struct {+ Activity ActivityFileConfig `json:"activity,omitempty"`+}++type ActivityFileConfig struct {+ Enabled *bool `json:"enabled,omitempty"`+ SessionIdleSec *int `json:"sessionIdleSec,omitempty"`+ RetentionDays *int `json:"retentionDays,omitempty"`+}diff --git a/internal/config/validate.go b/internal/config/validate.goindex 67392f59..1239073a 100644--- a/internal/config/validate.go+++ b/internal/config/validate.go@@ -166,6 +166,19 @@ func ValidateFileConfig(fc *FileConfig) []error {})}+ if fc.Observability.Activity.SessionIdleSec != nil && *fc.Observability.Activity.SessionIdleSec < 0 {+ errs = append(errs, ValidationError{+ Field: "observability.activity.sessionIdleSec",+ Message: fmt.Sprintf("must be >= 0 (got %d)", *fc.Observability.Activity.SessionIdleSec),+ })+ }+ if fc.Observability.Activity.RetentionDays != nil && *fc.Observability.Activity.RetentionDays < 0 {+ errs = append(errs, ValidationError{+ Field: "observability.activity.retentionDays",+ Message: fmt.Sprintf("must be >= 0 (got %d)", *fc.Observability.Activity.RetentionDays),+ })+ }+return errs}diff --git a/internal/handlers/actions.go b/internal/handlers/actions.goindex b6c4f8ca..ce4b533e 100644--- a/internal/handlers/actions.go+++ b/internal/handlers/actions.go@@ -93,6 +93,7 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {web.Error(w, 400, fmt.Errorf("missing required field 'kind'"))return}+ h.recordActionRequest(r, req)if !h.shouldUseLiteAction(req.Kind) {if available := h.Bridge.AvailableActions(); len(available) > 0 {known := false@@ -118,7 +119,7 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {resolvedTabID = req.TabID} else {var err error- ctx, resolvedTabID, err = h.Bridge.TabContext(req.TabID)+ ctx, resolvedTabID, err = h.tabContext(r, req.TabID)if err != nil {web.Error(w, 404, err)return@@ -132,6 +133,7 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {return}}+ h.recordResolvedTab(r, resolvedTabID)// Allow custom timeout via query param (1-60 seconds)actionTimeout := h.Config.ActionTimeout@@ -325,6 +327,7 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {if engineName == "lite" {w.Header().Set("X-Engine", "lite")+ h.recordEngine(r, "lite")}resp := map[string]any{"success": true, "result": result}if recoveryResult != nil {diff --git a/internal/handlers/activity_helpers.go b/internal/handlers/activity_helpers.gonew file mode 100644index 00000000..9b86a23a--- /dev/null+++ b/internal/handlers/activity_helpers.go@@ -0,0 +1,56 @@+package handlers++import (+ "context"+ "net/http"++ "github.com/pinchtab/pinchtab/internal/activity"+ "github.com/pinchtab/pinchtab/internal/bridge"+)++func (h *Handlers) tabContext(r *http.Request, tabID string) (context.Context, string, error) {+ ctx, resolvedID, err := h.Bridge.TabContext(tabID)+ if err == nil {+ h.recordActivity(r, activity.Update{TabID: resolvedID})+ }+ return ctx, resolvedID, err+}++func (h *Handlers) recordActivity(r *http.Request, update activity.Update) {+ activity.EnrichRequest(r, update)+}++func (h *Handlers) recordNavigateRequest(r *http.Request, tabID, url string) {+ h.recordActivity(r, activity.Update{+ Action: "navigate",+ TabID: tabID,+ URL: url,+ })+}++func (h *Handlers) recordActionRequest(r *http.Request, req bridge.ActionRequest) {+ h.recordActivity(r, activity.Update{+ Action: req.Kind,+ TabID: req.TabID,+ Ref: req.Ref,+ })+}++func (h *Handlers) recordReadRequest(r *http.Request, action, tabID string) {+ h.recordActivity(r, activity.Update{+ Action: action,+ TabID: tabID,+ })+}++func (h *Handlers) recordResolvedURL(r *http.Request, url string) {+ h.recordActivity(r, activity.Update{URL: url})+}++func (h *Handlers) recordEngine(r *http.Request, engine string) {+ h.recordActivity(r, activity.Update{Engine: engine})+}++func (h *Handlers) recordResolvedTab(r *http.Request, tabID string) {+ h.recordActivity(r, activity.Update{TabID: tabID})+}diff --git a/internal/handlers/navigation.go b/internal/handlers/navigation.goindex 42fd2cda..0be292b1 100644--- a/internal/handlers/navigation.go+++ b/internal/handlers/navigation.go@@ -95,9 +95,11 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {web.Error(w, 400, fmt.Errorf("url required"))return}+ h.recordNavigateRequest(r, req.TabID, req.URL)// --- Lite engine fast path ---if h.useLite(engine.CapNavigate, req.URL) {+ h.recordEngine(r, "lite")result, err := h.Router.Lite().Navigate(r.Context(), req.URL)if err != nil {web.Error(w, 502, fmt.Errorf("lite navigate: %w", err))@@ -211,12 +213,14 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {var url string_ = chromedp.Run(tCtx, chromedp.Location(&url))title, _ := bridge.WaitForTitle(tCtx, titleWait)+ h.recordResolvedTab(r, hashTabID)+ h.recordResolvedURL(r, url)web.JSON(w, 200, map[string]any{"tabId": hashTabID, "url": url, "title": title})return}- ctx, resolvedTabID, err := h.Bridge.TabContext(req.TabID)+ ctx, resolvedTabID, err := h.tabContext(r, req.TabID)if err != nil {web.Error(w, 404, err)return@@ -233,7 +237,6 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {tCtx, tCancel := context.WithTimeout(ctx, navTimeout)defer tCancel()go web.CancelOnClientDone(r.Context(), tCancel)-if len(blockPatterns) > 0 {_ = bridge.SetResourceBlocking(tCtx, blockPatterns)} else {@@ -263,6 +266,7 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {var url string_ = chromedp.Run(tCtx, chromedp.Location(&url))title, _ := bridge.WaitForTitle(tCtx, titleWait)+ h.recordResolvedURL(r, url)web.JSON(w, 200, map[string]any{"tabId": resolvedTabID, "url": url, "title": title})}diff --git a/internal/handlers/pdf.go b/internal/handlers/pdf.goindex 494966f0..80cf2785 100644--- a/internal/handlers/pdf.go+++ b/internal/handlers/pdf.go@@ -52,8 +52,9 @@ func (h *Handlers) HandlePDF(w http.ResponseWriter, r *http.Request) {tabID := r.URL.Query().Get("tabId")output := r.URL.Query().Get("output")+ h.recordReadRequest(r, "pdf", tabID)- ctx, _, err := h.Bridge.TabContext(tabID)+ ctx, _, err := h.tabContext(r, tabID)if err != nil {web.Error(w, 404, err)returndiff --git a/internal/handlers/snapshot.go b/internal/handlers/snapshot.goindex fb70a10d..829ef57b 100644--- a/internal/handlers/snapshot.go+++ b/internal/handlers/snapshot.go@@ -64,7 +64,9 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {// --- Lite engine fast path ---tabID := r.URL.Query().Get("tabId")+ h.recordReadRequest(r, "snapshot", tabID)if h.useLite(engine.CapSnapshot, "") {+ h.recordEngine(r, "lite")nodes, err := h.Router.Lite().Snapshot(r.Context(), tabID, filter)if err != nil {web.Error(w, 500, fmt.Errorf("lite snapshot: %w", err))@@ -108,12 +110,11 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {}}- ctx, resolvedTabID, err := h.Bridge.TabContext(tabID)+ ctx, resolvedTabID, err := h.tabContext(r, tabID)if err != nil {web.Error(w, 404, err)return}-tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)defer tCancel()go web.CancelOnClientDone(r.Context(), tCancel)@@ -183,6 +184,7 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {chromedp.Location(&url),chromedp.Title(&title),)+ h.recordResolvedURL(r, url)// IDPI: scan accessibility-tree node names and values for injection patterns.// The scan runs after the snapshot is built so truncation has already reduceddiff --git a/internal/handlers/text.go b/internal/handlers/text.goindex cb13f0d8..7e675d5c 100644--- a/internal/handlers/text.go+++ b/internal/handlers/text.go@@ -20,7 +20,9 @@ import (func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {// --- Lite engine fast path ---tabID := r.URL.Query().Get("tabId")+ h.recordReadRequest(r, "text", tabID)if h.useLite(engine.CapText, "") {+ h.recordEngine(r, "lite")text, err := h.Router.Lite().Text(r.Context(), tabID)if err != nil {web.Error(w, 500, fmt.Errorf("lite text: %w", err))@@ -47,7 +49,7 @@ func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {}}- ctx, _, err := h.Bridge.TabContext(tabID)+ ctx, _, err := h.tabContext(r, tabID)if err != nil {web.Error(w, 404, err)return@@ -85,6 +87,7 @@ func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {chromedp.Location(&url),chromedp.Title(&title),)+ h.recordResolvedURL(r, url)// IDPI: scan extracted text for injection patterns before it reaches the caller.var idpiResult idpi.CheckResultdiff --git a/internal/mcp/client.go b/internal/mcp/client.goindex 0e11a204..de0499a4 100644--- a/internal/mcp/client.go+++ b/internal/mcp/client.go@@ -11,6 +11,8 @@ import ("net/url""strings""time"++ "github.com/pinchtab/pinchtab/internal/activity")// Client is an HTTP client for PinchTab's REST API.@@ -47,6 +49,8 @@ func (c *Client) do(req *http.Request) ([]byte, int, error) {if c.Token != "" {req.Header.Set("Authorization", "Bearer "+c.Token)}+ req.Header.Set(activity.HeaderAgentID, "mcp")+ req.Header.Set(activity.HeaderPTSource, "mcp")resp, err := c.HTTPClient.Do(req)if err != nil {return nil, 0, fmt.Errorf("request %s %s: %w", req.Method, req.URL.Path, err)diff --git a/internal/orchestrator/proxy.go b/internal/orchestrator/proxy.goindex a93c4621..3c889652 100644--- a/internal/orchestrator/proxy.go+++ b/internal/orchestrator/proxy.go@@ -6,6 +6,7 @@ import ("net/url""strings"+ "github.com/pinchtab/pinchtab/internal/activity""github.com/pinchtab/pinchtab/internal/bridge""github.com/pinchtab/pinchtab/internal/handlers"iproxy "github.com/pinchtab/pinchtab/internal/proxy"@@ -25,6 +26,12 @@ func (o *Orchestrator) proxyTabRequest(w http.ResponseWriter, r *http.Request) {}proxyToInstance := func(inst *bridge.Instance) {+ activity.EnrichRequest(r, activity.Update{+ InstanceID: inst.ID,+ ProfileID: inst.ProfileID,+ ProfileName: inst.ProfileName,+ TabID: tabID,+ })targetURL, buildErr := o.instancePathURLFromBridge(inst, r.URL.Path, r.URL.RawQuery)if buildErr != nil {web.Error(w, 502, buildErr)@@ -81,6 +88,11 @@ func (o *Orchestrator) proxyToInstance(w http.ResponseWriter, r *http.Request) {web.Error(w, 503, fmt.Errorf("instance %q is not running (status: %s)", id, inst.Status))return}+ activity.EnrichRequest(r, activity.Update{+ InstanceID: inst.ID,+ ProfileID: inst.ProfileID,+ ProfileName: inst.ProfileName,+ })targetPath := r.URL.Pathif len(targetPath) > len("/instances/"+id) {@@ -105,7 +117,15 @@ func (o *Orchestrator) proxyToURL(w http.ResponseWriter, r *http.Request, targetreturn o.proxyTargetInstance(u) != nil},RewriteRequest: func(req *http.Request) {+ activity.PropagateHeaders(r.Context(), req)if inst := o.proxyTargetInstance(targetURL); inst != nil {+ req.Header.Set(activity.HeaderPTInstance, inst.ID)+ if inst.ProfileID != "" {+ req.Header.Set(activity.HeaderPTProfileID, inst.ProfileID)+ }+ if inst.ProfileName != "" {+ req.Header.Set(activity.HeaderPTProfile, inst.ProfileName)+ }o.applyInstanceAuth(req, inst)}},@@ -147,6 +167,11 @@ func (o *Orchestrator) handleProxyScreencast(w http.ResponseWriter, r *http.Requweb.Error(w, 404, fmt.Errorf("instance not found or not running"))return}+ activity.EnrichRequest(r, activity.Update{+ InstanceID: inst.ID,+ ProfileID: inst.ProfileID,+ ProfileName: inst.ProfileName,+ })targetURL, err := o.instancePathURL(inst, "/screencast", r.URL.RawQuery)if err != nil {@@ -156,6 +181,7 @@ func (o *Orchestrator) handleProxyScreencast(w http.ResponseWriter, r *http.Requreq := r.Clone(r.Context())req.Header = r.Header.Clone()+ activity.PropagateHeaders(r.Context(), req)o.applyInstanceAuth(req, inst)// Use WebSocket proxy for proper upgradediff --git a/internal/proxy/proxy.go b/internal/proxy/proxy.goindex c8e3941f..8fe40d73 100644--- a/internal/proxy/proxy.go+++ b/internal/proxy/proxy.go@@ -11,6 +11,7 @@ import ("strings""time"+ "github.com/pinchtab/pinchtab/internal/activity""github.com/pinchtab/pinchtab/internal/handlers""github.com/pinchtab/pinchtab/internal/web")@@ -52,6 +53,7 @@ func Forward(w http.ResponseWriter, r *http.Request, targetURL *url.URL, opts OpproxyReq.URL = targetURLproxyReq.Host = targetURL.HostproxyReq.Header = r.Header.Clone()+ activity.PropagateHeaders(r.Context(), proxyReq)if opts.RewriteRequest != nil {opts.RewriteRequest(proxyReq)}diff --git a/internal/scheduler/scheduler.go b/internal/scheduler/scheduler.goindex 26d6ad66..b7cc3314 100644--- a/internal/scheduler/scheduler.go+++ b/internal/scheduler/scheduler.go@@ -12,6 +12,8 @@ import ("net/url""sync""time"++ "github.com/pinchtab/pinchtab/internal/activity")// InstanceResolver finds the localhost port for a given tab ID.@@ -401,6 +403,12 @@ func (s *Scheduler) executeTask(ctx context.Context, t *Task) (any, error) {return nil, fmt.Errorf("failed to create request: %w", err)}req.Header.Set("Content-Type", "application/json")+ req.Header.Set(activity.HeaderPTSource, "scheduler")+ req.Header.Set(activity.HeaderPTTabID, t.TabID)+ if t.AgentID != "" {+ req.Header.Set(activity.HeaderAgentID, t.AgentID)+ req.Header.Set(activity.HeaderPTAgentID, t.AgentID)+ }resp, err := s.client.Do(req)if err != nil {diff --git a/internal/server/bridge.go b/internal/server/bridge.goindex 5ef30d27..0a3624b8 100644--- a/internal/server/bridge.go+++ b/internal/server/bridge.go@@ -10,6 +10,7 @@ import ("syscall""time"+ "github.com/pinchtab/pinchtab/internal/activity""github.com/pinchtab/pinchtab/internal/assets""github.com/pinchtab/pinchtab/internal/bridge""github.com/pinchtab/pinchtab/internal/cli"@@ -32,6 +33,15 @@ func RunBridgeServer(cfg *config.RuntimeConfig) {bridgeInstance := bridge.New(context.Background(), nil, cfg)bridgeInstance.StealthScript = assets.StealthScript+ actStore, err := activity.NewRecorder(activity.Config{+ Enabled: cfg.Observability.Activity.Enabled,+ SessionIdle: time.Duration(cfg.Observability.Activity.SessionIdleSec) * time.Second,+ RetentionDays: cfg.Observability.Activity.RetentionDays,+ }, cfg.StateDir)+ if err != nil {+ slog.Error("activity store", "err", err)+ os.Exit(1)+ }mux := http.NewServeMux()h := handlers.New(bridgeInstance, cfg, nil, nil, nil)@@ -47,11 +57,18 @@ func RunBridgeServer(cfg *config.RuntimeConfig) {})}h.RegisterRoutes(mux, doShutdown)+ activity.RegisterHandlers(mux, actStore)cli.LogSecurityWarnings(cfg)server := &http.Server{- Addr: listenAddr,- Handler: handlers.RequestIDMiddleware(handlers.LoggingMiddleware(handlers.AuthMiddleware(cfg, mux))),+ Addr: listenAddr,+ Handler: handlers.RequestIDMiddleware(+ activity.Middleware(+ actStore,+ "bridge",+ handlers.LoggingMiddleware(handlers.AuthMiddleware(cfg, mux)),+ ),+ ),ReadHeaderTimeout: 10 * time.Second,ReadTimeout: 30 * time.Second,WriteTimeout: 60 * time.Second,diff --git a/internal/server/server.go b/internal/server/server.goindex 3da4029c..0cb7667f 100644--- a/internal/server/server.go+++ b/internal/server/server.go@@ -11,6 +11,7 @@ import ("syscall""time"+ "github.com/pinchtab/pinchtab/internal/activity""github.com/pinchtab/pinchtab/internal/bridge""github.com/pinchtab/pinchtab/internal/cli""github.com/pinchtab/pinchtab/internal/config"@@ -69,12 +70,22 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {Instance: evt.Instance,})})+ actStore, err := activity.NewRecorder(activity.Config{+ Enabled: cfg.Observability.Activity.Enabled,+ SessionIdle: time.Duration(cfg.Observability.Activity.SessionIdleSec) * time.Second,+ RetentionDays: cfg.Observability.Activity.RetentionDays,+ }, cfg.StateDir)+ if err != nil {+ slog.Error("activity store", "err", err)+ os.Exit(1)+ }mux := http.NewServeMux()dash.RegisterHandlers(mux)configAPI.RegisterHandlers(mux)profMgr.RegisterHandlers(mux)+ activity.RegisterHandlers(mux, actStore)strategyName := cfg.Strategyif strategyName == "" {@@ -164,7 +175,13 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {web.JSON(w, 200, map[string]any{"metrics": handlers.SnapshotMetrics()})})- handler := handlers.LoggingMiddleware(handlers.CorsMiddleware(handlers.AuthMiddleware(cfg, mux)))+ handler := handlers.RequestIDMiddleware(+ activity.Middleware(+ actStore,+ "server",+ handlers.LoggingMiddleware(handlers.CorsMiddleware(handlers.AuthMiddleware(cfg, mux))),+ ),+ )cli.LogSecurityWarnings(cfg)srv := &http.Server{diff --git a/internal/strategy/activity.go b/internal/strategy/activity.gonew file mode 100644index 00000000..0c798cf4--- /dev/null+++ b/internal/strategy/activity.go@@ -0,0 +1,26 @@+package strategy++import (+ "net/http"++ "github.com/pinchtab/pinchtab/internal/activity"+ "github.com/pinchtab/pinchtab/internal/orchestrator"+)++func EnrichForTarget(r *http.Request, orch *orchestrator.Orchestrator, target string) {+ if r == nil || orch == nil || target == "" {+ return+ }++ for _, inst := range orch.List() {+ if inst.Status != "running" || inst.URL != target {+ continue+ }+ activity.EnrichRequest(r, activity.Update{+ InstanceID: inst.ID,+ ProfileID: inst.ProfileID,+ ProfileName: inst.ProfileName,+ })+ return+ }+}diff --git a/internal/strategy/autorestart/autorestart.go b/internal/strategy/autorestart/autorestart.goindex ecb8371a..8e113668 100644--- a/internal/strategy/autorestart/autorestart.go+++ b/internal/strategy/autorestart/autorestart.go@@ -438,6 +438,7 @@ func (s *Strategy) proxyToManaged(w http.ResponseWriter, r *http.Request) {web.Error(w, 503, err)return}+ strategy.EnrichForTarget(r, s.orch, target)proxy.HTTP(w, r, target+r.URL.Path)}diff --git a/internal/strategy/explicit/explicit.go b/internal/strategy/explicit/explicit.goindex 44b4d41c..b9fea879 100644--- a/internal/strategy/explicit/explicit.go+++ b/internal/strategy/explicit/explicit.go@@ -70,6 +70,7 @@ func (s *Strategy) proxyToFirst(w http.ResponseWriter, r *http.Request) {web.Error(w, 503, fmt.Errorf("no running instances — launch one from the Profiles tab"))return}+ strategy.EnrichForTarget(r, s.orch, target)proxy.HTTP(w, r, target+r.URL.Path)}diff --git a/internal/strategy/simple/simple.go b/internal/strategy/simple/simple.goindex f72574eb..d0ddc3fa 100644--- a/internal/strategy/simple/simple.go+++ b/internal/strategy/simple/simple.go@@ -78,6 +78,7 @@ func (s *Strategy) proxyToFirst(w http.ResponseWriter, r *http.Request) {web.Error(w, 503, err)return}+ strategy.EnrichForTarget(r, s.orch, target)proxy.HTTP(w, r, target+r.URL.Path)}diff --git a/scripts/check-dashboard.sh b/scripts/check-dashboard.shindex a8030866..a6c20546 100755--- a/scripts/check-dashboard.sh+++ b/scripts/check-dashboard.sh@@ -13,14 +13,37 @@ ERROR=$'\033[38;2;230;57;70m'MUTED=$'\033[38;2;90;100;128m'NC=$'\033[0m'-ok() { echo -e " ${SUCCESS}✓${NC} $1"; }-fail() { echo -e " ${ERROR}✗${NC} $1"; [ -n "${2:-}" ] && echo -e " ${MUTED}$2${NC}"; }+ok() { echo -e " ${SUCCESS}✓${NC} $1"; return 0; }+fail() {+ echo -e " ${ERROR}✗${NC} $1"+ if [ -n "${2:-}" ]; then+ echo -e " ${MUTED}$2${NC}"+ fi+ return 0+}section() {echo ""echo -e " ${ACCENT}${BOLD}$1${NC}"}+confirm() {+ if [ -r /dev/tty ]; then+ echo -n "$1 [y/N] " > /dev/tty+ read -r answer < /dev/tty+ [[ "$answer" =~ ^[Yy]$ ]]+ return+ fi++ if [ ! -t 0 ]; then+ return 1+ fi++ echo -n "$1 [y/N] "+ read -r answer+ [[ "$answer" =~ ^[Yy]$ ]]+}+if [ ! -d "dashboard" ]; thenfail "Dashboard directory not found"exit 1@@ -58,7 +81,18 @@ if [ -x "$TYGO" ] || command -v tygo &>/dev/null; thenok "Types in sync"elsefail "Types out of sync" "Run: cd dashboard && tygo generate && npx prettier --write src/generated/types.ts"- exit 1+ if confirm "Fix generated types now?"; then+ $TYGO_CMD generate+ npx prettier --write src/generated/types.ts+ if git diff --quiet -- src/generated/types.ts 2>/dev/null; then+ ok "Types fixed"+ else+ fail "Types still out of sync" "Review tygo output and rerun the check."+ exit 1+ fi+ else+ exit 1+ fififi@@ -84,7 +118,21 @@ if $RUN run format:check 2>&1; thenelsefail "Files not formatted"echo -e " ${MUTED}Run: cd dashboard && $RUN run format${NC}"- exit 1+ if confirm "Fix formatting now?"; then+ if $RUN run format 2>&1; then+ if $RUN run format:check 2>&1; then+ ok "Formatting fixed"+ else+ fail "Formatting still not clean"+ exit 1+ fi+ else+ fail "Formatting fix failed"+ exit 1+ fi+ else+ exit 1+ fifisection "Summary"diff --git a/scripts/doctor.sh b/scripts/doctor.shindex 9364d942..f5773aac 100755--- a/scripts/doctor.sh+++ b/scripts/doctor.sh@@ -219,6 +219,22 @@ if [ -d "dashboard" ]; thenfifi+ # ── gum ────────────────────────────────────────────────────────++ if command -v gum &>/dev/null; then+ ok "gum"+ else+ warn "gum not found" "Optional — used by ./dev for the interactive picker UI."+ if $HAS_BREW && confirm "Install gum via brew?"; then+ brew install gum && ok "gum installed" && WARNINGS=$((WARNINGS - 1))+ elif command -v go &>/dev/null && confirm "Install gum via go install?"; then+ go install github.com/charmbracelet/gum@latest && ok "gum installed" && WARNINGS=$((WARNINGS - 1))+ else+ hint "brew install gum"+ hint "go install github.com/charmbracelet/gum@latest"+ fi+ fi+# ── Dashboard deps ─────────────────────────────────────────────if [ -d "dashboard/node_modules" ]; thendiff --git a/tests/e2e/README.md b/tests/e2e/README.mdindex 150b4b37..720cad7f 100644--- a/tests/e2e/README.md+++ b/tests/e2e/README.md@@ -65,6 +65,7 @@ The Docker stack reuses the repository root `Dockerfile` and mounts explicit con| 04-tabs-api | Tab-scoped APIs (regression #207) || 05-actions | Click, type, press actions || 06-screenshot-pdf | Screenshot and PDF export |+| 40-activity | Activity API capture and filtering || scenarios-orchestrator/01-attach-bridge | Orchestrator attaches to the dedicated `pinchtab-bridge` container and proxies tab traffic || scenarios-orchestrator/31-multi-instance | Launch/list/stop and aggregate orchestration behavior |diff --git a/tests/e2e/scenarios-cli/36-activity.sh b/tests/e2e/scenarios-cli/36-activity.shnew file mode 100755index 00000000..7afdbb5c--- /dev/null+++ b/tests/e2e/scenarios-cli/36-activity.sh@@ -0,0 +1,54 @@+#!/bin/bash+# 36-activity.sh — CLI activity commands++source "$(dirname "$0")/common.sh"++# ─────────────────────────────────────────────────────────────────+start_test "pinchtab activity"++pt_ok nav "${FIXTURES_URL}/buttons.html"+TAB_ID=$(echo "$PT_OUT" | jq -r '.tabId')++pt_ok snap --tab "$TAB_ID"+assert_output_json "snapshot output is valid JSON"++pt_ok click --tab "$TAB_ID" "#increment"+assert_output_contains "clicked" "click command completed"++pt_ok activity --limit 100+assert_output_json "activity output is valid JSON"+assert_output_contains "\"events\"" "returns events payload"++if echo "$PT_OUT" | jq -e --arg tab "$TAB_ID" --arg path "/tabs/${TAB_ID}/action" '.events[] | select(.tabId == $tab and .path == $path)' > /dev/null; then+ echo -e " ${GREEN}✓${NC} activity output includes tab-scoped action event"+ ((ASSERTIONS_PASSED++)) || true+else+ echo -e " ${RED}✗${NC} activity output missing tab-scoped action event for ${TAB_ID}"+ ((ASSERTIONS_FAILED++)) || true+fi++end_test++# ─────────────────────────────────────────────────────────────────+start_test "pinchtab activity tab <id>"++pt_ok activity --limit 100 tab "$TAB_ID"+assert_output_json "tab activity output is valid JSON"++if echo "$PT_OUT" | jq -e --arg tab "$TAB_ID" 'all(.events[]?; .tabId == $tab)' > /dev/null; then+ echo -e " ${GREEN}✓${NC} tab activity output is scoped to selected tab"+ ((ASSERTIONS_PASSED++)) || true+else+ echo -e " ${RED}✗${NC} tab activity output includes other tabs"+ ((ASSERTIONS_FAILED++)) || true+fi++if echo "$PT_OUT" | jq -e --arg tab "$TAB_ID" '.events[] | select(.tabId == $tab and .path == "/snapshot")' > /dev/null; then+ echo -e " ${GREEN}✓${NC} tab activity output includes snapshot event"+ ((ASSERTIONS_PASSED++)) || true+else+ echo -e " ${RED}✗${NC} tab activity output missing snapshot event"+ ((ASSERTIONS_FAILED++)) || true+fi++end_testdiff --git a/tests/e2e/scenarios/40-activity.sh b/tests/e2e/scenarios/40-activity.shnew file mode 100755index 00000000..481bd45e--- /dev/null+++ b/tests/e2e/scenarios/40-activity.sh@@ -0,0 +1,38 @@+#!/bin/bash+# 40-activity.sh — Activity API E2E tests++source "$(dirname "$0")/common.sh"++# ─────────────────────────────────────────────────────────────────+start_test "GET /api/activity — records tab-scoped requests"++pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/buttons.html\"}"+TAB_ID=$(get_tab_id)++pt_get "/tabs/${TAB_ID}/snapshot"+assert_ok "tab snapshot succeeded"++pt_post "/tabs/${TAB_ID}/action" -d '{"kind":"click","selector":"#increment"}'+assert_http_status "200" "click action succeeded"++pt_get "/api/activity?tabId=${TAB_ID}&limit=100&ageSec=300"+assert_ok "activity query"+assert_json_exists "$RESULT" '.events' "events array present"++if echo "$RESULT" | jq -e --arg tab "$TAB_ID" --arg path "/tabs/${TAB_ID}/snapshot" '.events[] | select(.tabId == $tab and .path == $path)' > /dev/null; then+ echo -e " ${GREEN}✓${NC} tab snapshot event recorded"+ ((ASSERTIONS_PASSED++)) || true+else+ echo -e " ${RED}✗${NC} missing tab snapshot event for tab ${TAB_ID}"+ ((ASSERTIONS_FAILED++)) || true+fi++if echo "$RESULT" | jq -e --arg tab "$TAB_ID" --arg path "/tabs/${TAB_ID}/action" '.events[] | select(.tabId == $tab and .path == $path)' > /dev/null; then+ echo -e " ${GREEN}✓${NC} tab action event recorded"+ ((ASSERTIONS_PASSED++)) || true+else+ echo -e " ${RED}✗${NC} missing tab action event for tab ${TAB_ID}"+ ((ASSERTIONS_FAILED++)) || true+fi++end_test