High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat(activity): unify live agent activity across dashboard and bridges
Luigi Agostic7cdf96fb9f4
diff --git a/.github/workflows/reusable-go.yml b/.github/workflows/reusable-go.ymlindex 3d529193..06233dd0 100644--- a/.github/workflows/reusable-go.yml+++ b/.github/workflows/reusable-go.yml@@ -29,7 +29,9 @@ jobs:- name: Format checkrun: |- mapfile -t go_files < <(git ls-files -- '*.go')+ mapfile -t go_files < <(git ls-files -- '*.go' | while read -r file; do+ [ -f "$file" ] && printf '%s\n' "$file"+ done)unformatted=""if [ ${#go_files[@]} -gt 0 ]; thenunformatted=$(gofmt -l "${go_files[@]}")diff --git a/cmd/pinchtab/cmd_cli_runtime.go b/cmd/pinchtab/cmd_cli_runtime.goindex f9263cf3..a47fbde7 100644--- a/cmd/pinchtab/cmd_cli_runtime.go+++ b/cmd/pinchtab/cmd_cli_runtime.go@@ -7,6 +7,7 @@ import ("strings""time"+ "github.com/pinchtab/pinchtab/internal/activity""github.com/pinchtab/pinchtab/internal/config""github.com/spf13/cobra")@@ -23,12 +24,23 @@ func runCLI(fn func(cliRuntime)) {func runCLIWith(cfg *config.RuntimeConfig, fn func(cliRuntime)) {fn(cliRuntime{- client: &http.Client{Timeout: 60 * time.Second},+ client: newCLIHTTPClient(resolveCLIAgentID()),base: resolveCLIBase(cfg),token: resolveCLIToken(cfg),})}+func newCLIHTTPClient(agentID string) *http.Client {+ baseTransport := http.DefaultTransport+ return &http.Client{+ Timeout: 60 * time.Second,+ Transport: agentHeaderTransport{+ base: baseTransport,+ agentID: normalizeCLIAgentID(agentID),+ },+ }+}+func resolveCLIBase(cfg *config.RuntimeConfig) string {if serverURL != "" {return strings.TrimRight(serverURL, "/")@@ -52,6 +64,41 @@ func resolveCLIToken(cfg *config.RuntimeConfig) string {return token}+func resolveCLIAgentID() string {+ if trimmed := strings.TrimSpace(cliAgentID); trimmed != "" {+ return trimmed+ }+ if trimmed := strings.TrimSpace(os.Getenv("PINCHTAB_AGENT_ID")); trimmed != "" {+ return trimmed+ }+ return "cli"+}++func normalizeCLIAgentID(raw string) string {+ if trimmed := strings.TrimSpace(raw); trimmed != "" {+ return trimmed+ }+ return "cli"+}++type agentHeaderTransport struct {+ base http.RoundTripper+ agentID string+}++func (t agentHeaderTransport) RoundTrip(req *http.Request) (*http.Response, error) {+ base := t.base+ if base == nil {+ base = http.DefaultTransport+ }++ cloned := req.Clone(req.Context())+ cloned.Header = req.Header.Clone()+ cloned.Header.Set(activity.HeaderAgentID, normalizeCLIAgentID(t.agentID))++ return base.RoundTrip(cloned)+}+func optionalArg(args []string) string {if len(args) == 0 {return ""diff --git a/cmd/pinchtab/cmd_cli_runtime_test.go b/cmd/pinchtab/cmd_cli_runtime_test.goindex 5196cc9a..609b950f 100644--- a/cmd/pinchtab/cmd_cli_runtime_test.go+++ b/cmd/pinchtab/cmd_cli_runtime_test.go@@ -1,6 +1,8 @@package mainimport (+ "io"+ "net/http""testing""github.com/pinchtab/pinchtab/internal/config"@@ -62,3 +64,105 @@ func TestResolveCLIBase(t *testing.T) {})}}++func TestResolveCLIAgentID(t *testing.T) {+ tests := []struct {+ name string+ flagValue string+ envValue string+ expected string+ }{+ {+ name: "--agent-id overrides environment",+ flagValue: "agent-flag",+ envValue: "agent-env",+ expected: "agent-flag",+ },+ {+ name: "--agent-id trims whitespace",+ flagValue: " agent-flag ",+ expected: "agent-flag",+ },+ {+ name: "blank --agent-id falls through to environment",+ flagValue: " ",+ envValue: "agent-env",+ expected: "agent-env",+ },+ {+ name: "PINCHTAB_AGENT_ID overrides default",+ envValue: "agent-env",+ expected: "agent-env",+ },+ {+ name: "PINCHTAB_AGENT_ID trims whitespace",+ envValue: " agent-env ",+ expected: "agent-env",+ },+ {+ name: "blank values fall back to cli",+ flagValue: " ",+ envValue: " ",+ expected: "cli",+ },+ {+ name: "default fallback is cli",+ expected: "cli",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ oldAgentID := cliAgentID+ cliAgentID = tt.flagValue+ defer func() { cliAgentID = oldAgentID }()++ t.Setenv("PINCHTAB_AGENT_ID", tt.envValue)++ if got := resolveCLIAgentID(); got != tt.expected {+ t.Fatalf("resolveCLIAgentID() = %q, want %q", got, tt.expected)+ }+ })+ }+}++func TestRunCLIWithInjectsAgentIDHeaders(t *testing.T) {+ const wantAgentID = "agent-main"++ var gotRequest *http.Request+ client := &http.Client{+ Transport: agentHeaderTransport{+ base: roundTripFunc(func(req *http.Request) (*http.Response, error) {+ gotRequest = req+ return &http.Response{+ StatusCode: http.StatusOK,+ Header: make(http.Header),+ Body: io.NopCloser(http.NoBody),+ Request: req,+ }, nil+ }),+ agentID: wantAgentID,+ },+ }++ req, err := http.NewRequest(http.MethodGet, "http://example.test/health", nil)+ if err != nil {+ t.Fatalf("NewRequest() error = %v", err)+ }+ if _, err := client.Do(req); err != nil {+ t.Fatalf("client.Do() error = %v", err)+ }++ if gotRequest == nil {+ t.Fatal("transport did not receive request")+ }+ if got := gotRequest.Header.Get("X-Agent-Id"); got != wantAgentID {+ t.Fatalf("X-Agent-Id = %q, want %q", got, wantAgentID)+ }+}++type roundTripFunc func(*http.Request) (*http.Response, error)++func (fn roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {+ return fn(req)+}diff --git a/cmd/pinchtab/root.go b/cmd/pinchtab/root.goindex c6a94f4a..61342609 100644--- a/cmd/pinchtab/root.go+++ b/cmd/pinchtab/root.go@@ -105,6 +105,7 @@ func Execute() {// serverURL is the global --server flag for CLI commandsvar serverURL string+var cliAgentID stringfunc init() {rootCmd.Version = version@@ -112,6 +113,7 @@ func init() {// Global flagsrootCmd.PersistentFlags().StringVar(&serverURL, "server", "", "PinchTab server URL (default: http://127.0.0.1:<instancePortStart>)")+ rootCmd.PersistentFlags().StringVar(&cliAgentID, "agent-id", "", "Agent identifier recorded in activity logs")// Grouping commandsprimaryGroup := &cobra.Group{ID: "primary", Title: "Primary Commands"}diff --git a/dashboard/src/App.tsx b/dashboard/src/App.tsxindex 4a751ffe..80893682 100644--- a/dashboard/src/App.tsx+++ b/dashboard/src/App.tsx@@ -12,25 +12,22 @@ import { NavBar } from "./components/molecules";import { LoginPage, MonitoringPage, ProfilesPage, SettingsPage } from "./pages";import * as api from "./services/api";import { AUTH_REQUIRED_EVENT, AUTH_STATE_CHANGED_EVENT } from "./services/auth";+import { acquireDashboardRealtime } from "./services/dashboardRealtime";import { useAppStore } from "./stores/useAppStore";type AuthMode = "probing" | "required" | "open" | "unreachable";const AUTH_RETRY_DELAYS_MS = [1000, 2000, 4000, 8000, 15000] as const;function AppContent() {- const {- setInstances,- setProfiles,- setAgents,- upsertAgentFromEvent,- addEvent,- setServerInfo,- applyMonitoringSnapshot,- settings,- } = useAppStore();+ const setInstances = useAppStore((state) => state.setInstances);+ const setProfiles = useAppStore((state) => state.setProfiles);+ const setAgents = useAppStore((state) => state.setAgents);+ const setServerInfo = useAppStore((state) => state.setServerInfo);+ const memoryMetricsEnabled = useAppStore(+ (state) => state.settings.monitoring?.memoryMetrics ?? false,+ );const location = useLocation();const navigate = useNavigate();- const memoryMetricsEnabled = settings.monitoring?.memoryMetrics ?? false;const [authMode, setAuthMode] = useState<AuthMode>("probing");const [authProtected, setAuthProtected] = useState(false);const [authRetryCount, setAuthRetryCount] = useState(0);@@ -169,38 +166,8 @@ function AppContent() {if (!dashboardAccessible) {return;}- const unsubscribe = api.subscribeToEvents(- {- onInit: (agents) => {- setAgents(agents);- },- onSystem: (event) => {- console.log("System event:", event);- },- onActivity: (event) => {- upsertAgentFromEvent(event);- addEvent(event);- },- onMonitoring: (snapshot) => {- applyMonitoringSnapshot(snapshot, memoryMetricsEnabled);- },- },- {- includeMemory: memoryMetricsEnabled,- reasoningMode: settings.agents?.reasoningMode ?? "tool_calls",- },- );-- return unsubscribe;- }, [- dashboardAccessible,- addEvent,- applyMonitoringSnapshot,- memoryMetricsEnabled,- settings.agents?.reasoningMode,- setAgents,- upsertAgentFromEvent,- ]);+ return acquireDashboardRealtime(memoryMetricsEnabled);+ }, [dashboardAccessible, memoryMetricsEnabled]);if (authMode === "probing") {return (diff --git a/dashboard/src/activities/ActiveFilterBar.tsx b/dashboard/src/activities/ActiveFilterBar.tsxnew file mode 100644index 00000000..b0ae845c--- /dev/null+++ b/dashboard/src/activities/ActiveFilterBar.tsx@@ -0,0 +1,47 @@+import type { ActivityFilters } from "./types";++interface ActiveFilterBarProps {+ filters: ActivityFilters;+ hideAgentFilter?: boolean;+ onClear: () => void;+}++export default function ActiveFilterBar({+ filters,+ hideAgentFilter = false,+ onClear,+}: ActiveFilterBarProps) {+ const activeFilters = [+ !hideAgentFilter && filters.agentId ? `agent:${filters.agentId}` : "",+ filters.profileName ? `profile:${filters.profileName}` : "",+ filters.instanceId ? `instance:${filters.instanceId}` : "",+ filters.tabId ? `tab:${filters.tabId}` : "",+ filters.action ? `action:${filters.action}` : "",+ filters.sessionId ? `session:${filters.sessionId}` : "",+ filters.pathPrefix ? `path:${filters.pathPrefix}` : "",+ ].filter(Boolean);++ if (activeFilters.length === 0) {+ return null;+ }++ return (+ <div className="flex flex-wrap items-center gap-2 border-b border-border-subtle px-4 py-2">+ {activeFilters.map((filter) => (+ <span+ key={filter}+ className="dashboard-mono rounded-sm border border-primary/20 bg-primary/10 px-2 py-1 text-[0.68rem] text-text-secondary"+ >+ {filter}+ </span>+ ))}+ <button+ type="button"+ className="ml-auto text-[0.68rem] font-semibold uppercase tracking-[0.12em] text-text-muted transition-colors hover:text-text-primary"+ onClick={onClear}+ >+ Clear filters+ </button>+ </div>+ );+}diff --git a/dashboard/src/activities/ActivityFilterMenu.tsx b/dashboard/src/activities/ActivityFilterMenu.tsxindex 3c3a7011..a8d47c48 100644--- a/dashboard/src/activities/ActivityFilterMenu.tsx+++ b/dashboard/src/activities/ActivityFilterMenu.tsx@@ -2,7 +2,7 @@ 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";+import { actionOptions } from "./helpers";interface Props {filters: ActivityFilters;@@ -10,6 +10,7 @@ interface Props {instanceOptions: Instance[];tabOptions: InstanceTab[];loading: boolean;+ showAgentFilter?: boolean;onClear: () => void;onRefresh: () => void;onFilterChange: (key: keyof ActivityFilters, value: string) => void;@@ -53,6 +54,7 @@ export default function ActivityFilterMenu({instanceOptions,tabOptions,loading,+ showAgentFilter = true,onClear,onRefresh,onFilterChange,@@ -92,12 +94,16 @@ export default function ActivityFilterMenu({</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)}- />+ {showAgentFilter && (+ <Input+ label="Agent"+ placeholder="cli, mcp, custom"+ value={filters.agentId}+ onChange={(event) =>+ onFilterChange("agentId", event.target.value)+ }+ />+ )}<FilterSelectlabel="Action"value={filters.action}@@ -149,19 +155,6 @@ export default function ActivityFilterMenu({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)- }- /><Inputlabel="Path prefix"placeholder="/tabs/ or /instances/"diff --git a/dashboard/src/activities/ActivityPage.test.tsx b/dashboard/src/activities/ActivityPage.test.tsxindex 7402ac28..fd4899ea 100644--- a/dashboard/src/activities/ActivityPage.test.tsx+++ b/dashboard/src/activities/ActivityPage.test.tsx@@ -19,7 +19,18 @@ import { fetchAllTabs } from "../services/api";describe("ActivityPage", () => {beforeEach(() => {vi.clearAllMocks();+ const now = new Date().toISOString();useAppStore.setState({+ agents: [+ {+ id: "cli",+ name: "CLI",+ connectedAt: "2026-03-16T08:00:00Z",+ lastActivity: "2026-03-16T08:10:00Z",+ requestCount: 3,+ },+ ],+ agentEventsById: {},profiles: [{id: "prof_default",@@ -65,10 +76,12 @@ describe("ActivityPage", () => {count: 1,events: [{- timestamp: "2026-03-16T09:00:00Z",+ timestamp: now,source: "cli",requestId: "req_123",agentId: "cli",+ instanceId: "inst_123",+ profileName: "default",method: "POST",path: "/tabs/tab_123/action",status: 200,@@ -201,6 +214,5 @@ describe("ActivityPage", () => {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.tsxindex 266c6b6c..dd083870 100644--- a/dashboard/src/activities/ActivityPage.tsx+++ b/dashboard/src/activities/ActivityPage.tsx@@ -126,7 +126,7 @@ export default function ActivityPage() {<AgentActivityWorkspaceinitialFilters={initialFilters}defaultSidebarTab="activities"- hiddenSources={["dashboard"]}+ preferKnownAgents/>);}diff --git a/dashboard/src/activities/AgentActivityWorkspace.tsx b/dashboard/src/activities/AgentActivityWorkspace.tsxindex 5dc60156..4d8ca819 100644--- a/dashboard/src/activities/AgentActivityWorkspace.tsx+++ b/dashboard/src/activities/AgentActivityWorkspace.tsx@@ -1,7 +1,7 @@-import { useDeferredValue, useEffect, useMemo, useRef, useState } from "react";+import { useDeferredValue, useEffect, useMemo, useState } from "react";import { useAppStore } from "../stores/useAppStore";import * as api from "../services/api";-import type { Agent, InstanceTab } from "../types";+import type { ActivityEvent, Agent, InstanceTab } from "../types";import { fetchActivity } from "./api";import AgentStreamPanel from "./AgentStreamPanel";import AgentWorkspaceSidebar from "./AgentWorkspaceSidebar";@@ -18,47 +18,165 @@ interface Props {initialFilters?: Partial<ActivityFilters>;defaultSidebarTab?: WorkspaceTab;hiddenSources?: string[];+ requireAgentIdentity?: boolean;+ requireSelectedAgent?: boolean;+ showAllAgentsOption?: boolean;+ showAgentFilter?: boolean;+ simplifyEventRows?: boolean;+ copyTabId?: boolean;+ preferKnownAgents?: boolean;+ useAgentEventStore?: boolean;+ clearToInitialFilters?: boolean;+}++function detailString(+ details: Record<string, unknown> | undefined,+ key: string,+): string {+ const value = details?.[key];+ return typeof value === "string" ? value : "";+}++function detailNumber(+ details: Record<string, unknown> | undefined,+ key: string,+): number {+ const value = details?.[key];+ return typeof value === "number" ? value : 0;+}++function toDashboardActivityEvent(+ event: ActivityEvent,+): DashboardActivityEvent {+ const details = (event.details ?? {}) as Record<string, unknown>;+ return {+ channel: event.channel,+ message: event.message,+ progress: event.progress,+ total: event.total,+ timestamp: event.timestamp,+ source: detailString(details, "source"),+ requestId: detailString(details, "requestId") || event.id,+ sessionId: detailString(details, "sessionId"),+ actorId: detailString(details, "actorId"),+ agentId: event.agentId || "",+ method: event.method,+ path: event.path,+ status: detailNumber(details, "status"),+ durationMs: detailNumber(details, "durationMs"),+ instanceId: detailString(details, "instanceId"),+ profileId: detailString(details, "profileId"),+ profileName: detailString(details, "profileName"),+ tabId: detailString(details, "tabId"),+ url: detailString(details, "url"),+ action: detailString(details, "action"),+ engine: detailString(details, "engine"),+ ref: detailString(details, "ref"),+ };+}++function matchesVisibleEvent(+ event: DashboardActivityEvent,+ filters: ActivityFilters,+ hiddenSources: string[],+ requireAgentIdentity: boolean,+): boolean {+ if (hiddenSources.includes(event.source)) {+ return false;+ }+ if (requireAgentIdentity && !(event.agentId || "").trim()) {+ return false;+ }+ if (filters.agentId && event.agentId !== filters.agentId) {+ return false;+ }+ if (filters.tabId && event.tabId !== filters.tabId) {+ return false;+ }+ if (filters.instanceId && event.instanceId !== filters.instanceId) {+ return false;+ }+ if (filters.profileName && event.profileName !== filters.profileName) {+ return false;+ }+ if (filters.sessionId && event.sessionId !== filters.sessionId) {+ return false;+ }+ if (filters.action && event.action !== filters.action) {+ return false;+ }+ if (filters.pathPrefix && !event.path.startsWith(filters.pathPrefix)) {+ return false;+ }+ if (filters.ageSec) {+ const ageSec = Number(filters.ageSec);+ if (Number.isFinite(ageSec) && ageSec >= 0) {+ const cutoff = Date.now() - ageSec * 1000;+ if (new Date(event.timestamp).getTime() < cutoff) {+ return false;+ }+ }+ }+ return true;}export default function AgentActivityWorkspace({initialFilters,defaultSidebarTab = "agents",hiddenSources = [],+ requireAgentIdentity = false,+ requireSelectedAgent = false,+ showAllAgentsOption = true,+ showAgentFilter = true,+ simplifyEventRows = false,+ copyTabId = false,+ preferKnownAgents = false,+ useAgentEventStore = false,+ clearToInitialFilters = false,}: Props) {- const { instances, profiles } = useAppStore();+ const { instances, profiles, agents, agentEventsById, hydrateAgentEvents } =+ useAppStore();+ const normalizedHiddenSources = useMemo(+ () => [...hiddenSources],+ [hiddenSources],+ );+ const initialBaseFilters = useMemo(+ () => ({+ ...defaultActivityFilters,+ ...initialFilters,+ }),+ [initialFilters],+ );+const [sidebarTab, setSidebarTab] = useState<WorkspaceTab>(defaultSidebarTab);- const [filters, setFilters] = useState<ActivityFilters>({- ...defaultActivityFilters,- ...initialFilters,- });- const [events, setEvents] = useState<DashboardActivityEvent[]>([]);+ const [filters, setFilters] = useState<ActivityFilters>(initialBaseFilters);+ const [activityEvents, setActivityEvents] = useState<+ DashboardActivityEvent[]+ >([]);const [tabs, setTabs] = useState<InstanceTab[]>([]);- const [loading, setLoading] = useState(true);+ const [activityLoading, setActivityLoading] = useState(false);+ const [agentLoading, setAgentLoading] = useState(false);const [error, setError] = useState("");const [refreshNonce, setRefreshNonce] = useState(0);const deferredFilters = useDeferredValue(filters);- const query = useMemo(+ const activityQuery = useMemo(() => buildActivityQuery(deferredFilters),[deferredFilters],);- const queryKey = JSON.stringify(query);- const stableQuery = useRef(query);- stableQuery.current = query;+ const activityQueryKey = JSON.stringify(activityQuery);+ const usesAgentThreadView = useAgentEventStore && sidebarTab === "agents";useEffect(() => {setSidebarTab(defaultSidebarTab);}, [defaultSidebarTab]);useEffect(() => {- const next = {- ...defaultActivityFilters,- ...initialFilters,- };+ const next = initialBaseFilters;setFilters((current) =>sameActivityFilters(current, next) ? current : next,);- }, [initialFilters]);+ }, [initialBaseFilters]);useEffect(() => {let cancelled = false;@@ -80,30 +198,76 @@ export default function AgentActivityWorkspace({}, []);useEffect(() => {+ if (usesAgentThreadView) {+ setActivityLoading(false);+ return;+ }+let cancelled = false;const load = async () => {- setLoading(true);+ setActivityLoading(true);setError("");try {- const response = await fetchActivity(stableQuery.current);- if (cancelled) return;- setEvents(response.events);+ const response = await fetchActivity(activityQuery);+ if (cancelled) {+ return;+ }+ setActivityEvents(response.events);} catch (err) {- if (cancelled) return;+ if (cancelled) {+ return;+ }setError(err instanceof Error ? err.message : "Failed to load activity",);} finally {if (!cancelled) {- setLoading(false);+ setActivityLoading(false);}}};+void load();return () => {cancelled = true;};- }, [queryKey, refreshNonce]);+ }, [activityQuery, activityQueryKey, refreshNonce, usesAgentThreadView]);++ useEffect(() => {+ if (!usesAgentThreadView || !filters.agentId) {+ setAgentLoading(false);+ return;+ }++ let cancelled = false;+ const load = async () => {+ setAgentLoading(true);+ setError("");+ try {+ const response = await api.fetchAgent(filters.agentId, "both");+ if (cancelled) {+ return;+ }+ hydrateAgentEvents(filters.agentId, response.events);+ } catch (err) {+ if (cancelled) {+ return;+ }+ setError(+ err instanceof Error ? err.message : "Failed to load agent activity",+ );+ } finally {+ if (!cancelled) {+ setAgentLoading(false);+ }+ }+ };++ void load();+ return () => {+ cancelled = true;+ };+ }, [filters.agentId, hydrateAgentEvents, refreshNonce, usesAgentThreadView]);const filteredInstances = useMemo(() =>@@ -124,14 +288,51 @@ export default function AgentActivityWorkspace({);const visibleEvents = useMemo(- () => events.filter((event) => !hiddenSources.includes(event.source)),- [events, hiddenSources],+ () =>+ activityEvents.filter((event) =>+ matchesVisibleEvent(+ event,+ filters,+ normalizedHiddenSources,+ requireAgentIdentity,+ ),+ ),+ [activityEvents, filters, normalizedHiddenSources, requireAgentIdentity],);- const visibleAgents = useMemo<Agent[]>(() => {+ const agentThreadEvents = useMemo(() => {+ if (!filters.agentId) {+ return [] as DashboardActivityEvent[];+ }++ return (agentEventsById[filters.agentId] ?? [])+ .map(toDashboardActivityEvent)+ .filter((event) =>+ matchesVisibleEvent(+ event,+ {+ ...filters,+ agentId: "",+ },+ normalizedHiddenSources,+ requireAgentIdentity,+ ),+ );+ }, [agentEventsById, filters, normalizedHiddenSources, requireAgentIdentity]);++ const displayedEvents = usesAgentThreadView+ ? agentThreadEvents+ : visibleEvents;++ const derivedAgents = useMemo<Agent[]>(() => {const byId = new Map<string, Agent>();+for (const event of visibleEvents) {- const agentId = event.agentId?.trim() || "anonymous";+ const agentId = event.agentId?.trim();+ if (!agentId) {+ continue;+ }+const existing = byId.get(agentId);if (!existing) {byId.set(agentId, {@@ -143,6 +344,7 @@ export default function AgentActivityWorkspace({});continue;}+existing.requestCount += 1;if (new Date(event.timestamp).getTime() >@@ -159,18 +361,54 @@ export default function AgentActivityWorkspace({);}, [visibleEvents]);+ const visibleAgents = useMemo<Agent[]>(() => {+ if (!preferKnownAgents) {+ return derivedAgents;+ }++ return [...agents]+ .filter((agent) => {+ if (requireAgentIdentity && !(agent.id || "").trim()) {+ return false;+ }+ if (requireAgentIdentity && agent.id === "anonymous") {+ return false;+ }+ return true;+ })+ .sort(+ (left, right) =>+ new Date(right.lastActivity || right.connectedAt).getTime() -+ new Date(left.lastActivity || left.connectedAt).getTime(),+ );+ }, [agents, derivedAgents, preferKnownAgents, requireAgentIdentity]);+const summary = useMemo(() => {const agentsSeen = new Set(- visibleEvents.map((event) => event.agentId).filter(Boolean),+ displayedEvents.map((event) => event.agentId).filter(Boolean),);const tabsSeen = new Set(- visibleEvents.map((event) => event.tabId).filter(Boolean),+ displayedEvents.map((event) => event.tabId).filter(Boolean),);const instancesSeen = new Set(- visibleEvents.map((event) => event.instanceId).filter(Boolean),+ displayedEvents.map((event) => event.instanceId).filter(Boolean),);- return `${visibleEvents.length} events • ${agentsSeen.size} agents • ${tabsSeen.size} tabs • ${instancesSeen.size} instances`;- }, [visibleEvents]);++ return `${displayedEvents.length} events • ${agentsSeen.size} agents • ${tabsSeen.size} tabs • ${instancesSeen.size} instances`;+ }, [displayedEvents]);++ useEffect(() => {+ if (!requireSelectedAgent || visibleAgents.length === 0) {+ return;+ }+ if (visibleAgents.some((agent) => agent.id === filters.agentId)) {+ return;+ }+ setFilters((current) => ({+ ...current,+ agentId: visibleAgents[0].id,+ }));+ }, [filters.agentId, requireSelectedAgent, visibleAgents]);const updateFilter = (key: keyof ActivityFilters, value: string) => {setFilters((current) => ({ ...current, [key]: value }));@@ -201,17 +439,32 @@ export default function AgentActivityWorkspace({};const clearFilters = () => {- setFilters({ ...defaultActivityFilters });+ const resetBaseFilters = clearToInitialFilters+ ? initialBaseFilters+ : defaultActivityFilters;+ setFilters((current) => ({+ ...resetBaseFilters,+ agentId:+ requireSelectedAgent && current.agentId+ ? current.agentId+ : resetBaseFilters.agentId,+ }));};+ const sidebarLoading =+ sidebarTab === "activities" ? activityLoading : agentLoading;+return (<div className="flex h-full min-h-0 flex-col overflow-hidden xl:flex-row"><AgentStreamPanelfilters={filters}- events={visibleEvents}+ events={displayedEvents}summary={summary}error={error}- loading={loading}+ loading={usesAgentThreadView ? agentLoading : activityLoading}+ copyTabId={copyTabId}+ hideAgentFilter={requireSelectedAgent}+ simplifyMeta={simplifyEventRows}onClearFilters={clearFilters}onFilterChange={updateFilter}/>@@ -221,13 +474,14 @@ export default function AgentActivityWorkspace({visibleAgents={visibleAgents}activeAgentId={filters.agentId}filters={filters}+ showAllAgentsOption={showAllAgentsOption}+ showAgentFilter={showAgentFilter}profiles={profiles}filteredInstances={filteredInstances}visibleTabs={visibleTabs}- loading={loading}+ loading={sidebarLoading}onSidebarTabChange={setSidebarTab}onSelectAgent={(agentId) => updateFilter("agentId", agentId)}- onClearAgentSelection={() => updateFilter("agentId", "")}onClearFilters={clearFilters}onRefresh={() => setRefreshNonce((current) => current + 1)}onFilterChange={updateFilter}diff --git a/dashboard/src/activities/AgentStreamPanel.tsx b/dashboard/src/activities/AgentStreamPanel.tsxindex d1148243..8d342718 100644--- a/dashboard/src/activities/AgentStreamPanel.tsx+++ b/dashboard/src/activities/AgentStreamPanel.tsx@@ -1,170 +1,18 @@+import { useLayoutEffect, useRef } from "react";import { EmptyState } from "../components/atoms";-import { Badge } from "../components/atoms";-import { activityMethodVariant, activityStatusVariant } from "./helpers";+import ActiveFilterBar from "./ActiveFilterBar";+import StreamRow from "./StreamRow";import type { ActivityFilters, DashboardActivityEvent } from "./types";-function formatTime(ts: string): string {- return new Date(ts).toLocaleTimeString("en-GB", {- hour: "2-digit",- minute: "2-digit",- second: "2-digit",- });-}--function eventIcon(event: DashboardActivityEvent): string {- if (event.action === "click" || event.action === "dblclick") return "👆";- if (event.action === "type") return "⌨️";- if (event.action === "hover") return "🖱️";- if (event.path.includes("/navigate")) return "🧭";- if (event.path.includes("/snapshot")) return "📸";- if (event.path.includes("/screencast")) return "🖥️";- return "📝";-}--function FilterPill({- label,- onClick,-}: {- label: string;- onClick: () => void;-}) {- 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"- onClick={onClick}- title={label}- >- <span className="block truncate">{label}</span>- </button>- );-}--function ActiveFilterBar({- filters,- onClear,-}: {- filters: ActivityFilters;- onClear: () => void;-}) {- const activeFilters = [- filters.agentId ? `agent:${filters.agentId}` : "",- filters.profileName ? `profile:${filters.profileName}` : "",- filters.instanceId ? `instance:${filters.instanceId}` : "",- filters.tabId ? `tab:${filters.tabId}` : "",- filters.action ? `action:${filters.action}` : "",- filters.source ? `source:${filters.source}` : "",- filters.sessionId ? `session:${filters.sessionId}` : "",- filters.pathPrefix ? `path:${filters.pathPrefix}` : "",- ].filter(Boolean);-- if (activeFilters.length === 0) {- return null;- }-- return (- <div className="flex flex-wrap items-center gap-2 border-b border-border-subtle px-4 py-2">- {activeFilters.map((filter) => (- <span- key={filter}- className="dashboard-mono rounded-sm border border-primary/20 bg-primary/10 px-2 py-1 text-[0.68rem] text-text-secondary"- >- {filter}- </span>- ))}- <button- type="button"- className="ml-auto text-[0.68rem] font-semibold uppercase tracking-[0.12em] text-text-muted transition-colors hover:text-text-primary"- onClick={onClear}- >- Clear filters- </button>- </div>- );-}--function StreamRow({- event,- onFilterChange,-}: {- event: DashboardActivityEvent;- onFilterChange: (key: keyof ActivityFilters, value: string) => void;-}) {- return (- <div className="border-b border-border-subtle/70 px-4 py-3 text-sm transition-colors hover:bg-white/2">- <div className="flex items-start gap-3">- <span className="pt-0.5 text-lg">{eventIcon(event)}</span>- <span className="dashboard-mono w-18 shrink-0 pt-0.5 text-xs text-text-muted">- {formatTime(event.timestamp)}- </span>- <div className="min-w-0 flex-1">- <div className="flex flex-wrap items-center gap-2">- <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>}- <span className="dashboard-mono min-w-0 flex-1 truncate text-text-secondary">- {event.path}- </span>- </div>-- <div className="mt-1 flex flex-wrap items-center gap-1.5">- {event.tabId && (- <FilterPill- label={`tab:${event.tabId}`}- onClick={() => onFilterChange("tabId", event.tabId || "")}- />- )}- {event.profileName && (- <FilterPill- label={`profile:${event.profileName}`}- onClick={() =>- onFilterChange("profileName", event.profileName || "")- }- />- )}- {event.instanceId && (- <FilterPill- label={`instance:${event.instanceId}`}- onClick={() =>- onFilterChange("instanceId", event.instanceId || "")- }- />- )}- {event.url && (- <span className="dashboard-mono min-w-0 truncate text-[0.68rem] text-text-muted">- {event.url}- </span>- )}- </div>- </div>-- <div className="flex shrink-0 flex-col items-end gap-1.5">- <span className="dashboard-mono text-xs text-text-muted">- {event.durationMs}ms- </span>- {event.agentId && (- <FilterPill- label={`agent:${event.agentId}`}- onClick={() => onFilterChange("agentId", event.agentId || "")}- />- )}- </div>- </div>- </div>- );-}-interface AgentStreamPanelProps {filters: ActivityFilters;events: DashboardActivityEvent[];summary: string;error: string;loading: boolean;+ copyTabId?: boolean;+ hideAgentFilter?: boolean;+ simplifyMeta?: boolean;onClearFilters: () => void;onFilterChange: (key: keyof ActivityFilters, value: string) => void;}@@ -175,9 +23,49 @@ export default function AgentStreamPanel({summary,error,loading,+ copyTabId = false,+ hideAgentFilter = false,+ simplifyMeta = false,onClearFilters,onFilterChange,}: AgentStreamPanelProps) {+ const scrollContainerRef = useRef<HTMLDivElement | null>(null);+ const shouldStickToBottomRef = useRef(true);+ const previousEventCountRef = useRef(0);++ useLayoutEffect(() => {+ if (!simplifyMeta) {+ previousEventCountRef.current = events.length;+ return;+ }++ const container = scrollContainerRef.current;+ if (!container) {+ previousEventCountRef.current = events.length;+ return;+ }++ const eventCountChanged = events.length !== previousEventCountRef.current;+ previousEventCountRef.current = events.length;++ if (eventCountChanged && shouldStickToBottomRef.current) {+ container.scrollTop = container.scrollHeight;+ }+ }, [events, simplifyMeta]);++ const handleScroll = () => {+ if (!simplifyMeta) {+ return;+ }+ const container = scrollContainerRef.current;+ if (!container) {+ return;+ }+ const distanceFromBottom =+ container.scrollHeight - container.scrollTop - container.clientHeight;+ shouldStickToBottomRef.current = distanceFromBottom <= 48;+ };+return (<section className="flex min-h-0 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">@@ -187,7 +75,11 @@ export default function AgentStreamPanel({</div></div>- <ActiveFilterBar filters={filters} onClear={onClearFilters} />+ <ActiveFilterBar+ filters={filters}+ hideAgentFilter={hideAgentFilter}+ onClear={onClearFilters}+ />{error && (<div className="border-b border-destructive/30 bg-destructive/10 px-4 py-2 text-xs text-destructive">@@ -195,7 +87,11 @@ export default function AgentStreamPanel({</div>)}- <div className="min-h-0 flex-1 overflow-auto">+ <div+ ref={scrollContainerRef}+ className="min-h-0 flex-1 overflow-auto"+ onScroll={handleScroll}+ >{!loading && events.length === 0 ? (<EmptyStateicon="📡"@@ -203,11 +99,18 @@ export default function AgentStreamPanel({description="Adjust the filters or generate some traffic from the CLI, MCP, or dashboard."/>) : (- <div>+ <div+ className={+ simplifyMeta ? "flex min-h-full flex-col justify-end py-2" : ""+ }+ >{events.map((event, index) => (<StreamRowkey={`${event.requestId || event.timestamp}-${index}`}event={event}+ copyTabId={copyTabId}+ hideAgentFilter={hideAgentFilter}+ simplifyMeta={simplifyMeta}onFilterChange={onFilterChange}/>))}diff --git a/dashboard/src/activities/AgentWorkspaceSidebar.tsx b/dashboard/src/activities/AgentWorkspaceSidebar.tsxindex 7f4e55b0..e604c76e 100644--- a/dashboard/src/activities/AgentWorkspaceSidebar.tsx+++ b/dashboard/src/activities/AgentWorkspaceSidebar.tsx@@ -10,13 +10,14 @@ interface AgentWorkspaceSidebarProps {visibleAgents: Agent[];activeAgentId: string;filters: ActivityFilters;+ showAllAgentsOption?: boolean;+ showAgentFilter?: boolean;profiles: Profile[];filteredInstances: Instance[];visibleTabs: InstanceTab[];loading: boolean;onSidebarTabChange: (tab: WorkspaceTab) => void;onSelectAgent: (agentId: string) => void;- onClearAgentSelection: () => void;onClearFilters: () => void;onRefresh: () => void;onFilterChange: (key: keyof ActivityFilters, value: string) => void;@@ -29,13 +30,14 @@ export default function AgentWorkspaceSidebar({visibleAgents,activeAgentId,filters,+ showAllAgentsOption = true,+ showAgentFilter = true,profiles,filteredInstances,visibleTabs,loading,onSidebarTabChange,onSelectAgent,- onClearAgentSelection,onClearFilters,onRefresh,onFilterChange,@@ -73,17 +75,19 @@ export default function AgentWorkspaceSidebar({</div>) : (<div className="flex flex-col gap-1">- <button- type="button"- className={`rounded-sm px-3 py-2 text-left text-sm transition-all ${- activeAgentId === ""- ? "border border-primary/30 bg-primary/10 text-primary"- : "border border-transparent text-text-muted hover:bg-bg-elevated"- }`}- onClick={onClearAgentSelection}- >- All Agents- </button>+ {showAllAgentsOption && (+ <button+ type="button"+ className={`rounded-sm px-3 py-2 text-left text-sm transition-all ${+ activeAgentId === ""+ ? "border border-primary/30 bg-primary/10 text-primary"+ : "border border-transparent text-text-muted hover:bg-bg-elevated"+ }`}+ onClick={() => onSelectAgent("")}+ >+ All Agents+ </button>+ )}{visibleAgents.map((agent) => (<AgentItemkey={agent.id}@@ -102,6 +106,7 @@ export default function AgentWorkspaceSidebar({instanceOptions={filteredInstances}tabOptions={visibleTabs}loading={loading}+ showAgentFilter={showAgentFilter}onClear={onClearFilters}onRefresh={onRefresh}onFilterChange={onFilterChange}diff --git a/dashboard/src/activities/AgentsPage.test.tsx b/dashboard/src/activities/AgentsPage.test.tsxindex 22fb8fde..ed218f1a 100644--- a/dashboard/src/activities/AgentsPage.test.tsx+++ b/dashboard/src/activities/AgentsPage.test.tsx@@ -1,4 +1,4 @@-import { render, screen, waitFor } from "@testing-library/react";+import { act, 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";@@ -11,10 +11,11 @@ vi.mock("./api", () => ({vi.mock("../services/api", () => ({fetchAllTabs: vi.fn(),+ fetchAgent: vi.fn(),}));import { fetchActivity } from "./api";-import { fetchAllTabs } from "../services/api";+import { fetchAgent, fetchAllTabs } from "../services/api";describe("AgentsPage", () => {beforeEach(() => {@@ -29,48 +30,95 @@ describe("AgentsPage", () => {requestCount: 3,},],+ agentEventsById: {},profiles: [],instances: [],currentTabs: {},});vi.mocked(fetchAllTabs).mockResolvedValue([]);- vi.mocked(fetchActivity).mockResolvedValue({- count: 3,+ vi.mocked(fetchAgent).mockResolvedValue({+ agent: {+ id: "cli",+ name: "CLI",+ connectedAt: "2026-03-16T08:00:00Z",+ lastActivity: "2026-03-16T08:10:00Z",+ requestCount: 3,+ },events: [{- timestamp: "2026-03-16T09:00:00Z",- source: "cli",- requestId: "req_123",+ id: "evt_1",agentId: "cli",+ channel: "tool_call",+ type: "click",method: "POST",path: "/tabs/tab_123/action",- status: 200,- durationMs: 87,- action: "click",+ timestamp: "2026-03-16T09:00:00Z",+ details: {+ source: "bridge",+ requestId: "req_123",+ status: 200,+ durationMs: 87,+ tabId: "tab_123",+ action: "click",+ },},{- timestamp: "2026-03-16T09:00:01Z",- source: "dashboard",- requestId: "req_124",+ id: "evt_2",+ agentId: "cli",+ channel: "tool_call",+ type: "text",method: "GET",- path: "/profiles",- status: 200,- durationMs: 22,+ path: "/tabs/tab_123/text",+ timestamp: "2026-03-16T09:00:02Z",+ details: {+ source: "server",+ requestId: "req_125",+ status: 200,+ durationMs: 11,+ tabId: "tab_123",+ },},{- timestamp: "2026-03-16T09:00:02Z",- source: "server",- requestId: "req_125",- method: "GET",- path: "/health",+ id: "evt_hidden",+ agentId: "cli",+ channel: "tool_call",+ type: "navigate",+ method: "POST",+ path: "/tabs/tab_123/navigate",+ timestamp: "2026-03-16T09:00:03Z",+ details: {+ source: "dashboard",+ requestId: "req_hidden",+ status: 200,+ durationMs: 9,+ tabId: "tab_123",+ url: "https://hidden.example",+ action: "navigate",+ },+ },+ ],+ });+ vi.mocked(fetchActivity).mockResolvedValue({+ count: 1,+ events: [+ {+ timestamp: "2026-03-16T09:01:00Z",+ source: "bridge",+ requestId: "req_activity",+ agentId: "cli",+ method: "POST",+ path: "/tabs/tab_555/navigate",status: 200,- durationMs: 11,+ durationMs: 10,+ tabId: "tab_555",+ url: "https://pinchtab.com",+ action: "navigate",},],});});- it("defaults the right rail to Agents", async () => {+ it("defaults the right rail to Agents and bootstraps the selected agent thread", async () => {render(<MemoryRouter><AgentsPage />@@ -78,16 +126,17 @@ describe("AgentsPage", () => {);await waitFor(() => {- expect(fetchActivity).toHaveBeenCalled();+ expect(fetchAgent).toHaveBeenCalledWith("cli", "both");});expect(screen.getByRole("button", { name: "Agents" })).toHaveClass("bg-primary/8",);expect(screen.queryByText("Request timeline")).not.toBeInTheDocument();+ expect(fetchActivity).not.toHaveBeenCalled();});- it("switches to Activities and shows the filter stack", async () => {+ it("switches to Activities and shows the filter stack including agent filter", async () => {render(<MemoryRouter><AgentsPage />@@ -95,16 +144,20 @@ describe("AgentsPage", () => {);await waitFor(() => {- expect(fetchActivity).toHaveBeenCalled();+ expect(fetchAgent).toHaveBeenCalled();});await userEvent.click(screen.getByRole("button", { name: "Activities" }));+ await waitFor(() => {+ expect(fetchActivity).toHaveBeenCalled();+ });+expect(screen.getByLabelText("Profile")).toBeInTheDocument();expect(screen.getByLabelText("Agent")).toBeInTheDocument();});- it("filters dashboard and server source events out of the agents stream", async () => {+ it("keeps the simplified event rows and inline copyable tab ids", async () => {render(<MemoryRouter><AgentsPage />@@ -112,12 +165,88 @@ describe("AgentsPage", () => {);await waitFor(() => {- expect(fetchActivity).toHaveBeenCalled();+ expect(screen.getByText(/Click on page on tab/)).toBeInTheDocument();+ });++ expect(+ screen.queryByRole("button", { name: "All Agents" }),+ ).not.toBeInTheDocument();+ expect(screen.queryByText("bridge")).not.toBeInTheDocument();+ expect(screen.queryByText("POST")).not.toBeInTheDocument();+ expect(screen.queryByText("200")).not.toBeInTheDocument();+ expect(screen.queryByText("agent:cli")).not.toBeInTheDocument();+ expect(screen.getAllByRole("button", { name: "tab_123" }).length).toBe(3);+ });++ it("shows all agent activity in the thread regardless of source", async () => {+ render(+ <MemoryRouter>+ <AgentsPage />+ </MemoryRouter>,+ );++ await waitFor(() => {+ expect(screen.getByText(/3 events • 1 agents/)).toBeInTheDocument();+ });++ expect(+ screen.getAllByText(+ (_content, element) =>+ element?.textContent === "Click on page on tab tab_123",+ ).length,+ ).toBeGreaterThan(0);+ expect(+ screen.getAllByText(+ (_content, element) =>+ element?.textContent === "Extract text from page on tab tab_123",+ ).length,+ ).toBeGreaterThan(0);+ expect(+ screen.getAllByText(/Navigate to https:\/\/hidden\.example/).length,+ ).toBeGreaterThan(0);+ });++ it("updates the open agent thread and sidebar list from the shared store", async () => {+ render(+ <MemoryRouter>+ <AgentsPage />+ </MemoryRouter>,+ );++ await waitFor(() => {+ expect(fetchAgent).toHaveBeenCalled();+ });++ act(() => {+ useAppStore.getState().upsertAgentFromEvent({+ id: "evt_new_agent",+ agentId: "worker-2",+ channel: "progress",+ type: "progress",+ method: "POST",+ path: "/api/agents/worker-2/events",+ message: "Planning next step",+ timestamp: "2026-03-16T09:00:04Z",+ } as any);+ useAppStore.getState().appendAgentEvent({+ id: "evt_live",+ agentId: "cli",+ channel: "progress",+ type: "progress",+ method: "POST",+ path: "/api/agents/cli/events",+ message: "Planning next step",+ timestamp: "2026-03-16T09:00:05Z",+ details: {+ source: "server",+ requestId: "req_live",+ status: 201,+ durationMs: 3,+ },+ } as any);});- expect(screen.getByText("/tabs/tab_123/action")).toBeInTheDocument();- expect(screen.queryByText("/profiles")).not.toBeInTheDocument();- expect(screen.queryByText("/health")).not.toBeInTheDocument();- expect(screen.getByText(/1 events • 1 agents/)).toBeInTheDocument();+ expect(screen.getByText("worker-2")).toBeInTheDocument();+ expect(screen.getByText("Planning next step")).toBeInTheDocument();});});diff --git a/dashboard/src/activities/AgentsPage.tsx b/dashboard/src/activities/AgentsPage.tsxindex b621769c..bc95e80c 100644--- a/dashboard/src/activities/AgentsPage.tsx+++ b/dashboard/src/activities/AgentsPage.tsx@@ -1,10 +1,21 @@import AgentActivityWorkspace from "./AgentActivityWorkspace";+const AGENT_PAGE_INITIAL_FILTERS = { ageSec: "", limit: "1000" } as const;+export default function AgentsPage() {return (<AgentActivityWorkspace+ initialFilters={AGENT_PAGE_INITIAL_FILTERS}defaultSidebarTab="agents"- hiddenSources={["dashboard", "server"]}+ requireAgentIdentity+ requireSelectedAgent+ showAllAgentsOption={false}+ showAgentFilter+ simplifyEventRows+ copyTabId+ preferKnownAgents+ useAgentEventStore+ clearToInitialFilters/>);}diff --git a/dashboard/src/activities/CopyIdPill.tsx b/dashboard/src/activities/CopyIdPill.tsxnew file mode 100644index 00000000..6cb0b3ab--- /dev/null+++ b/dashboard/src/activities/CopyIdPill.tsx@@ -0,0 +1,58 @@+import { useEffect, useState } from "react";++function compactId(value: string): string {+ if (value.length <= 12) {+ return value;+ }+ return `${value.slice(0, 4)}…${value.slice(-4)}`;+}++interface CopyIdPillProps {+ id: string;+ compact?: boolean;+ inline?: boolean;+}++export default function CopyIdPill({+ id,+ compact = false,+ inline = false,+}: CopyIdPillProps) {+ const [copied, setCopied] = useState(false);++ useEffect(() => {+ if (!copied) {+ return;+ }+ const timeoutId = window.setTimeout(() => setCopied(false), 1200);+ return () => window.clearTimeout(timeoutId);+ }, [copied]);++ const handleClick = async () => {+ try {+ await navigator.clipboard.writeText(id);+ setCopied(true);+ } catch {+ setCopied(false);+ }+ };++ return (+ <button+ type="button"+ className={`dashboard-mono transition-all hover:text-primary ${+ inline+ ? "inline-flex items-center rounded border border-border-subtle/70 bg-white/4 px-1 py-[0.08rem] align-baseline text-[0.54rem] font-medium leading-none text-text-muted hover:border-primary/30 hover:bg-primary/8"+ : "rounded-sm border border-border-subtle bg-white/3 px-1.5 py-0.5 text-[0.62rem] font-semibold text-text-secondary hover:border-primary/30 hover:bg-primary/10"+ }`}+ onClick={() => {+ void handleClick();+ }}+ title={copied ? "Copied" : `Copy tab ID ${id}`}+ >+ <span className="block truncate">+ {copied ? "Copied" : compact ? compactId(id) : id}+ </span>+ </button>+ );+}diff --git a/dashboard/src/activities/FilterPill.tsx b/dashboard/src/activities/FilterPill.tsxnew file mode 100644index 00000000..3e2ed089--- /dev/null+++ b/dashboard/src/activities/FilterPill.tsx@@ -0,0 +1,17 @@+interface FilterPillProps {+ label: string;+ onClick: () => void;+}++export default function FilterPill({ label, onClick }: FilterPillProps) {+ 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"+ onClick={onClick}+ title={label}+ >+ <span className="block truncate">{label}</span>+ </button>+ );+}diff --git a/dashboard/src/activities/StreamRow.tsx b/dashboard/src/activities/StreamRow.tsxnew file mode 100644index 00000000..fdf4abed--- /dev/null+++ b/dashboard/src/activities/StreamRow.tsx@@ -0,0 +1,216 @@+import { Badge } from "../components/atoms";+import { activityMethodVariant, activityStatusVariant } from "./helpers";+import type { ActivityFilters, DashboardActivityEvent } from "./types";+import CopyIdPill from "./CopyIdPill";+import FilterPill from "./FilterPill";++function formatTime(ts: string): string {+ return new Date(ts).toLocaleTimeString("en-GB", {+ hour: "2-digit",+ minute: "2-digit",+ second: "2-digit",+ });+}++function eventIcon(event: DashboardActivityEvent): string {+ if (event.channel === "progress") return "💬";+ if (event.action === "click" || event.action === "dblclick") return "👆";+ if (event.action === "type") return "⌨️";+ if (event.action === "hover") return "🖱️";+ if (event.path.includes("/navigate")) return "🧭";+ if (event.path.includes("/snapshot")) return "📸";+ if (event.path.includes("/screencast")) return "🖥️";+ return "📝";+}++function compactId(value: string): string {+ if (value.length <= 12) {+ return value;+ }+ return `${value.slice(0, 4)}…${value.slice(-4)}`;+}++function quoted(value: string): string {+ return `"${value}"`;+}++function eventSummary(event: DashboardActivityEvent): string {+ if (event.channel === "progress" && event.message) {+ return event.message;+ }+ if (event.path.includes("/navigate")) {+ return event.url ? `Navigate to ${event.url}` : "Navigate to page";+ }++ if (event.path.includes("/snapshot")) {+ return "Capture page snapshot";+ }++ if (event.path.includes("/screencast")) {+ return "Open screencast stream";+ }++ if (event.path.includes("/text")) {+ return "Extract text from page";+ }++ switch (event.action) {+ case "click":+ return event.ref ? `Click ${quoted(event.ref)}` : "Click on page";+ case "dblclick":+ return event.ref+ ? `Double-click ${quoted(event.ref)}`+ : "Double-click on page";+ case "type":+ return event.ref ? `Type into ${quoted(event.ref)}` : "Type into page";+ case "hover":+ return event.ref ? `Hover ${quoted(event.ref)}` : "Hover on page";+ default:+ return "Run browser operation";+ }+}++interface StreamRowProps {+ event: DashboardActivityEvent;+ copyTabId?: boolean;+ hideAgentFilter?: boolean;+ simplifyMeta?: boolean;+ onFilterChange: (key: keyof ActivityFilters, value: string) => void;+}++export default function StreamRow({+ event,+ copyTabId = false,+ hideAgentFilter = false,+ simplifyMeta = false,+ onFilterChange,+}: StreamRowProps) {+ if (simplifyMeta) {+ return (+ <div className="px-4 py-4">+ <div className="flex items-start gap-3">+ <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full border border-primary/20 bg-primary/10 text-lg shadow-[0_0_24px_rgb(var(--brand-accent-rgb)/0.08)]">+ {eventIcon(event)}+ </div>+ <div className="min-w-0 flex-1">+ <div className="mb-2 flex flex-wrap items-center gap-2 text-[0.68rem] text-text-muted">+ <span className="dashboard-mono text-[0.68rem] text-text-muted">+ {formatTime(event.timestamp)}+ </span>+ <span className="dashboard-mono">·</span>+ <span className="dashboard-mono">{event.durationMs}ms</span>+ </div>++ <div className="border-l border-border-subtle pl-4">+ <div className="text-[0.95rem] leading-6 text-text-primary">+ {eventSummary(event)}+ {event.tabId && event.channel !== "progress" && (+ <>+ {" on tab "}+ {copyTabId ? (+ <CopyIdPill id={event.tabId} compact inline />+ ) : (+ <span className="dashboard-mono">+ {compactId(event.tabId)}+ </span>+ )}+ </>+ )}+ </div>++ <div className="mt-4 flex flex-wrap items-center gap-2">+ {event.profileName && (+ <FilterPill+ label={`profile:${event.profileName}`}+ onClick={() =>+ onFilterChange("profileName", event.profileName || "")+ }+ />+ )}+ {event.instanceId && (+ <FilterPill+ label={`instance:${event.instanceId}`}+ onClick={() =>+ onFilterChange("instanceId", event.instanceId || "")+ }+ />+ )}+ </div>+ </div>+ </div>+ </div>+ </div>+ );+ }++ return (+ <div className="border-b border-border-subtle/70 px-4 py-3 text-sm transition-colors hover:bg-white/2">+ <div className="flex items-start gap-3">+ <span className="pt-0.5 text-lg">{eventIcon(event)}</span>+ <span className="dashboard-mono w-18 shrink-0 pt-0.5 text-xs text-text-muted">+ {formatTime(event.timestamp)}+ </span>+ <div className="min-w-0 flex-1">+ <div className="flex flex-wrap items-center gap-2">+ <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>}+ <span className="dashboard-mono min-w-0 flex-1 truncate text-text-secondary">+ {event.path}+ </span>+ </div>++ <div className="mt-1 flex flex-wrap items-center gap-1.5">+ {event.tabId &&+ (copyTabId ? (+ <CopyIdPill id={event.tabId} />+ ) : (+ <FilterPill+ label={`tab:${event.tabId}`}+ onClick={() => onFilterChange("tabId", event.tabId || "")}+ />+ ))}+ {event.profileName && (+ <FilterPill+ label={`profile:${event.profileName}`}+ onClick={() =>+ onFilterChange("profileName", event.profileName || "")+ }+ />+ )}+ {event.instanceId && (+ <FilterPill+ label={`instance:${event.instanceId}`}+ onClick={() =>+ onFilterChange("instanceId", event.instanceId || "")+ }+ />+ )}+ {event.url && (+ <span className="dashboard-mono min-w-0 truncate text-[0.68rem] text-text-muted">+ {event.url}+ </span>+ )}+ </div>+ </div>++ <div className="flex shrink-0 flex-col items-end gap-1.5">+ <span className="dashboard-mono text-xs text-text-muted">+ {event.durationMs}ms+ </span>+ {!hideAgentFilter && event.agentId && (+ <FilterPill+ label={`agent:${event.agentId}`}+ onClick={() => onFilterChange("agentId", event.agentId || "")}+ />+ )}+ </div>+ </div>+ </div>+ );+}diff --git a/dashboard/src/activities/helpers.ts b/dashboard/src/activities/helpers.tsindex e7a45013..21f6899f 100644--- a/dashboard/src/activities/helpers.ts+++ b/dashboard/src/activities/helpers.ts@@ -7,7 +7,6 @@ export const defaultActivityFilters: ActivityFilters = {profileName: "",sessionId: "",action: "",- source: "",pathPrefix: "",ageSec: "3600",limit: "200",@@ -21,14 +20,6 @@ export const actionOptions = ["type","hover",];-export const sourceOptions = [- "",- "server",- "bridge",- "scheduler",- "mcp",- "cli",-];export function buildActivityQuery(filters: ActivityFilters): ActivityQuery {const query: ActivityQuery = {};@@ -40,7 +31,6 @@ export function buildActivityQuery(filters: ActivityFilters): ActivityQuery {}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);@@ -78,7 +68,6 @@ export function sameActivityFilters(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.limitdiff --git a/dashboard/src/activities/types.ts b/dashboard/src/activities/types.tsindex 66f8ba1e..5b2a7d56 100644--- a/dashboard/src/activities/types.ts+++ b/dashboard/src/activities/types.ts@@ -1,6 +1,11 @@import type { ActivityLogEvent, ActivityLogResponse } from "../generated/types";-export type DashboardActivityEvent = ActivityLogEvent;+export type DashboardActivityEvent = ActivityLogEvent & {+ channel?: string;+ message?: string;+ progress?: number;+ total?: number;+};export type DashboardActivityResponse = ActivityLogResponse;export interface ActivityFilters {@@ -10,7 +15,6 @@ export interface ActivityFilters {profileName: string;sessionId: string;action: string;- source: string;pathPrefix: string;ageSec: string;limit: string;diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex 5cc6c6f6..51117432 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -288,8 +288,16 @@ export async function fetchAgents(): Promise<Agent[]> {return request<Agent[]>("/api/agents");}-export async function fetchAgent(id: string): Promise<AgentDetail> {- return request<AgentDetail>(`/api/agents/${encodeURIComponent(id)}`);+export async function fetchAgent(+ id: string,+ mode?: string,+): Promise<AgentDetail> {+ const params = new URLSearchParams();+ if (mode) {+ params.set("mode", mode);+ }+ const suffix = params.size > 0 ? `?${params.toString()}` : "";+ return request<AgentDetail>(`/api/agents/${encodeURIComponent(id)}${suffix}`);}export async function fetchServerMetrics(): Promise<MonitoringServerMetrics> {diff --git a/dashboard/src/services/dashboardRealtime.ts b/dashboard/src/services/dashboardRealtime.tsnew file mode 100644index 00000000..1cd4f276--- /dev/null+++ b/dashboard/src/services/dashboardRealtime.ts@@ -0,0 +1,108 @@+import type { Agent } from "../generated/types";+import { useAppStore } from "../stores/useAppStore";+import { subscribeToEvents } from "./api";++interface RealtimeHandle {+ consumers: number;+ includeMemory: boolean;+ unsubscribe: (() => void) | null;+}++const realtimeHandle: RealtimeHandle = {+ consumers: 0,+ includeMemory: false,+ unsubscribe: null,+};++function sortAgents(agents: Agent[]): Agent[] {+ return [...agents].sort(+ (left, right) =>+ new Date(right.lastActivity || right.connectedAt).getTime() -+ new Date(left.lastActivity || left.connectedAt).getTime(),+ );+}++function mergeAgents(current: Agent[], incoming: Agent[]): Agent[] {+ const merged = new Map<string, Agent>();++ for (const agent of current) {+ merged.set(agent.id, agent);+ }++ for (const agent of incoming) {+ const existing = merged.get(agent.id);+ if (!existing) {+ merged.set(agent.id, agent);+ continue;+ }++ merged.set(agent.id, {+ ...existing,+ ...agent,+ connectedAt:+ new Date(existing.connectedAt).getTime() <+ new Date(agent.connectedAt).getTime()+ ? existing.connectedAt+ : agent.connectedAt,+ lastActivity:+ new Date(existing.lastActivity || existing.connectedAt).getTime() >+ new Date(agent.lastActivity || agent.connectedAt).getTime()+ ? existing.lastActivity+ : agent.lastActivity,+ requestCount: Math.max(existing.requestCount, agent.requestCount),+ });+ }++ return sortAgents([...merged.values()]);+}++function startDashboardRealtime(includeMemory: boolean) {+ realtimeHandle.unsubscribe?.();+ realtimeHandle.includeMemory = includeMemory;+ realtimeHandle.unsubscribe = subscribeToEvents(+ {+ onInit: (agents) => {+ const state = useAppStore.getState();+ state.setAgents(mergeAgents(state.agents, agents));+ },+ onSystem: (event) => {+ console.log("System event:", event);+ },+ onActivity: (event) => {+ const state = useAppStore.getState();+ state.upsertAgentFromEvent(event);+ state.appendAgentEvent(event);+ state.addEvent(event);+ },+ onMonitoring: (snapshot) => {+ useAppStore+ .getState()+ .applyMonitoringSnapshot(snapshot, realtimeHandle.includeMemory);+ },+ },+ {+ includeMemory,+ reasoningMode: "both",+ },+ );+}++export function acquireDashboardRealtime(includeMemory: boolean): () => void {+ realtimeHandle.consumers += 1;++ if (+ realtimeHandle.unsubscribe === null ||+ realtimeHandle.includeMemory !== includeMemory+ ) {+ startDashboardRealtime(includeMemory);+ }++ return () => {+ realtimeHandle.consumers = Math.max(0, realtimeHandle.consumers - 1);+ if (realtimeHandle.consumers > 0) {+ return;+ }+ realtimeHandle.unsubscribe?.();+ realtimeHandle.unsubscribe = null;+ };+}diff --git a/dashboard/src/stores/useAppStore.test.ts b/dashboard/src/stores/useAppStore.test.tsindex f3bbbba7..f4ef90ca 100644--- a/dashboard/src/stores/useAppStore.test.ts+++ b/dashboard/src/stores/useAppStore.test.ts@@ -16,6 +16,7 @@ describe("useAppStore", () => {currentMemory: {},agents: [],selectedAgentId: null,+ agentEventsById: {},events: [],eventFilter: "all",settings: {@@ -170,6 +171,58 @@ describe("useAppStore", () => {expect(agents[0].requestCount).toBe(2);expect(agents[0].lastActivity).toBe("2024-01-01T00:01:00Z");});++ it("ignores live events without an agent id", () => {+ useAppStore.getState().upsertAgentFromEvent({+ id: "evt_1",+ agentId: "",+ channel: "progress",+ type: "progress",+ method: "",+ path: "",+ timestamp: "2024-01-01T00:00:00Z",+ } as any);++ expect(useAppStore.getState().agents).toEqual([]);+ });++ it("hydrates agent history without dropping already streamed events", () => {+ useAppStore.getState().appendAgentEvent({+ id: "evt_live",+ agentId: "agent_1",+ channel: "progress",+ type: "progress",+ method: "POST",+ path: "/api/agents/agent_1/events",+ timestamp: "2024-01-01T00:02:00Z",+ } as any);++ useAppStore.getState().hydrateAgentEvents("agent_1", [+ {+ id: "evt_old",+ agentId: "agent_1",+ channel: "tool_call",+ type: "navigate",+ method: "POST",+ path: "/navigate",+ timestamp: "2024-01-01T00:01:00Z",+ } as any,+ {+ id: "evt_live",+ agentId: "agent_1",+ channel: "progress",+ type: "progress",+ method: "POST",+ path: "/api/agents/agent_1/events",+ timestamp: "2024-01-01T00:02:00Z",+ } as any,+ ]);++ expect(useAppStore.getState().agentEventsById.agent_1).toEqual([+ expect.objectContaining({ id: "evt_old" }),+ expect.objectContaining({ id: "evt_live" }),+ ]);+ });});describe("settings", () => {diff --git a/dashboard/src/stores/useAppStore.ts b/dashboard/src/stores/useAppStore.tsindex 6a0c52b5..1bb31673 100644--- a/dashboard/src/stores/useAppStore.ts+++ b/dashboard/src/stores/useAppStore.ts@@ -58,8 +58,11 @@ interface AppState {// Agentsagents: Agent[];selectedAgentId: string | null;+ agentEventsById: Record<string, ActivityEvent[]>;setAgents: (agents: Agent[]) => void;upsertAgentFromEvent: (event: ActivityEvent) => void;+ hydrateAgentEvents: (agentId: string, events: ActivityEvent[]) => void;+ appendAgentEvent: (event: ActivityEvent) => void;setSelectedAgentId: (id: string | null) => void;// Activity feed@@ -196,10 +199,14 @@ export const useAppStore = create<AppState>((set) => ({// Agentsagents: [],selectedAgentId: null,+ agentEventsById: {},setAgents: (agents) => set({ agents }),upsertAgentFromEvent: (event) =>set((state) => {- const agentId = event.agentId || "anonymous";+ const agentId = event.agentId?.trim();+ if (!agentId) {+ return state;+ }const existing = state.agents.find((agent) => agent.id === agentId);if (!existing) {@@ -235,6 +242,50 @@ export const useAppStore = create<AppState>((set) => ({),};}),+ hydrateAgentEvents: (agentId, events) =>+ set((state) => ({+ agentEventsById: {+ ...state.agentEventsById,+ [agentId]: [...(state.agentEventsById[agentId] ?? []), ...events]+ .reduce<ActivityEvent[]>((merged, event) => {+ if (merged.some((existing) => existing.id === event.id)) {+ return merged;+ }+ merged.push(event);+ return merged;+ }, [])+ .sort(+ (left, right) =>+ new Date(left.timestamp).getTime() -+ new Date(right.timestamp).getTime(),+ )+ .slice(-500),+ },+ })),+ appendAgentEvent: (event) =>+ set((state) => {+ const agentId = event.agentId?.trim();+ if (!agentId) {+ return state;+ }+ const current = state.agentEventsById[agentId] ?? [];+ if (current.some((existing) => existing.id === event.id)) {+ return state;+ }+ const next = [...current, event]+ .sort(+ (left, right) =>+ new Date(left.timestamp).getTime() -+ new Date(right.timestamp).getTime(),+ )+ .slice(-500);+ return {+ agentEventsById: {+ ...state.agentEventsById,+ [agentId]: next,+ },+ };+ }),setSelectedAgentId: (selectedAgentId) => set({ selectedAgentId }),// Activity feeddiff --git a/docs/endpoints.md b/docs/endpoints.mdindex 3c9e9488..195d9dd3 100644--- a/docs/endpoints.md+++ b/docs/endpoints.md@@ -380,6 +380,12 @@ Activity query parameters include:- `engine`- `pathPrefix`+Activity attribution and source behavior:++- requests tagged with `X-Agent-Id` are recorded as `agentId` and can be filtered with `GET /api/activity?agentId=<id>`+- unfiltered `GET /api/activity` returns the primary activity feed+- named internal sources such as `dashboard` or `orchestrator` are stored in source-specific daily files and can be queried with `?source=<name>`+Scheduler routes are only present when `scheduler.enabled` is true.## Feature Gatesdiff --git a/docs/guides/data-storage.md b/docs/guides/data-storage.mdindex a2a0423c..64f2727a 100644--- a/docs/guides/data-storage.md+++ b/docs/guides/data-storage.md@@ -8,9 +8,9 @@ PinchTab stores configuration, profiles, session state, and usage logs on local| --- | --- | --- || `config.json` | Main PinchTab configuration | `PINCHTAB_CONFIG` selects the file || `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` |+| `activity/events-YYYY-MM-DD.jsonl` | Primary daily request/activity log for `/api/activity`, CLI activity, and dashboard activity views | `server.stateDir`, `observability.activity.retentionDays` |+| `activity/events-<source>-YYYY-MM-DD.jsonl` | Source-specific daily activity log for named sources such as `dashboard` or `orchestrator` | `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,7 +28,6 @@ Typical layout:```textpinchtab/├── config.json-├── action_logs.json├── activity/│ └── events-2026-03-16.jsonl├── sessions.json@@ -107,6 +106,12 @@ Request activity is stored as one JSONL file per UTC day:<server.stateDir>/activity/events-YYYY-MM-DD.jsonl```+Named sources also get their own daily files:++```text+<server.stateDir>/activity/events-<source>-YYYY-MM-DD.jsonl+```+By default PinchTab keeps 1 day of activity data and prunes older daily files when new activity is recorded. You can change that with:```json@@ -122,6 +127,10 @@ By default PinchTab keeps 1 day of activity data and prunes older daily files wh`retentionDays` controls on-disk retention for activity logs. `sessionIdleSec` controls session grouping only.+Requests that carry `X-Agent-Id` are stored with that value as `agentId` in the activity event. This is what powers agent-scoped queries such as `GET /api/activity?agentId=<id>` and the dashboard Agents view.++Unfiltered `GET /api/activity` reads the primary feed. Source-specific logs remain queryable by passing `source=<name>`.+In orchestrator mode, child instances get their own state directory under the profile:```text@@ -130,15 +139,9 @@ In orchestrator mode, child instances get their own state directory under the prPinchTab writes a child `config.json` there so the launched instance can inherit the correct profile path, state directory, and port.-## Action Logs--PinchTab also stores profile-level analytics data in:--```text-<user-config-dir>/action_logs.json-```+Managed child bridges still write activity into the shared parent activity store. That keeps `/api/activity`, `/api/agents`, and dashboard activity views unified across orchestrator-managed instances instead of splitting activity by per-instance state directory.-This powers profile analytics endpoints. It is separate from the request/activity JSONL files and from per-instance session restore state.+Profile `logs` and `analytics` endpoints are derived from the activity store rather than a separate analytics file.## Customizing Storage@@ -210,7 +213,6 @@ Removing the PinchTab data directory deletes:- saved profiles- session restore data-- action logs- local configurationBack up the profile directories first if you need to preserve logged-in browser sessions.diff --git a/docs/guides/tailscale-bridge-orchestrator.md b/docs/guides/tailscale-bridge-orchestrator.mdindex 00693095..c8c44788 100644--- a/docs/guides/tailscale-bridge-orchestrator.md+++ b/docs/guides/tailscale-bridge-orchestrator.md@@ -271,7 +271,7 @@ Open a tab on the remote bridge:curl -X POST http://127.0.0.1:9867/instances/<instanceId>/tabs/open \-H "Authorization: Bearer orchestrator-token" \-H "Content-Type: application/json" \- -d '{"url":"https://example.com"}'+ -d '{"url":"https://pinchtab.com"}'```Read a tab through the orchestrator:diff --git a/docs/reference/cli.md b/docs/reference/cli.mdindex 2089e585..826ca073 100644--- a/docs/reference/cli.md+++ b/docs/reference/cli.md@@ -41,13 +41,33 @@ pinchtab serverpinchtab bridgepinchtab mcppinchtab config-pinchtab nav https://example.com+pinchtab --agent-id agent-main nav https://pinchtab.com+pinchtab nav https://pinchtab.compinchtab snap -i -cpinchtab click e5pinchtab find "login button"pinchtab network --limit 20```+Global flags such as `--server` and `--agent-id` apply to direct command mode. `--agent-id` is recorded in activity logs and dashboard agent views so multiple CLI-driven agents are distinguishable.++## Agent Attribution++CLI requests carry agent identity over the `X-Agent-Id` request header.++- `--agent-id <value>` sets the header explicitly for that command+- `PINCHTAB_AGENT_ID` sets the default agent ID for the current shell or script+- if neither is set, the CLI uses `cli`++That agent ID is what appears as `agentId` in `/api/activity`, the Agents page, and scheduler-driven activity.++Example:++```bash+PINCHTAB_AGENT_ID=agent-crawl-01 pinchtab nav https://pinchtab.com+curl 'http://127.0.0.1:9867/api/activity?agentId=agent-crawl-01'+```+## Core Commands| Command | Purpose |diff --git a/docs/reference/fill.md b/docs/reference/fill.mdindex d11e29be..ea459683 100644--- a/docs/reference/fill.md+++ b/docs/reference/fill.md@@ -5,9 +5,9 @@ Set an input value directly without relying on the same event sequence as `type````bashcurl -X POST http://localhost:9867/action \-H "Content-Type: application/json" \- -d '{"kind":"fill","ref":"e8","text":"[email protected]"}'+ -d '{"kind":"fill","ref":"e8","text":"[email protected]"}'# CLI Alternative-pinchtab fill e8 "[email protected]"+pinchtab fill e8 "[email protected]"# Response{"success": true,diff --git a/docs/reference/find.md b/docs/reference/find.mdindex 6b97e65e..e24a4cee 100644--- a/docs/reference/find.md+++ b/docs/reference/find.md@@ -100,7 +100,7 @@ Then use the returned ref:```bashcurl -X POST http://localhost:9867/tabs/<tabId>/action \-H "Content-Type: application/json" \- -d '{"ref":"e14","kind":"type","text":"[email protected]"}'+ -d '{"ref":"e14","kind":"type","text":"[email protected]"}'```## Operational Notesdiff --git a/docs/reference/keyboard.md b/docs/reference/keyboard.mdindex b9af83c9..cc9acd96 100644--- a/docs/reference/keyboard.md+++ b/docs/reference/keyboard.md@@ -17,7 +17,7 @@ pinchtab keyboard type "hello world"Insert text directly without dispatching key events. Equivalent to pasting text — faster but won't trigger keydown/keypress/keyup listeners.```bash-pinchtab keyboard inserttext "[email protected]"+pinchtab keyboard inserttext "[email protected]"```Use `inserttext` when:diff --git a/docs/reference/navigate.md b/docs/reference/navigate.mdindex 73115b81..ccc1451f 100644--- a/docs/reference/navigate.md+++ b/docs/reference/navigate.md@@ -5,13 +5,13 @@ Open a new tab and navigate it to a URL, or reuse a tab when a tab ID is provide```bashcurl -X POST http://localhost:9867/navigate \-H "Content-Type: application/json" \- -d '{"url":"https://example.com"}'+ -d '{"url":"https://pinchtab.com"}'# CLI Alternative-pinchtab nav https://example.com+pinchtab nav https://pinchtab.com# Response{"tabId": "8f9c7d4e1234567890abcdef12345678",- "url": "https://example.com",+ "url": "https://pinchtab.com","title": "Example Domain"}```diff --git a/docs/reference/profiles.md b/docs/reference/profiles.mdindex d8f13080..c73742e5 100644--- a/docs/reference/profiles.md+++ b/docs/reference/profiles.md@@ -51,7 +51,7 @@ curl http://localhost:9867/profiles/prof_278be873"sizeMB": 510.17,"source": "created","chromeProfileName": "Your Chrome",- "accountEmail": "[email protected]",+ "accountEmail": "[email protected]","accountName": "Luigi","hasAccount": true,"useWhen": "Use for work accounts",@@ -194,7 +194,7 @@ curl http://localhost:9867/profiles/prof_278be873/logscurl 'http://localhost:9867/profiles/work/logs?limit=50'```-`logs` accepts either the profile ID or the profile name.+`logs` accepts either the profile ID or the profile name. Results are derived from the activity store for that profile.### Get Analytics@@ -203,7 +203,7 @@ curl http://localhost:9867/profiles/prof_278be873/analyticscurl http://localhost:9867/profiles/work/analytics```-`analytics` also accepts either the profile ID or the profile name.+`analytics` also accepts either the profile ID or the profile name. It is computed from the same activity data used by `/api/activity`.## Related Pagesdiff --git a/docs/reference/scheduler.md b/docs/reference/scheduler.mdindex afa7d19c..1f473e8b 100644--- a/docs/reference/scheduler.md+++ b/docs/reference/scheduler.md@@ -114,6 +114,7 @@ Important:- request validation enforces only `agentId` and `action`- missing `tabId` is rejected later during execution with `tabId is required for task execution`- past deadlines are rejected at submission time+- `agentId` is also forwarded to the executor as `X-Agent-Id`, so the resulting browser action is attributed to the same agent in `/api/activity` and the dashboard Agents view## Queue Full Response@@ -260,6 +261,7 @@ That means:- `action` becomes `kind`- top-level `ref` is forwarded when present- every key in `params` is merged into the top-level action body+- `agentId` is propagated as `X-Agent-Id`Example:@@ -363,7 +365,7 @@ curl -X POST http://localhost:9867/tasks \"agentId": "my-agent","action": "click","tabId": "8f9c7d4e1234567890abcdef12345678",- "callbackUrl": "https://example.com/hooks/task-done"+ "callbackUrl": "https://pinchtab.com/hooks/task-done"}'```@@ -389,7 +391,7 @@ curl -X POST http://localhost:9867/tasks/batch \-H "Content-Type: application/json" \-d '{"agentId": "agent-crawl-01",- "callbackUrl": "https://example.com/hooks/batch",+ "callbackUrl": "https://pinchtab.com/hooks/batch","tasks": [{ "action": "click", "tabId": "TAB_ID", "params": { "selector": "#btn" } },{ "action": "scroll", "tabId": "TAB_ID", "params": { "scrollY": 400 } },diff --git a/docs/reference/snapshot.md b/docs/reference/snapshot.mdindex 4ece3ff2..435194df 100644--- a/docs/reference/snapshot.md+++ b/docs/reference/snapshot.md@@ -8,7 +8,7 @@ curl "http://localhost:9867/snapshot?filter=interactive"pinchtab snap -i# Response{- "url": "https://example.com",+ "url": "https://pinchtab.com","title": "Example Domain","nodes": [{diff --git a/docs/reference/tabs.md b/docs/reference/tabs.mdindex 82366afb..f9891af7 100644--- a/docs/reference/tabs.md+++ b/docs/reference/tabs.md@@ -104,7 +104,7 @@ pinchtab tab # list tabspinchtab tab 2 # focus tab by 1-based indexpinchtab tab 8f9c7d4e1234... # focus tab by tab IDpinchtab tab new # open blank tab-pinchtab tab new https://example.com # open and navigate+pinchtab tab new https://pinchtab.com # open and navigatepinchtab tab close 8f9c7d4e1234... # close tab```@@ -119,9 +119,9 @@ Use the tab-scoped HTTP route or the top-level CLI command with `--tab`.```bashcurl -X POST http://localhost:9867/tabs/<tabId>/navigate \-H "Content-Type: application/json" \- -d '{"url":"https://example.com"}'+ -d '{"url":"https://pinchtab.com"}'# CLI Alternative-pinchtab nav https://example.com --tab <tabId>+pinchtab nav https://pinchtab.com --tab <tabId>```### Snapshotdiff --git a/internal/activity/activity.go b/internal/activity/activity.goindex 8e5a858b..0825b52a 100644--- a/internal/activity/activity.go+++ b/internal/activity/activity.go@@ -150,18 +150,19 @@ func (s *Store) Record(evt Event) error {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)+ if shouldWritePrimaryLog(evt.Source) {+ if err := appendJSONL(s.filePathFor(evt.Timestamp), line); err != nil {+ return err+ }+ }+ if sourcePath := s.sourceFilePathFor(evt.Source, evt.Timestamp); sourcePath != "" {+ if err := appendJSONL(sourcePath, line); err != nil {+ return err+ }}return nil}@@ -174,7 +175,8 @@ func (s *Store) Query(filter Filter) ([]Event, error) {limit := clampQueryLimit(filter.Limit)var events []Event- for _, path := range s.queryFiles() {+ seen := make(map[string]struct{})+ for _, path := range s.queryFiles(filter.Source) {f, err := os.Open(path)if err != nil {if os.IsNotExist(err) {@@ -193,6 +195,11 @@ func (s *Store) Query(filter Filter) ([]Event, error) {if !filter.matches(evt) {continue}+ key := eventDedupKey(evt)+ if _, ok := seen[key]; ok {+ continue+ }+ seen[key] = struct{}{}if len(events) < limit {events = append(events, evt)continue@@ -317,7 +324,15 @@ 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 {+func (s *Store) sourceFilePathFor(source string, ts time.Time) string {+ source = normalizeSourceName(source)+ if source == "" {+ return ""+ }+ return filepath.Join(s.dir, fmt.Sprintf("events-%s-%s.jsonl", source, ts.UTC().Format(time.DateOnly)))+}++func (s *Store) queryFiles(source string) []string {_ = s.pruneExpiredFiles(time.Now().UTC())entries, err := os.ReadDir(s.dir)@@ -331,12 +346,16 @@ func (s *Store) queryFiles() []string {files = append(files, legacyPath)}+ source = normalizeSourceName(source)for _, entry := range entries {if entry.IsDir() {continue}name := entry.Name()- if !strings.HasPrefix(name, "events-") || !strings.HasSuffix(name, ".jsonl") {+ if !isActivityLogFile(name) {+ continue+ }+ if source == "" && !isPrimaryDailyActivityLog(name) {continue}files = append(files, filepath.Join(s.dir, name))@@ -377,11 +396,11 @@ func (s *Store) pruneExpiredFilesLocked(now time.Time) error {}continue}- if !strings.HasPrefix(name, "events-") || !strings.HasSuffix(name, ".jsonl") {+ if !isActivityLogFile(name) {continue}- day := strings.TrimSuffix(strings.TrimPrefix(name, "events-"), ".jsonl")- if len(day) != len(time.DateOnly) {+ day, ok := activityLogDay(name)+ if !ok {continue}if day < keepFrom {@@ -401,3 +420,82 @@ func randomID(prefix string) string {}return prefix + hex.EncodeToString(b)}++func appendJSONL(path string, line []byte) error {+ f, err := os.OpenFile(path, 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() }()+ if _, err := f.Write(append(line, '\n')); err != nil {+ return fmt.Errorf("write activity event: %w", err)+ }+ return nil+}++func shouldWritePrimaryLog(source string) bool {+ switch normalizeSourceName(source) {+ case "", "server", "bridge":+ return true+ default:+ return false+ }+}++func normalizeSourceName(source string) string {+ source = strings.ToLower(strings.TrimSpace(source))+ if source == "" {+ return ""+ }+ var b strings.Builder+ b.Grow(len(source))+ lastDash := false+ for _, r := range source {+ isAlphaNum := (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9')+ if isAlphaNum {+ b.WriteRune(r)+ lastDash = false+ continue+ }+ if !lastDash {+ b.WriteByte('-')+ lastDash = true+ }+ }+ return strings.Trim(b.String(), "-")+}++func isActivityLogFile(name string) bool {+ return name != "events.jsonl" && strings.HasPrefix(name, "events-") && strings.HasSuffix(name, ".jsonl")+}++func isPrimaryDailyActivityLog(name string) bool {+ if !isActivityLogFile(name) {+ return false+ }+ middle := strings.TrimSuffix(strings.TrimPrefix(name, "events-"), ".jsonl")+ return len(middle) == len(time.DateOnly)+}++func activityLogDay(name string) (string, bool) {+ if !isActivityLogFile(name) {+ return "", false+ }+ middle := strings.TrimSuffix(strings.TrimPrefix(name, "events-"), ".jsonl")+ if len(middle) < len(time.DateOnly) {+ return "", false+ }+ day := middle[len(middle)-len(time.DateOnly):]+ if len(day) != len(time.DateOnly) {+ return "", false+ }+ return day, true+}++func eventDedupKey(evt Event) string {+ data, err := json.Marshal(evt)+ if err != nil {+ return fmt.Sprintf("%s|%s|%s|%s|%d", evt.Timestamp.UTC().Format(time.RFC3339Nano), evt.Source, evt.Method, evt.Path, evt.Status)+ }+ return string(data)+}diff --git a/internal/activity/activity_test.go b/internal/activity/activity_test.goindex a5a374cc..63497512 100644--- a/internal/activity/activity_test.go+++ b/internal/activity/activity_test.go@@ -4,6 +4,7 @@ import ("encoding/json""os""path/filepath"+ "strings""testing""time")@@ -60,6 +61,79 @@ func TestStoreWritesJSONLFile(t *testing.T) {}}+func TestStorePartitionsDashboardEventsOutsidePrimaryLog(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: "dashboard",+ Method: "GET",+ Path: "/api/events",+ Status: 200,+ }); err != nil {+ t.Fatalf("Record dashboard: %v", err)+ }+ if err := store.Record(Event{+ Timestamp: now.Add(time.Second),+ Source: "server",+ Method: "GET",+ Path: "/health",+ Status: 200,+ }); err != nil {+ t.Fatalf("Record server: %v", err)+ }++ mainPath := filepath.Join(root, "activity", "events-"+now.Format(time.DateOnly)+".jsonl")+ mainData, err := os.ReadFile(mainPath)+ if err != nil {+ t.Fatalf("ReadFile main: %v", err)+ }+ if strings.Contains(string(mainData), "\"source\":\"dashboard\"") {+ t.Fatal("primary activity log should not include dashboard events")+ }+ if !strings.Contains(string(mainData), "\"source\":\"server\"") {+ t.Fatal("primary activity log should include server events")+ }++ dashboardPath := filepath.Join(root, "activity", "events-dashboard-"+now.Format(time.DateOnly)+".jsonl")+ dashboardData, err := os.ReadFile(dashboardPath)+ if err != nil {+ t.Fatalf("ReadFile dashboard: %v", err)+ }+ if !strings.Contains(string(dashboardData), "\"source\":\"dashboard\"") {+ t.Fatal("dashboard activity log missing dashboard event")+ }++ gotMain, err := store.Query(Filter{Limit: 10})+ if err != nil {+ t.Fatalf("Query main: %v", err)+ }+ if len(gotMain) != 1 || gotMain[0].Source != "server" {+ t.Fatalf("main query = %#v, want only external server event", gotMain)+ }++ gotDashboard, err := store.Query(Filter{Source: "dashboard", Limit: 10})+ if err != nil {+ t.Fatalf("Query dashboard: %v", err)+ }+ if len(gotDashboard) != 1 || gotDashboard[0].Source != "dashboard" {+ t.Fatalf("dashboard query = %#v, want dashboard event", gotDashboard)+ }++ gotServer, err := store.Query(Filter{Source: "server", Limit: 10})+ if err != nil {+ t.Fatalf("Query server: %v", err)+ }+ if len(gotServer) != 1 || gotServer[0].Source != "server" {+ t.Fatalf("server query = %#v, want one deduplicated server event", gotServer)+ }+}+func TestStorePrunesExpiredDailyFiles(t *testing.T) {root := t.TempDir()store, err := NewStore(root, 30*time.Minute, 1)@@ -124,6 +198,37 @@ func TestNewStorePrunesExpiredDailyFilesOnStartup(t *testing.T) {}}+func TestNewStorePrunesExpiredSourceSpecificDailyFilesOnStartup(t *testing.T) {+ root := t.TempDir()+ activityDir := filepath.Join(root, "activity")+ if err := os.MkdirAll(activityDir, 0750); err != nil {+ t.Fatalf("MkdirAll: %v", err)+ }++ oldDay := time.Now().UTC().AddDate(0, 0, -31)+ oldPath := filepath.Join(activityDir, "events-dashboard-"+oldDay.Format(time.DateOnly)+".jsonl")+ if err := os.WriteFile(oldPath, []byte("{\"source\":\"dashboard\"}\n"), 0600); err != nil {+ t.Fatalf("WriteFile old: %v", err)+ }++ keepDay := time.Now().UTC()+ keepPath := filepath.Join(activityDir, "events-dashboard-"+keepDay.Format(time.DateOnly)+".jsonl")+ if err := os.WriteFile(keepPath, []byte("{\"source\":\"dashboard\"}\n"), 0600); err != nil {+ t.Fatalf("WriteFile keep: %v", err)+ }++ if _, err := NewStore(root, 30*time.Minute, 30); err != nil {+ t.Fatalf("NewStore: %v", err)+ }++ if _, err := os.Stat(oldPath); !os.IsNotExist(err) {+ t.Fatalf("expected expired source-specific activity file to be pruned, stat err = %v", err)+ }+ if _, err := os.Stat(keepPath); err != nil {+ t.Fatalf("expected current source-specific activity file to remain, stat err = %v", err)+ }+}+func TestNewRecorderDisabledReturnsNoop(t *testing.T) {rec, err := NewRecorder(Config{}, t.TempDir())if err != nil {@@ -185,3 +290,21 @@ func TestStoreRecord_SanitizesURLBeforePersisting(t *testing.T) {t.Fatalf("evt.URL = %q, want sanitized URL", evt.URL)}}++func TestNormalizeSourceName(t *testing.T) {+ tests := []struct {+ in string+ want string+ }{+ {in: "dashboard", want: "dashboard"},+ {in: " Dashboard UI ", want: "dashboard-ui"},+ {in: "mcp/agent", want: "mcp-agent"},+ {in: "___", want: ""},+ }++ for _, tt := range tests {+ if got := normalizeSourceName(tt.in); got != tt.want {+ t.Fatalf("normalizeSourceName(%q) = %q, want %q", tt.in, got, tt.want)+ }+ }+}diff --git a/internal/activity/context.go b/internal/activity/context.goindex 6632483b..da2a39ef 100644--- a/internal/activity/context.go+++ b/internal/activity/context.go@@ -13,7 +13,6 @@ import (const (HeaderAgentID = "X-Agent-Id"- HeaderPTAgentID = "X-PinchTab-Agent-Id"HeaderPTActorID = "X-PinchTab-Actor-Id"HeaderPTSessionID = "X-PinchTab-Session-Id"HeaderPTSource = "X-PinchTab-Source"@@ -176,7 +175,7 @@ func PropagateHeaders(ctx context.Context, req *http.Request) {req.Header.Set(HeaderPTActorID, evt.ActorID)}if evt.AgentID != "" {- req.Header.Set(HeaderPTAgentID, evt.AgentID)+ req.Header.Set(HeaderAgentID, evt.AgentID)}if evt.SessionID != "" {req.Header.Set(HeaderPTSessionID, evt.SessionID)@@ -215,10 +214,8 @@ func actorIDFor(r *http.Request) string {}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- }+ if value := strings.TrimSpace(r.Header.Get(HeaderAgentID)); value != "" {+ return value}return ""}diff --git a/internal/activity/context_test.go b/internal/activity/context_test.goindex a40fc73d..5efb28a7 100644--- a/internal/activity/context_test.go+++ b/internal/activity/context_test.go@@ -1,6 +1,7 @@package activityimport (+ "context""net/http""net/http/httptest""net/url"@@ -161,3 +162,40 @@ func TestMiddlewarePrefersExplicitSourceHeaderOverCookieAuth(t *testing.T) {t.Fatalf("event.Source = %q, want mcp", got)}}++func TestMiddlewareUsesAgentIDHeader(t *testing.T) {+ rec := &captureRecorder{}+ handler := Middleware(rec, "server", http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusNoContent)+ }))++ req := httptest.NewRequest(http.MethodGet, "/health", nil)+ req.Header.Set(HeaderAgentID, "agent-main")+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)++ if len(rec.events) != 1 {+ t.Fatalf("len(events) = %d, want 1", len(rec.events))+ }+ if got := rec.events[0].AgentID; got != "agent-main" {+ t.Fatalf("event.AgentID = %q, want agent-main", got)+ }+}++func TestPropagateHeadersUsesAgentIDHeader(t *testing.T) {+ req := httptest.NewRequest(http.MethodGet, "/health", nil)+ state := &requestState{event: Event{+ AgentID: "agent-main",+ RequestID: "req-1",+ }}++ proxyReq := httptest.NewRequest(http.MethodGet, "http://example.test/health", nil)+ PropagateHeaders(context.WithValue(req.Context(), requestStateKey{}, state), proxyReq)++ if got := proxyReq.Header.Get(HeaderAgentID); got != "agent-main" {+ t.Fatalf("X-Agent-Id = %q, want agent-main", got)+ }+ if got := proxyReq.Header.Get("X-PinchTab-Agent-Id"); got != "" {+ t.Fatalf("X-PinchTab-Agent-Id = %q, want empty", got)+ }+}diff --git a/internal/config/config_file.go b/internal/config/config_file.goindex f9c2f895..a61722de 100644--- a/internal/config/config_file.go+++ b/internal/config/config_file.go@@ -112,6 +112,7 @@ func DefaultFileConfig() FileConfig {Enabled: &activityEnabled,SessionIdleSec: &activitySessionIdleSec,RetentionDays: &activityRetentionDays,+ StateDir: "",},},Sessions: SessionsFileConfig{@@ -255,9 +256,10 @@ type observabilityFileConfigJSON struct {}type activityConfigJSON struct {- Enabled *bool `json:"enabled"`- SessionIdleSec *int `json:"sessionIdleSec"`- RetentionDays *int `json:"retentionDays"`+ Enabled *bool `json:"enabled"`+ SessionIdleSec *int `json:"sessionIdleSec"`+ RetentionDays *int `json:"retentionDays"`+ StateDir string `json:"stateDir"`}type sessionsFileConfigJSON struct {@@ -399,6 +401,7 @@ func (fc FileConfig) MarshalJSON() ([]byte, error) {Enabled: fc.Observability.Activity.Enabled,SessionIdleSec: fc.Observability.Activity.SessionIdleSec,RetentionDays: fc.Observability.Activity.RetentionDays,+ StateDir: fc.Observability.Activity.StateDir,},},Sessions: sessionsFileConfigJSON{@@ -462,6 +465,7 @@ func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {activityEnabled := cfg.Observability.Activity.EnabledactivitySessionIdleSec := cfg.Observability.Activity.SessionIdleSecactivityRetentionDays := cfg.Observability.Activity.RetentionDays+ activityStateDir := cfg.Observability.Activity.StateDirdashboardSessionPersist := cfg.Sessions.Dashboard.PersistdashboardSessionIdleSec := int(cfg.Sessions.Dashboard.IdleTimeout / time.Second)dashboardSessionMaxLifetimeSec := int(cfg.Sessions.Dashboard.MaxLifetime / time.Second)@@ -561,6 +565,7 @@ func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {Enabled: &activityEnabled,SessionIdleSec: &activitySessionIdleSec,RetentionDays: &activityRetentionDays,+ StateDir: activityStateDir,},},Sessions: SessionsFileConfig{diff --git a/internal/config/config_file_test.go b/internal/config/config_file_test.goindex 98fd53af..c012f461 100644--- a/internal/config/config_file_test.go+++ b/internal/config/config_file_test.go@@ -88,6 +88,9 @@ func TestDefaultFileConfig(t *testing.T) {if fc.Sessions.Dashboard.RequireElevation == nil || *fc.Sessions.Dashboard.RequireElevation {t.Errorf("DefaultFileConfig.Sessions.Dashboard.RequireElevation = %v, want explicit false", formatBoolPtr(fc.Sessions.Dashboard.RequireElevation))}+ if fc.Observability.Activity.StateDir != "" {+ t.Errorf("DefaultFileConfig.Observability.Activity.StateDir = %q, want empty string", fc.Observability.Activity.StateDir)+ }}// TestIsLegacyConfig tests the format detection logic.@@ -235,6 +238,9 @@ func TestDefaultFileConfigJSON(t *testing.T) {if parsed.Security.Attach.Enabled == nil || *parsed.Security.Attach.Enabled {t.Errorf("round-trip Security.Attach.Enabled = %v, want explicit false", formatBoolPtr(parsed.Security.Attach.Enabled))}+ if parsed.Observability.Activity.StateDir != "" {+ t.Errorf("round-trip Observability.Activity.StateDir = %q, want empty string", parsed.Observability.Activity.StateDir)+ }if !parsed.Security.IDPI.Enabled {t.Errorf("round-trip Security.IDPI.Enabled = %v, want true", parsed.Security.IDPI.Enabled)}diff --git a/internal/config/config_load.go b/internal/config/config_load.goindex eac493d8..e924a1a6 100644--- a/internal/config/config_load.go+++ b/internal/config/config_load.go@@ -93,6 +93,7 @@ func Load() *RuntimeConfig {Enabled: true,SessionIdleSec: 1800,RetentionDays: 1,+ StateDir: "",},},@@ -261,6 +262,9 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {if fc.Observability.Activity.RetentionDays != nil {cfg.Observability.Activity.RetentionDays = *fc.Observability.Activity.RetentionDays}+ if fc.Observability.Activity.StateDir != "" {+ cfg.Observability.Activity.StateDir = fc.Observability.Activity.StateDir+ }if fc.Sessions.Dashboard.Persist != nil {cfg.Sessions.Dashboard.Persist = *fc.Sessions.Dashboard.Persist}diff --git a/internal/config/config_load_test.go b/internal/config/config_load_test.goindex 23e6ea3b..28d03f15 100644--- a/internal/config/config_load_test.go+++ b/internal/config/config_load_test.go@@ -197,6 +197,45 @@ func TestConfigFileWithNestedValues(t *testing.T) {}}+func TestLoadConfigActivityStateDir(t *testing.T) {+ clearConfigEnvVars(t)++ tmpDir := t.TempDir()+ configPath := filepath.Join(tmpDir, "config.json")+ sharedActivityDir := filepath.Join(tmpDir, "shared-activity")+ _ = os.Setenv("PINCHTAB_CONFIG", configPath)+ defer func() { _ = os.Unsetenv("PINCHTAB_CONFIG") }()++ if err := os.WriteFile(configPath, []byte(`{+ "server": {+ "stateDir": "/tmp/profile-state"+ },+ "observability": {+ "activity": {+ "stateDir": "`+sharedActivityDir+`"+ }+ }+ }`), 0644); err != nil {+ t.Fatal(err)+ }++ cfg := Load()+ if cfg.Observability.Activity.StateDir != sharedActivityDir {+ t.Fatalf("Observability.Activity.StateDir = %q, want %q", cfg.Observability.Activity.StateDir, sharedActivityDir)+ }+ if cfg.ActivityStateDir() != sharedActivityDir {+ t.Fatalf("ActivityStateDir() = %q, want %q", cfg.ActivityStateDir(), sharedActivityDir)+ }+}++func TestRuntimeConfigActivityStateDirFallsBackToStateDir(t *testing.T) {+ cfg := &RuntimeConfig{StateDir: "/tmp/pinchtab-state"}++ if got := cfg.ActivityStateDir(); got != "/tmp/pinchtab-state" {+ t.Fatalf("ActivityStateDir() = %q, want %q", got, "/tmp/pinchtab-state")+ }+}+func TestLoadConfigEngineFromFile(t *testing.T) {clearConfigEnvVars(t)diff --git a/internal/config/config_methods.go b/internal/config/config_methods.goindex 54e1fe13..f2838986 100644--- a/internal/config/config_methods.go+++ b/internal/config/config_methods.go@@ -25,3 +25,15 @@ func (cfg *RuntimeConfig) EnabledSensitiveEndpoints() []string {}return enabled}++// ActivityStateDir returns the directory root used for activity log storage.+// When unset, activity logs live under the main server state directory.+func (cfg *RuntimeConfig) ActivityStateDir() string {+ if cfg == nil {+ return ""+ }+ if cfg.Observability.Activity.StateDir != "" {+ return cfg.Observability.Activity.StateDir+ }+ return cfg.StateDir+}diff --git a/internal/config/config_types.go b/internal/config/config_types.goindex c0c19d81..4d0566f0 100644--- a/internal/config/config_types.go+++ b/internal/config/config_types.go@@ -154,9 +154,10 @@ type ObservabilityConfig struct {}type ActivityConfig struct {- Enabled bool `json:"enabled,omitempty"`- SessionIdleSec int `json:"sessionIdleSec,omitempty"`- RetentionDays int `json:"retentionDays,omitempty"`+ Enabled bool `json:"enabled,omitempty"`+ SessionIdleSec int `json:"sessionIdleSec,omitempty"`+ RetentionDays int `json:"retentionDays,omitempty"`+ StateDir string `json:"stateDir,omitempty"`}// FileConfig is the persistent configuration written to disk.@@ -292,9 +293,10 @@ type ObservabilityFileConfig struct {}type ActivityFileConfig struct {- Enabled *bool `json:"enabled,omitempty"`- SessionIdleSec *int `json:"sessionIdleSec,omitempty"`- RetentionDays *int `json:"retentionDays,omitempty"`+ Enabled *bool `json:"enabled,omitempty"`+ SessionIdleSec *int `json:"sessionIdleSec,omitempty"`+ RetentionDays *int `json:"retentionDays,omitempty"`+ StateDir string `json:"stateDir,omitempty"`}// AutoSolverFileConfig is the persistent configuration for the autosolver system.diff --git a/internal/dashboard/dashboard.go b/internal/dashboard/dashboard.goindex f3bcd6fc..14cc6c8d 100644--- a/internal/dashboard/dashboard.go+++ b/internal/dashboard/dashboard.go@@ -62,10 +62,15 @@ type Dashboard struct {agents map[string]*apiTypes.AgentrecentEvents []apiTypes.ActivityEventmaxEvents int+ seenEventIDs map[string]struct{}+ seenEventLog []string+ maxSeenIDs intmu sync.RWMutex}+const persistedAgentBootstrapLimit = 1000+// BroadcastSystemEvent sends a system event to all SSE clients.func (d *Dashboard) BroadcastSystemEvent(evt SystemEvent) {d.mu.RLock()@@ -127,6 +132,9 @@ func (d *Dashboard) RecordActivityEvent(evt activity.Event) {if evt.Engine != "" {details["engine"] = evt.Engine}+ if evt.Action != "" {+ details["action"] = evt.Action+ }d.RecordEvent(apiTypes.ActivityEvent{ID: evt.RequestID,@@ -156,6 +164,11 @@ func (d *Dashboard) RecordEvent(evt apiTypes.ActivityEvent) {}d.mu.Lock()+ if _, ok := d.seenEventIDs[evt.ID]; ok {+ d.mu.Unlock()+ return+ }+ d.rememberEventIDLocked(evt.ID)d.upsertAgentLocked(evt)if len(d.recentEvents) >= d.maxEvents {copy(d.recentEvents, d.recentEvents[1:])@@ -251,6 +264,45 @@ func (d *Dashboard) EventsForAgent(agentID, mode string) []apiTypes.ActivityEvenreturn out}+// IngestPersistedAgentActivity loads new agent-tagged requests from the shared+// activity store into the live dashboard cache.+func (d *Dashboard) IngestPersistedAgentActivity(rec activity.Recorder, since time.Time) (time.Time, error) {+ if d == nil || rec == nil || !rec.Enabled() {+ return since, nil+ }++ events, err := rec.Query(activity.Filter{+ Since: since,+ Limit: persistedAgentBootstrapLimit,+ })+ if err != nil {+ return since, err+ }++ latest := since+ for _, evt := range events {+ if evt.Timestamp.After(latest) {+ latest = evt.Timestamp+ }+ if strings.TrimSpace(evt.AgentID) == "" {+ continue+ }+ if !shouldTrackPersistedAgentActivity(evt) {+ continue+ }+ d.RecordActivityEvent(evt)+ }++ return latest, nil+}++// LoadPersistedAgentActivity rebuilds the in-memory agent summaries and recent+// tool-call history from the persisted activity log on server startup.+func (d *Dashboard) LoadPersistedAgentActivity(rec activity.Recorder) error {+ _, err := d.IngestPersistedAgentActivity(rec, time.Time{})+ return err+}+func NewDashboard(cfg *DashboardConfig) *Dashboard {c := DashboardConfig{IdleTimeout: 30 * time.Second,@@ -283,6 +335,9 @@ func NewDashboard(cfg *DashboardConfig) *Dashboard {agents: make(map[string]*apiTypes.Agent),recentEvents: make([]apiTypes.ActivityEvent, 0, 200),maxEvents: 200,+ seenEventIDs: make(map[string]struct{}),+ seenEventLog: make([]string, 0, 2000),+ maxSeenIDs: 2000,}}@@ -522,6 +577,24 @@ func matchesMode(mode, channel string) bool {}}+func shouldTrackPersistedAgentActivity(evt activity.Event) bool {+ return strings.TrimSpace(evt.AgentID) != ""+}++func (d *Dashboard) rememberEventIDLocked(id string) {+ if id == "" {+ return+ }+ d.seenEventIDs[id] = struct{}{}+ d.seenEventLog = append(d.seenEventLog, id)+ if len(d.seenEventLog) <= d.maxSeenIDs {+ return+ }+ evicted := d.seenEventLog[0]+ d.seenEventLog = d.seenEventLog[1:]+ delete(d.seenEventIDs, evicted)+}+func classifyActivityType(evt activity.Event) string {if evt.Action != "" {switch evt.Action {diff --git a/internal/dashboard/dashboard_test.go b/internal/dashboard/dashboard_test.goindex b4f88240..3f1df102 100644--- a/internal/dashboard/dashboard_test.go+++ b/internal/dashboard/dashboard_test.go@@ -8,9 +8,22 @@ import ("testing""time"+ "github.com/pinchtab/pinchtab/internal/activity"apiTypes "github.com/pinchtab/pinchtab/internal/api/types")+type stubActivityRecorder struct {+ events []activity.Event+}++func (s stubActivityRecorder) Enabled() bool { return true }++func (s stubActivityRecorder) Record(activity.Event) error { return nil }++func (s stubActivityRecorder) Query(activity.Filter) ([]activity.Event, error) {+ return s.events, nil+}+func TestNewDashboard(t *testing.T) {d := NewDashboard(nil)if d == nil {@@ -214,6 +227,129 @@ func TestDashboardHandleAgentEventsByIDUsesRouteAgent(t *testing.T) {}}+func TestDashboardLoadPersistedAgentActivityRestoresAgentsAndEvents(t *testing.T) {+ d := NewDashboard(nil)+ now := time.Now().UTC()++ err := d.LoadPersistedAgentActivity(stubActivityRecorder{+ events: []activity.Event{+ {+ Timestamp: now.Add(-2 * time.Minute),+ Source: "bridge",+ RequestID: "req-1",+ AgentID: "agent-1",+ Method: http.MethodPost,+ Path: "/tabs/tab_1/action",+ Status: http.StatusOK,+ DurationMs: 11,+ TabID: "tab_1",+ Action: "click",+ },+ {+ Timestamp: now.Add(-1 * time.Minute),+ Source: "bridge",+ RequestID: "req-2",+ Method: http.MethodGet,+ Path: "/health",+ Status: http.StatusOK,+ DurationMs: 4,+ },+ {+ Timestamp: now,+ Source: "server",+ RequestID: "req-3",+ AgentID: "agent-2",+ Method: http.MethodGet,+ Path: "/tabs/tab_2/text",+ Status: http.StatusOK,+ DurationMs: 8,+ TabID: "tab_2",+ },+ },+ })+ if err != nil {+ t.Fatalf("LoadPersistedAgentActivity() error = %v", err)+ }++ agents := d.Agents()+ if len(agents) != 2 {+ t.Fatalf("Agents() len = %d, want 2", len(agents))+ }++ events := d.RecentEvents()+ if len(events) != 2 {+ t.Fatalf("RecentEvents() len = %d, want 2", len(events))+ }+ if events[0].ID != "req-1" || events[1].ID != "req-3" {+ t.Fatalf("RecentEvents() IDs = [%s, %s], want [req-1, req-3]", events[0].ID, events[1].ID)+ }+}++func TestDashboardIngestPersistedAgentActivityAddsNewEventsWithoutDuplicatingLiveOnes(t *testing.T) {+ d := NewDashboard(nil)+ now := time.Now().UTC()++ d.RecordActivityEvent(activity.Event{+ Timestamp: now.Add(-2 * time.Second),+ Source: "bridge",+ RequestID: "req-live",+ AgentID: "agent-1",+ Method: http.MethodPost,+ Path: "/tabs/tab_1/action",+ Status: http.StatusOK,+ DurationMs: 12,+ TabID: "tab_1",+ Action: "click",+ })++ latest, err := d.IngestPersistedAgentActivity(stubActivityRecorder{+ events: []activity.Event{+ {+ Timestamp: now.Add(-2 * time.Second),+ Source: "bridge",+ RequestID: "req-live",+ AgentID: "agent-1",+ Method: http.MethodPost,+ Path: "/tabs/tab_1/action",+ Status: http.StatusOK,+ DurationMs: 12,+ TabID: "tab_1",+ Action: "click",+ },+ {+ Timestamp: now,+ Source: "bridge",+ RequestID: "req-new",+ AgentID: "agent-2",+ Method: http.MethodGet,+ Path: "/tabs/tab_2/text",+ Status: http.StatusOK,+ DurationMs: 7,+ TabID: "tab_2",+ },+ },+ }, now.Add(-5*time.Second))+ if err != nil {+ t.Fatalf("IngestPersistedAgentActivity() error = %v", err)+ }+ if !latest.Equal(now) {+ t.Fatalf("latest = %v, want %v", latest, now)+ }++ events := d.RecentEvents()+ if len(events) != 2 {+ t.Fatalf("RecentEvents() len = %d, want 2", len(events))+ }+ if events[0].ID != "req-live" || events[1].ID != "req-new" {+ t.Fatalf("RecentEvents() IDs = [%s, %s], want [req-live, req-new]", events[0].ID, events[1].ID)+ }++ agents := d.Agents()+ if len(agents) != 2 {+ t.Fatalf("Agents() len = %d, want 2", len(agents))+ }+}+func TestMatchesMode(t *testing.T) {tests := []struct {mode stringdiff --git a/internal/handlers/middleware.go b/internal/handlers/middleware.goindex 2612e24a..207f3ba3 100644--- a/internal/handlers/middleware.go+++ b/internal/handlers/middleware.go@@ -375,6 +375,11 @@ const (func RateLimitMiddleware(next http.Handler) http.Handler {startRateLimiterJanitor(rateLimitWindow, evictionInterval)return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if isLongLivedStreamRequest(r) {+ next.ServeHTTP(w, r)+ return+ }+host := authn.ClientIP(r)now := time.Now()@@ -400,6 +405,23 @@ func RateLimitMiddleware(next http.Handler) http.Handler {})}+func isLongLivedStreamRequest(r *http.Request) bool {+ if r == nil || r.Method != http.MethodGet {+ return false+ }+ path := strings.TrimSpace(r.URL.Path)+ switch {+ case path == "/api/events":+ return true+ case strings.HasPrefix(path, "/api/agents/") && strings.HasSuffix(path, "/events"):+ return true+ case strings.HasPrefix(path, "/instances/") && strings.HasSuffix(path, "/logs/stream"):+ return true+ default:+ return false+ }+}+func startRateLimiterJanitor(window, interval time.Duration) {rateLimiterStarted.Do(func() {go func() {diff --git a/internal/handlers/middleware_test.go b/internal/handlers/middleware_test.goindex 661e6aa7..ef30e9fa 100644--- a/internal/handlers/middleware_test.go+++ b/internal/handlers/middleware_test.go@@ -835,6 +835,32 @@ func TestRateLimitMiddleware_RateLimitsHealthAndMetrics(t *testing.T) {}}+func TestRateLimitMiddleware_DoesNotRateLimitStreamingEndpoints(t *testing.T) {+ resetRateLimitStateForTests()+ t.Cleanup(resetRateLimitStateForTests)++ handler := RateLimitMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusOK)+ }))++ for _, p := range []string{+ "/api/events",+ "/api/agents/agent-1/events",+ "/instances/inst-1/logs/stream",+ } {+ resetRateLimitStateForTests()+ for i := 0; i < rateLimitMaxReq+5; i++ {+ req := httptest.NewRequest(http.MethodGet, p, nil)+ req.RemoteAddr = "127.0.0.1:12345"+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("%s request %d: expected 200, got %d", p, i+1, w.Code)+ }+ }+ }+}+func TestRateLimitMiddleware_IgnoresSpoofedForwardedHeaders(t *testing.T) {resetRateLimitStateForTests()t.Cleanup(resetRateLimitStateForTests)diff --git a/internal/orchestrator/health.go b/internal/orchestrator/health.goindex c9a7146e..94be7ef5 100644--- a/internal/orchestrator/health.go+++ b/internal/orchestrator/health.go@@ -9,12 +9,15 @@ import ("net/url""strings""time"++ "github.com/pinchtab/pinchtab/internal/activity")const (instanceHealthPollInterval = 500 * time.MillisecondinstanceStartupTimeout = 45 * time.SecondattachedBridgeHealthPollInterval = 60 * time.Second+ orchestratorActivitySource = "orchestrator")type healthProbePolicy int@@ -66,6 +69,7 @@ func (o *Orchestrator) monitor(inst *InstanceInternal) {lastProbe = fmt.Sprintf("%s -> %s", baseURL, reqErr.Error())continue}+ tagOrchestratorMonitoringRequest(req)o.applyInstanceAuth(req, inst)resp, err := o.client.Do(req)if err == nil {@@ -212,6 +216,7 @@ func (o *Orchestrator) probeInstanceHealth(inst *InstanceInternal) (bool, stringlastProbe = fmt.Sprintf("%s -> %s", baseURL, reqErr.Error())continue}+ tagOrchestratorMonitoringRequest(req)o.applyInstanceAuth(req, inst)resp, err := o.client.Do(req)if err != nil {@@ -255,6 +260,7 @@ func (o *Orchestrator) fetchTabs(inst *InstanceInternal) ([]remoteTab, error) {if err != nil {return nil, err}+ tagOrchestratorMonitoringRequest(req)o.applyInstanceAuth(req, inst)resp, err := o.client.Do(req)@@ -285,6 +291,7 @@ func (o *Orchestrator) fetchMetrics(inst *InstanceInternal) (*memoryMetrics, errif err != nil {return nil, err}+ tagOrchestratorMonitoringRequest(req)o.applyInstanceAuth(req, inst)resp, err := o.client.Do(req)@@ -304,6 +311,13 @@ func (o *Orchestrator) fetchMetrics(inst *InstanceInternal) (*memoryMetrics, errreturn result.Memory, nil}+func tagOrchestratorMonitoringRequest(req *http.Request) {+ if req == nil {+ return+ }+ req.Header.Set(activity.HeaderPTSource, orchestratorActivitySource)+}+func isInstanceHealthyStatus(code int) bool {return code > 0 && code < http.StatusInternalServerError}diff --git a/internal/orchestrator/health_test.go b/internal/orchestrator/health_test.goindex 52e8a419..cb4e28af 100644--- a/internal/orchestrator/health_test.go+++ b/internal/orchestrator/health_test.go@@ -136,3 +136,92 @@ func TestProbeInstanceHealth_RejectsUnsupportedScheme(t *testing.T) {t.Fatalf("lastProbe = %q, want invalid HTTP bridge message", lastProbe)}}++func TestProbeInstanceHealth_TagsBridgeHealthProbeAsOrchestrator(t *testing.T) {+ o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})+ o.ApplyRuntimeConfig(&config.RuntimeConfig{+ AttachEnabled: true,+ AttachAllowHosts: []string{"10.0.0.8"},+ AttachAllowSchemes: []string{"http"},+ })++ var source string+ o.client = &http.Client{+ Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {+ source = req.Header.Get("X-PinchTab-Source")+ return &http.Response{+ StatusCode: http.StatusOK,+ Body: io.NopCloser(strings.NewReader("")),+ Header: make(http.Header),+ }, nil+ }),+ }++ healthy, _, _ := o.probeInstanceHealth(&InstanceInternal{+ Instance: bridge.Instance{+ Attached: true,+ AttachType: "bridge",+ },+ URL: "http://10.0.0.8:9868",+ })+ if !healthy {+ t.Fatal("expected probe to succeed")+ }+ if source != "orchestrator" {+ t.Fatalf("X-PinchTab-Source = %q, want orchestrator", source)+ }+}++func TestFetchTabs_TagsBridgeRequestAsOrchestrator(t *testing.T) {+ o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})++ var source string+ o.client = &http.Client{+ Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {+ source = req.Header.Get("X-PinchTab-Source")+ return &http.Response{+ StatusCode: http.StatusOK,+ Body: io.NopCloser(strings.NewReader(`{"tabs":[]}`)),+ Header: make(http.Header),+ }, nil+ }),+ }++ _, err := o.fetchTabs(&InstanceInternal{+ Instance: bridge.Instance{ID: "inst-1"},+ URL: "http://127.0.0.1:9868",+ })+ if err != nil {+ t.Fatalf("fetchTabs() error = %v", err)+ }+ if source != "orchestrator" {+ t.Fatalf("X-PinchTab-Source = %q, want orchestrator", source)+ }+}++func TestFetchMetrics_TagsBridgeRequestAsOrchestrator(t *testing.T) {+ o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})++ var source string+ o.client = &http.Client{+ Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {+ source = req.Header.Get("X-PinchTab-Source")+ return &http.Response{+ StatusCode: http.StatusOK,+ Body: io.NopCloser(strings.NewReader(`{"memory":{"jsHeapUsedMB":1}}`)),+ Header: make(http.Header),+ }, nil+ }),+ }++ _, err := o.fetchMetrics(&InstanceInternal{+ Instance: bridge.Instance{ID: "inst-1"},+ URL: "http://127.0.0.1:9868",+ })+ if err != nil {+ t.Fatalf("fetchMetrics() error = %v", err)+ }+ if source != "orchestrator" {+ t.Fatalf("X-PinchTab-Source = %q, want orchestrator", source)+ }+}diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.goindex 396c5317..a1d90f59 100644--- a/internal/orchestrator/orchestrator.go+++ b/internal/orchestrator/orchestrator.go@@ -374,6 +374,9 @@ func (o *Orchestrator) writeChildConfig(port string, cdpPort int, profilePath, ifc := config.FileConfigFromRuntime(o.runtimeCfg)fc.Server.Port = portfc.Server.StateDir = instanceStateDir+ if o.runtimeCfg != nil {+ fc.Observability.Activity.StateDir = o.runtimeCfg.ActivityStateDir()+ }fc.Browser.ChromeDebugPort = intPtr(cdpPort)fc.Profiles.BaseDir = filepath.Dir(profilePath)fc.Profiles.DefaultProfile = filepath.Base(profilePath)diff --git a/internal/orchestrator/orchestrator_test.go b/internal/orchestrator/orchestrator_test.goindex 1aa1b705..a0e7e3a9 100644--- a/internal/orchestrator/orchestrator_test.go+++ b/internal/orchestrator/orchestrator_test.go@@ -7,6 +7,7 @@ import ("net/http/httptest""net/url""os"+ "path/filepath""strconv""strings""testing"@@ -312,6 +313,50 @@ func TestOrchestrator_Launch_ExplicitPortAlsoReservesDistinctChromeDebugPort(t *}}+func TestOrchestrator_Launch_ChildConfigKeepsSharedActivityStateDir(t *testing.T) {+ old := processAliveFunc+ processAliveFunc = func(pid int) bool { return pid > 0 }+ defer func() { processAliveFunc = old }()+ stubPortAvailability(t, func(int) bool { return true })++ root := t.TempDir()+ runner := &mockRunner{portAvail: true}+ o := NewOrchestratorWithRunner(root, runner)+ sharedActivityStateDir := filepath.Join(root, "dashboard-state")+ o.ApplyRuntimeConfig(&config.RuntimeConfig{+ StateDir: sharedActivityStateDir,+ InstancePortStart: 9930,+ InstancePortEnd: 9933,+ })++ inst, err := o.Launch("profile1", "", true, nil)+ if err != nil {+ t.Fatalf("Launch failed: %v", err)+ }++ cfgPath := envMap(runner.env)["PINCHTAB_CONFIG"]+ data, err := os.ReadFile(cfgPath)+ if err != nil {+ t.Fatalf("ReadFile(%q) error = %v", cfgPath, err)+ }++ var fc config.FileConfig+ if err := json.Unmarshal(data, &fc); err != nil {+ t.Fatalf("Unmarshal child config error = %v", err)+ }++ wantChildStateDir := filepath.Join(root, "profile1", ".pinchtab-state")+ if fc.Server.StateDir != wantChildStateDir {+ t.Fatalf("child Server.StateDir = %q, want %q", fc.Server.StateDir, wantChildStateDir)+ }+ if fc.Observability.Activity.StateDir != sharedActivityStateDir {+ t.Fatalf("child Observability.Activity.StateDir = %q, want %q", fc.Observability.Activity.StateDir, sharedActivityStateDir)+ }+ if inst.Port != "9930" {+ t.Fatalf("bridge port = %s, want 9930", inst.Port)+ }+}+func TestOrchestrator_Stop_ReleasesBridgeAndChromeDebugPorts(t *testing.T) {old := processAliveFuncprocessAliveFunc = func(pid int) bool { return false }diff --git a/internal/profiles/profiles.go b/internal/profiles/profiles.goindex b9b63bd8..112d1bf1 100644--- a/internal/profiles/profiles.go+++ b/internal/profiles/profiles.go@@ -4,6 +4,7 @@ import ("fmt""io/fs""log/slog"+ "net/url""os""path/filepath""sort"@@ -12,6 +13,7 @@ import ("time""unicode"+ "github.com/pinchtab/pinchtab/internal/activity""github.com/pinchtab/pinchtab/internal/bridge""github.com/pinchtab/pinchtab/internal/ids")@@ -90,9 +92,9 @@ func isProfileNameValidationError(err error) bool {}type ProfileManager struct {- baseDir string- tracker *ActionTracker- mu sync.RWMutex+ baseDir string+ activity activity.Recorder+ mu sync.RWMutex}type ProfileMeta struct {@@ -121,10 +123,15 @@ func NewProfileManager(baseDir string) *ProfileManager {_ = os.MkdirAll(baseDir, 0755)return &ProfileManager{baseDir: baseDir,- tracker: NewActionTracker(),}}+func (pm *ProfileManager) SetActivityRecorder(rec activity.Recorder) {+ pm.mu.Lock()+ defer pm.mu.Unlock()+ pm.activity = rec+}+func (pm *ProfileManager) findProfileDirByName(name string) (string, error) {direct := filepath.Join(pm.baseDir, name)if info, err := os.Stat(direct); err == nil && info.IsDir() {@@ -484,15 +491,16 @@ func (pm *ProfileManager) Delete(name string) error {}func (pm *ProfileManager) RecordAction(profile string, record bridge.ActionRecord) {- pm.tracker.Record(profile, record)+ _ = profile+ _ = record}func (pm *ProfileManager) Logs(name string, limit int) []bridge.ActionRecord {- return pm.tracker.GetLogs(name, limit)+ return pm.logsFromActivity(name, limit)}func (pm *ProfileManager) Analytics(name string) bridge.AnalyticsReport {- return pm.tracker.Analyze(name)+ return analyticsFromActionRecords(pm.logsFromActivity(name, 1000))}func dirSizeMB(path string) float64 {@@ -510,6 +518,74 @@ func dirSizeMB(path string) float64 {return float64(total) / (1024 * 1024)}+func (pm *ProfileManager) logsFromActivity(name string, limit int) []bridge.ActionRecord {+ pm.mu.RLock()+ rec := pm.activity+ pm.mu.RUnlock()+ if rec == nil || !rec.Enabled() {+ return []bridge.ActionRecord{}+ }++ events, err := rec.Query(activity.Filter{+ ProfileName: name,+ Limit: limit,+ })+ if err != nil {+ return []bridge.ActionRecord{}+ }++ logs := make([]bridge.ActionRecord, 0, len(events))+ for _, evt := range events {+ logs = append(logs, bridge.ActionRecord{+ Timestamp: evt.Timestamp,+ Method: evt.Method,+ Endpoint: evt.Path,+ URL: evt.URL,+ TabID: evt.TabID,+ DurationMs: evt.DurationMs,+ Status: evt.Status,+ })+ }+ sort.Slice(logs, func(i, j int) bool {+ return logs[i].Timestamp.Before(logs[j].Timestamp)+ })+ if limit > 0 && len(logs) > limit {+ return logs[len(logs)-limit:]+ }+ return logs+}++func analyticsFromActionRecords(logs []bridge.ActionRecord) bridge.AnalyticsReport {+ report := bridge.AnalyticsReport{+ TotalActions: len(logs),+ CommonHosts: make(map[string]int),+ TopEndpoints: make(map[string]int),+ }++ last24h := time.Now().Add(-24 * time.Hour)+ for _, l := range logs {+ if l.Timestamp.After(last24h) {+ report.Last24h+++ }+ if l.URL != "" {+ u, err := url.Parse(l.URL)+ if err == nil && u.Host != "" {+ report.CommonHosts[u.Host]+++ }+ }+ if l.Endpoint != "" {+ report.TopEndpoints[l.Endpoint]+++ }+ }+ if len(report.TopEndpoints) == 0 {+ report.TopEndpoints = nil+ }+ if len(report.CommonHosts) == 0 {+ report.CommonHosts = map[string]int{}+ }+ return report+}+func (pm *ProfileManager) UpdateMeta(name string, meta map[string]string) error {pm.mu.Lock()defer pm.mu.Unlock()diff --git a/internal/profiles/profiles_test.go b/internal/profiles/profiles_test.goindex 8c9785af..513a145e 100644--- a/internal/profiles/profiles_test.go+++ b/internal/profiles/profiles_test.go@@ -12,6 +12,7 @@ import ("testing""time"+ "github.com/pinchtab/pinchtab/internal/activity""github.com/pinchtab/pinchtab/internal/bridge")@@ -306,29 +307,51 @@ func TestProfileManagerDelete(t *testing.T) {}}-func TestActionTracker(t *testing.T) {- at := NewActionTracker()- profName := fmt.Sprintf("prof-%d", time.Now().UnixNano())+func TestProfileManagerLogsAndAnalyticsUseActivityRecorder(t *testing.T) {+ pm := NewProfileManager(t.TempDir())+ store, err := activity.NewStore(t.TempDir(), 30*time.Minute, 1)+ if err != nil {+ t.Fatalf("NewStore: %v", err)+ }+ pm.SetActivityRecorder(store)+ profileName := fmt.Sprintf("prof-%d", time.Now().UnixNano())+ now := time.Now().UTC()for i := 0; i < 5; i++ {- at.Record(profName, bridge.ActionRecord{- Timestamp: time.Now().Add(time.Duration(i) * time.Second),- Method: "GET",- Endpoint: "/snapshot",- URL: "https://pinchtab.com",- DurationMs: 100,- Status: 200,- })+ if err := store.Record(activity.Event{+ Timestamp: now.Add(time.Duration(i) * time.Second),+ Source: "server",+ ProfileName: profileName,+ Method: "GET",+ Path: "/snapshot",+ URL: "https://pinchtab.com/page",+ DurationMs: 100,+ Status: 200,+ }); err != nil {+ t.Fatalf("Record: %v", err)+ }}- logs := at.GetLogs(profName, 3)+ logs := pm.Logs(profileName, 3)if len(logs) != 3 {- t.Errorf("expected 3 logs, got %d", len(logs))+ t.Fatalf("expected 3 logs, got %d", len(logs))+ }+ if logs[0].Endpoint != "/snapshot" {+ t.Fatalf("logs[0].Endpoint = %q, want /snapshot", logs[0].Endpoint)}- report := at.Analyze(profName)+ report := pm.Analytics(profileName)if report.TotalActions != 5 {- t.Errorf("expected 5 total actions, got %d", report.TotalActions)+ t.Fatalf("expected 5 total actions, got %d", report.TotalActions)+ }+ if report.Last24h != 5 {+ t.Fatalf("expected 5 last24h actions, got %d", report.Last24h)+ }+ if report.CommonHosts["pinchtab.com"] != 5 {+ t.Fatalf("CommonHosts = %#v, want pinchtab.com=5", report.CommonHosts)+ }+ if report.TopEndpoints["/snapshot"] != 5 {+ t.Fatalf("TopEndpoints = %#v, want /snapshot=5", report.TopEndpoints)}}diff --git a/internal/profiles/tracker.go b/internal/profiles/tracker.godeleted file mode 100644index d449c097..00000000--- a/internal/profiles/tracker.go+++ /dev/null@@ -1,121 +0,0 @@-package profiles--import (- "encoding/json"- "net/url"- "os"- "path/filepath"- "sync"- "time"-- "github.com/pinchtab/pinchtab/internal/bridge"-)--// userConfigDir returns the OS-appropriate app config directory.-// For backwards compatibility, if ~/.pinchtab exists and the new location-// doesn't, it returns ~/.pinchtab.-func userConfigDir() string {- h, _ := os.UserHomeDir()- legacyPath := filepath.Join(h, ".pinchtab")-- configDir, err := os.UserConfigDir()- if err != nil {- return legacyPath- }-- newPath := filepath.Join(configDir, "pinchtab")-- // Backwards compatibility: if legacy location exists and new doesn't, use legacy- if dirExists(legacyPath) && !dirExists(newPath) {- return legacyPath- }-- return newPath-}--// dirExists checks if a directory exists-func dirExists(path string) bool {- info, err := os.Stat(path)- if err != nil {- return false- }- return info.IsDir()-}--type ActionTracker struct {- logs map[string][]bridge.ActionRecord- mu sync.RWMutex-}--func NewActionTracker() *ActionTracker {- t := &ActionTracker{- logs: make(map[string][]bridge.ActionRecord),- }- _ = t.load()- return t-}--func (t *ActionTracker) Record(profile string, record bridge.ActionRecord) {- t.mu.Lock()- defer t.mu.Unlock()- t.logs[profile] = append(t.logs[profile], record)- if len(t.logs[profile]) > 1000 {- t.logs[profile] = t.logs[profile][len(t.logs[profile])-1000:]- }- _ = t.save()-}--func (t *ActionTracker) GetLogs(profile string, limit int) []bridge.ActionRecord {- t.mu.RLock()- defer t.mu.RUnlock()- logs := t.logs[profile]- if limit > 0 && len(logs) > limit {- return logs[len(logs)-limit:]- }- return logs-}--func (t *ActionTracker) Analyze(profile string) bridge.AnalyticsReport {- t.mu.RLock()- defer t.mu.RUnlock()- logs := t.logs[profile]-- report := bridge.AnalyticsReport{- TotalActions: len(logs),- CommonHosts: make(map[string]int),- }-- last24h := time.Now().Add(-24 * time.Hour)- for _, l := range logs {- if l.Timestamp.After(last24h) {- report.Last24h++- }- if l.URL != "" {- u, err := url.Parse(l.URL)- if err == nil && u.Host != "" {- report.CommonHosts[u.Host]++- }- }- }- return report-}--func (t *ActionTracker) save() error {- path := filepath.Join(userConfigDir(), "action_logs.json")- _ = os.MkdirAll(filepath.Dir(path), 0755)-- data, err := json.Marshal(t.logs)- if err != nil {- return err- }- return os.WriteFile(path, data, 0644)-}--func (t *ActionTracker) load() error {- path := filepath.Join(userConfigDir(), "action_logs.json")- data, err := os.ReadFile(path)- if err != nil {- return err- }- return json.Unmarshal(data, &t.logs)-}diff --git a/internal/scheduler/scheduler.go b/internal/scheduler/scheduler.goindex b7cc3314..5a6444eb 100644--- a/internal/scheduler/scheduler.go+++ b/internal/scheduler/scheduler.go@@ -407,7 +407,6 @@ func (s *Scheduler) executeTask(ctx context.Context, t *Task) (any, error) {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)diff --git a/internal/server/activity_recorder.go b/internal/server/activity_recorder.goindex d1f86058..a4d86449 100644--- a/internal/server/activity_recorder.go+++ b/internal/server/activity_recorder.go@@ -1,6 +1,9 @@package serverimport (+ "net/http"+ "strings"+"github.com/pinchtab/pinchtab/internal/activity""github.com/pinchtab/pinchtab/internal/dashboard")@@ -27,7 +30,7 @@ func (r dashboardActivityRecorder) Record(evt activity.Event) error {return err}}- if r.dash != nil {+ if r.dash != nil && shouldBroadcastDashboardActivity(evt) {r.dash.RecordActivityEvent(evt)}return nil@@ -39,3 +42,18 @@ func (r dashboardActivityRecorder) Query(filter activity.Filter) ([]activity.Eve}return r.base.Query(filter)}++func shouldBroadcastDashboardActivity(evt activity.Event) bool {+ if !strings.EqualFold(strings.TrimSpace(evt.Source), "orchestrator") {+ return true+ }+ if evt.Method != http.MethodGet {+ return true+ }+ switch evt.Path {+ case "/health", "/tabs", "/metrics":+ return false+ default:+ return true+ }+}diff --git a/internal/server/activity_recorder_test.go b/internal/server/activity_recorder_test.gonew file mode 100644index 00000000..1185eccc--- /dev/null+++ b/internal/server/activity_recorder_test.go@@ -0,0 +1,75 @@+package server++import (+ "net/http"+ "testing"+ "time"++ "github.com/pinchtab/pinchtab/internal/activity"+ "github.com/pinchtab/pinchtab/internal/dashboard"+)++type stubRecorder struct {+ events []activity.Event+}++func (s *stubRecorder) Enabled() bool {+ return true+}++func (s *stubRecorder) Record(evt activity.Event) error {+ s.events = append(s.events, evt)+ return nil+}++func (s *stubRecorder) Query(activity.Filter) ([]activity.Event, error) {+ return nil, nil+}++func TestDashboardActivityRecorderSkipsInternalOrchestratorMonitoringEvents(t *testing.T) {+ base := &stubRecorder{}+ dash := dashboard.NewDashboard(nil)+ rec := newDashboardActivityRecorder(base, dash)++ err := rec.Record(activity.Event{+ Timestamp: time.Now().UTC(),+ Source: "orchestrator",+ Method: http.MethodGet,+ Path: "/tabs",+ })+ if err != nil {+ t.Fatalf("Record() error = %v", err)+ }+ if len(base.events) != 1 {+ t.Fatalf("base recorder events = %d, want 1", len(base.events))+ }+ if len(dash.RecentEvents()) != 0 {+ t.Fatalf("dashboard recent events = %d, want 0", len(dash.RecentEvents()))+ }+}++func TestDashboardActivityRecorderBroadcastsNonMonitoringEvents(t *testing.T) {+ base := &stubRecorder{}+ dash := dashboard.NewDashboard(nil)+ rec := newDashboardActivityRecorder(base, dash)++ err := rec.Record(activity.Event{+ RequestID: "req-1",+ Timestamp: time.Now().UTC(),+ Source: "orchestrator",+ Method: http.MethodPost,+ Path: "/tabs/tab_1/navigate",+ AgentID: "agent-1",+ Status: http.StatusOK,+ DurationMs: 12,+ })+ if err != nil {+ t.Fatalf("Record() error = %v", err)+ }+ if len(base.events) != 1 {+ t.Fatalf("base recorder events = %d, want 1", len(base.events))+ }+ if len(dash.RecentEvents()) != 1 {+ t.Fatalf("dashboard recent events = %d, want 1", len(dash.RecentEvents()))+ }+}diff --git a/internal/server/bridge.go b/internal/server/bridge.goindex 79f4803c..bb6a32be 100644--- a/internal/server/bridge.go+++ b/internal/server/bridge.go@@ -35,7 +35,7 @@ func RunBridgeServer(cfg *config.RuntimeConfig, version string) {Enabled: cfg.Observability.Activity.Enabled,SessionIdle: time.Duration(cfg.Observability.Activity.SessionIdleSec) * time.Second,RetentionDays: cfg.Observability.Activity.RetentionDays,- }, cfg.StateDir)+ }, cfg.ActivityStateDir())if err != nil {slog.Error("activity store", "err", err)os.Exit(1)diff --git a/internal/server/server.go b/internal/server/server.goindex 0fd5fa22..ab81ead4 100644--- a/internal/server/server.go+++ b/internal/server/server.go@@ -79,14 +79,19 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {Enabled: cfg.Observability.Activity.Enabled,SessionIdle: time.Duration(cfg.Observability.Activity.SessionIdleSec) * time.Second,RetentionDays: cfg.Observability.Activity.RetentionDays,- }, cfg.StateDir)+ }, cfg.ActivityStateDir())if err != nil {slog.Error("activity store", "err", err)os.Exit(1)}+ profMgr.SetActivityRecorder(actStore)mux := http.NewServeMux()+ if err := dash.LoadPersistedAgentActivity(actStore); err != nil {+ slog.Warn("restore dashboard agent activity", "err", err)+ }+dash.RegisterHandlers(mux)configAPI.RegisterHandlers(mux)authAPI.RegisterHandlers(mux)@@ -94,6 +99,29 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {liveActivity := newDashboardActivityRecorder(actStore, dash)activity.RegisterHandlers(mux, liveActivity)+ syncCtx, syncCancel := context.WithCancel(context.Background())+ go func() {+ ticker := time.NewTicker(1 * time.Second)+ defer ticker.Stop()++ lastSync := time.Now().UTC().Add(-2 * time.Second)+ for {+ select {+ case <-syncCtx.Done():+ return+ case <-ticker.C:+ nextSync, err := dash.IngestPersistedAgentActivity(actStore, lastSync)+ if err != nil {+ slog.Warn("sync dashboard agent activity", "err", err)+ continue+ }+ if !nextSync.IsZero() {+ lastSync = nextSync.Add(-2 * time.Second)+ }+ }+ }+ }()+strategyName := cfg.Strategyif strategyName == "" {strategyName = "always-on"@@ -221,6 +249,7 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {if sched != nil {sched.Stop()}+ syncCancel()dash.Shutdown()orch.Shutdown()ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)diff --git a/scripts/check.sh b/scripts/check.shindex fd61a00a..624eaca4 100755--- a/scripts/check.sh+++ b/scripts/check.sh@@ -33,7 +33,9 @@ echo -e " ${INFO}Running pre-push checks (matches GitHub Actions CI)...${NC}"section "Format"-mapfile -t go_files < <(git ls-files -- '*.go')+mapfile -t go_files < <(git ls-files -- '*.go' | while read -r file; do+ [ -f "$file" ] && printf '%s\n' "$file"+done)unformatted=""if [ ${#go_files[@]} -gt 0 ]; thenunformatted=$(gofmt -l "${go_files[@]}")@@ -48,7 +50,7 @@ if [ -n "$unformatted" ]; thengofmt -w "${go_files[@]}"ok "gofmt (fixed)"else- hint "Run: gofmt -w \$(git ls-files -- '*.go')"+ hint "Run: gofmt -w \$(git ls-files -- '*.go' | while read -r file; do [ -f \"\$file\" ] && printf '%s\\n' \"\$file\"; done)"exit 1fielsediff --git a/skills/pinchtab/SKILL.md b/skills/pinchtab/SKILL.mdindex 2d980b66..b107582d 100644--- a/skills/pinchtab/SKILL.md+++ b/skills/pinchtab/SKILL.md@@ -31,6 +31,22 @@ Preferred tool surface:- Use `curl` for profile-management routes or non-shell/API fallback flows.- Use `jq` only when you need structured parsing from JSON responses.+## Agent Identity And Attribution++When multiple agents share one PinchTab server, always give each agent a stable ID.++- CLI flows: prefer `pinchtab --agent-id <agent-id> ...`+- long-running shells: set `PINCHTAB_AGENT_ID=<agent-id>`+- raw HTTP flows: send `X-Agent-Id: <agent-id>` on requests that should be attributed to that agent++That identity is recorded as `agentId` in activity events and powers:++- the dashboard Agents view+- `GET /api/activity?agentId=<agent-id>`+- scheduler task attribution when work is dispatched on behalf of an agent++If you are switching between unrelated browser tasks, do not reuse the same agent ID unless you intentionally want one combined activity trail.+## Safety Defaults- Default to `http://localhost` targets. Only use a remote PinchTab server when the user explicitly provides it and, if needed, a token.@@ -98,15 +114,15 @@ Use `&&` only when you do not need to inspect intermediate output before decidinGood:```bash-pinchtab nav https://example.com && pinchtab snap -i -c+pinchtab nav https://pinchtab.com && pinchtab snap -i -cpinchtab click --wait-nav e5 && pinchtab snap -i -c-pinchtab nav https://example.com --block-images && pinchtab text+pinchtab nav https://pinchtab.com --block-images && pinchtab text```Run commands separately when you must read the snapshot output first:```bash-pinchtab nav https://example.com+pinchtab nav https://pinchtab.compinchtab snap -i -c# Read refs, choose the correct e#pinchtab click e7@@ -172,7 +188,7 @@ Use a temporary instance for public pages, scraping, or tasks that do not need lpinchtab instance startpinchtab instances# Point CLI commands at the instance port you want to use.-pinchtab --server http://localhost:9868 nav https://example.com+pinchtab --server http://localhost:9868 nav https://pinchtab.compinchtab --server http://localhost:9868 text```@@ -235,6 +251,7 @@ curl -X POST http://localhost:9867/instances/start \-H "Content-Type: application/json" \-d '{"profileId":"work","mode":"headless"}'curl -X POST http://localhost:9868/action \+ -H "X-Agent-Id: agent-main" \-H "Content-Type: application/json" \-d '{"kind":"click","selector":"e5"}'```diff --git a/skills/pinchtab/references/agent-optimization.md b/skills/pinchtab/references/agent-optimization.mdindex 529b9409..1ebda434 100644--- a/skills/pinchtab/references/agent-optimization.md+++ b/skills/pinchtab/references/agent-optimization.md@@ -166,6 +166,7 @@ pinchtab nav <url> --block-images --timeout 60## General Efficiency Rules+- **Set a stable agent ID up front.** Use `pinchtab --agent-id <agent-id> ...`, `PINCHTAB_AGENT_ID`, or `X-Agent-Id` for raw HTTP calls so the dashboard Agents view and `/api/activity?agentId=...` stay attributable.- **Batch reads before writes.** Snap once, extract all refs, then act. Avoid snap → act → snap → act loops when you can snap → act × N → snap once to verify.- **Use `text` for extraction tasks.** If you only need to read content (not interact), `text` is cheaper than `snap` + parsing.- **Scope snapshots.** Use `snap -s <selector>` to target a specific section of the page when you know where the element is.diff --git a/skills/pinchtab/references/api.md b/skills/pinchtab/references/api.mdindex fa30c606..5c1d2b64 100644--- a/skills/pinchtab/references/api.md+++ b/skills/pinchtab/references/api.md@@ -4,6 +4,27 @@ Base URL for all examples: `http://localhost:9867`> **CLI alternative:** All endpoints have CLI equivalents. Use `pinchtab help` for the full list. Examples are shown as `# CLI:` comments below.+## Agent Attribution++If an agent is calling the HTTP API directly, include `X-Agent-Id: <agent-id>` on the requests that should show up under that agent in dashboard and activity views.++Example:++```bash+curl -X POST /navigate \+ -H 'X-Agent-Id: agent-crawl-01' \+ -H 'Content-Type: application/json' \+ -d '{"url": "https://pinchtab.com"}'++curl '/api/activity?agentId=agent-crawl-01'+```++Notes:++- CLI users should prefer `pinchtab --agent-id <agent-id> ...` instead of setting the header manually+- scheduler-submitted tasks reuse their `agentId` as `X-Agent-Id` when the task is executed+- bare `GET /api/activity` returns the primary activity feed; named internal sources such as `dashboard` or `orchestrator` are queried with `?source=<name>`+## Navigate```bashdiff --git a/skills/pinchtab/references/commands.md b/skills/pinchtab/references/commands.mdindex de9c403b..e9f77ce3 100644--- a/skills/pinchtab/references/commands.md+++ b/skills/pinchtab/references/commands.md@@ -29,10 +29,10 @@ Check if the server is running and healthy.Navigate the current tab to a URL.```bash-pinchtab nav https://example.com-pinchtab nav https://example.com --new-tab-pinchtab nav https://example.com --block-images-pinchtab nav https://example.com --timeout 60+pinchtab nav https://pinchtab.com+pinchtab nav https://pinchtab.com --new-tab+pinchtab nav https://pinchtab.com --block-images+pinchtab nav https://pinchtab.com --timeout 60```| Flag | Description |diff --git a/skills/pinchtab/references/env.md b/skills/pinchtab/references/env.mdindex e869e9a9..00e78a04 100644--- a/skills/pinchtab/references/env.md+++ b/skills/pinchtab/references/env.md@@ -17,7 +17,7 @@ Use the `--server` CLI flag instead of environment variables:```bashpinchtab --server http://192.168.1.50:9867 snap-pinchtab --server https://pinchtab.example.com snap+pinchtab --server https://pinchtab.com snap```## What is intentionally not listeddiff --git a/tests/manual/stealth-check.md b/tests/manual/stealth-check.mdindex 7f9a2317..29fdd07a 100644--- a/tests/manual/stealth-check.md+++ b/tests/manual/stealth-check.md@@ -80,7 +80,7 @@ Expected for this manual suite:curl -sf -H 'Authorization: Bearer live-test-token' \-H 'Content-Type: application/json' \http://127.0.0.1:9988/navigate \- -d '{"url":"https://example.com"}'+ -d '{"url":"https://pinchtab.com"}'```2. Wait for the page to settle.